Table of Contents
How to solve the problem of transparent image where the opencv.js projection transformation result is blank
Home Web Front-end JS Tutorial How to solve the problem that the result of OpenCV.js projection transformation is a blank transparent picture?

How to solve the problem that the result of OpenCV.js projection transformation is a blank transparent picture?

Apr 04, 2025 pm 03:45 PM
ai Solution click event

How to solve the problem of transparent image where the opencv.js projection transformation result is blank

When using opencv.js for image processing, sometimes you will encounter the problem of transparent images with blank image results after projection transformation. Here are the problems I encountered and the solutions.

When I was processing images, the code was able to successfully identify the four coordinates of the document, but when it came to the projection transformation step, the result was always blank transparent picture and there was no error. Here is part of the code for the projection transformation I used:

 // Projection transformation let srcquad = cv.matfromarray(4, 1, cv.cv_32fc2, points.flat());
let dstquad = cv.matfromarray(4, 1, cv.cv_32fc2, [0, 0, img.cols, 0, img.cols, img.rows, 0, img.rows]);
let transformx = cv.getperspectivetransform(srcquad, dstquad);
let target = new cv.mat();
cv.warpperspective(img, target, transmtx, new cv.size(img.cols, img.rows));
// Show the result cv.imshow(canvas, target);
Copy after login

To solve this problem, I made the following improvements:

  1. Set the canvas size : After the image is loaded, that is, in the imgelement.onload function, set the width and height of the canvas to be consistent with the image size.
  2. Add error handling : When the image loading fails, that is, in the imgelement.onerror function, add error handling to capture image loading errors.

Here is the complete code improved:

 

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>OpenCV.js Example</title>


    <script async src="https://docs.opencv.org/4.5.5/opencv.js" onload="onOpenCvReady();"></script>
    <canvas id="canvasOutput"></canvas>
    <script>
        function onOpenCvReady() {
            console.log("OpenCV.js loading is completed.");
            processImage();
        }

        function sleep(ms) {
            return new Promise(resolve => setTimeout(resolve, ms));
        }

        async function processImage() {
            await sleep(3000); // Wait for 3 seconds let imageUrl = "../archives/111.jpg";
            let imgElement = new Image();
            imgElement.src = imageUrl;
            var img;

            // Load the image imgElement.onload = function() {
                try {
                    img = cv.imread(imgElement);
                    if (img.empty()) {
                        console.error("Image could not be read.");
                        return;
                    }

                    // Get the canvas element and set the size let canvas = document.getElementById(&#39;canvasOutput&#39;);
                    canvas.width = img.cols;
                    canvas.height = img.rows;

                    // Reset image size let dsize = new cv.Size(img.cols, img.rows);
                    let dst = new cv.Mat();
                    cv.resize(img, dst, dsize, 0, 0, cv.INTER_AREA);

                    // Convert to grayscale image console.log("Before conversion:", img);
                    let gray = new cv.Mat(); // Create a new Mat object to store the grayscale image cv.cvtColor(dst, gray, cv.COLOR_BGR2GRAY); // Use appropriate conversion console.log("After conversion:", gray);

                    // Gaussian filter cv.GaussianBlur(gray, gray, new cv.Size(11, 11), 0, 0);
                    cv.imshow(canvas, gray);
                    cv.Canny(gray, gray, 20, 50, 3);

                    let contours = new cv.MatVector();
                    let hierarchy = new cv.Mat();
                    cv.findContours(gray, contours, hierarchy, cv.RETR_CCOMP, cv.CHAIN_APPROX_NONE);

                    let index = 0, maxArea = 0;
                    const area = img.cols * img.rows;
                    for (let i = 0; i < contours.size(); i) {
                        let tempArea = Math.abs(cv.contourArea(contours.get(i)));
                        if (tempArea > maxArea && tempArea > 0.3 * area) {
                            index = i;
                            maxArea = tempArea;
                        }
                    }

                    if (maxArea === 0) return;
                    const foundContour = contours.get(index);
                    const arcL = cv.arcLength(foundContour, true);
                    let approx = new cv.Mat();

                    // Approximate polygon cv.approxPolyDP(foundContour, approx, 0.01 * arcL, true);

                    if (approx.total() === 4) {
                        let points = [];
                        const data32S = approx.data32S;
                        for (let i = 0, len = data32S.length / 2; i < len; i ) {
                            points[i] = {x: data32S[i * 2], y: data32S[i * 2 1]};
                        }
                        console.log("Quadrilateral point detected:", points);

                        // Projection transform let srcQuad = cv.matFromArray(4, 1, cv.CV_32FC2, points.flat());
                        let dstQuad = cv.matFromArray(4, 1, cv.CV_32FC2, [0, 0, img.cols, 0, img.cols, img.rows, 0, img.rows]);
                        let transformtx = cv.getPerspectiveTransform(srcQuad, dstQuad);
                        let target = new cv.Mat();
                        cv.warpPerspective(img, target, transmtx, new cv.Size(img.cols, img.rows));

                        // Show the result cv.imshow(canvas, target);

                        // Create a temporary canvas element let tempCanvas = document.createElement(&#39;canvas&#39;);
                        tempCanvas.width = target.cols;
                        tempCanvas.height = target.rows;
                        let tempCtx = tempCanvas.getContext(&#39;2d&#39;);

                        // Convert cv.Mat to ImageData
                        let imageData = new ImageData(new Uint8ClampedArray(target.data), target.cols, target.rows);

                        // Draw ImageData on temporary canvas tempCtx.putImageData(imageData, 0, 0);

                        // Generate canvas to Blob object tempCanvas.toBlob((blob) => {
                            // Create a URL object let url = URL.createObjectURL(blob);
                            // Create an element a and set its attribute let a = document.createElement(&#39;a&#39;);
                            a.href = url;
                            a.download = &#39;processed_image.png&#39;; // Set the name of the download file // Add the a element to the body document.body.appendChild(a);
                            // Trigger the click event to start downloading a.click();
                            // Remove the a element document.body.removeChild(a);
                            // Release URL object URL.revokeObjectURL(url);
                        }, &#39;image/png&#39;);

                        // Free memory target.delete(); // Free target here, otherwise memory leaks}

                    // Free memory img.delete();
                    dst.delete();
                    gray.delete(); // Release grayscale image Mat
                    contours.delete();
                    hierarchy.delete();
                    approx.delete();
                    foundContour.delete();
                } catch (err) {
                    console.error("Image processing error:", err);
                }
            }

            imgElement.onerror = function() {
                console.error("Image could not be loaded.");
            };
        }
    </script>

Copy after login

Through the above improvements, I successfully solved the problem that the result of the projection transformation is a blank transparent picture. Hope these improvements will be helpful to everyone.

The above is the detailed content of How to solve the problem that the result of OpenCV.js projection transformation is a blank transparent picture?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Unable to log in to mysql as root Unable to log in to mysql as root Apr 08, 2025 pm 04:54 PM

The main reasons why you cannot log in to MySQL as root are permission problems, configuration file errors, password inconsistent, socket file problems, or firewall interception. The solution includes: check whether the bind-address parameter in the configuration file is configured correctly. Check whether the root user permissions have been modified or deleted and reset. Verify that the password is accurate, including case and special characters. Check socket file permission settings and paths. Check that the firewall blocks connections to the MySQL server.

Navicat's solution to the database cannot be connected Navicat's solution to the database cannot be connected Apr 08, 2025 pm 11:12 PM

The following steps can be used to resolve the problem that Navicat cannot connect to the database: Check the server connection, make sure the server is running, address and port correctly, and the firewall allows connections. Verify the login information and confirm that the user name, password and permissions are correct. Check network connections and troubleshoot network problems such as router or firewall failures. Disable SSL connections, which may not be supported by some servers. Check the database version to make sure the Navicat version is compatible with the target database. Adjust the connection timeout, and for remote or slower connections, increase the connection timeout timeout. Other workarounds, if the above steps are not working, you can try restarting the software, using a different connection driver, or consulting the database administrator or official Navicat support.

Can mysql return json Can mysql return json Apr 08, 2025 pm 03:09 PM

MySQL can return JSON data. The JSON_EXTRACT function extracts field values. For complex queries, you can consider using the WHERE clause to filter JSON data, but pay attention to its performance impact. MySQL's support for JSON is constantly increasing, and it is recommended to pay attention to the latest version and features.

Understand ACID properties: The pillars of a reliable database Understand ACID properties: The pillars of a reliable database Apr 08, 2025 pm 06:33 PM

Detailed explanation of database ACID attributes ACID attributes are a set of rules to ensure the reliability and consistency of database transactions. They define how database systems handle transactions, and ensure data integrity and accuracy even in case of system crashes, power interruptions, or multiple users concurrent access. ACID Attribute Overview Atomicity: A transaction is regarded as an indivisible unit. Any part fails, the entire transaction is rolled back, and the database does not retain any changes. For example, if a bank transfer is deducted from one account but not increased to another, the entire operation is revoked. begintransaction; updateaccountssetbalance=balance-100wh

The primary key of mysql can be null The primary key of mysql can be null Apr 08, 2025 pm 03:03 PM

The MySQL primary key cannot be empty because the primary key is a key attribute that uniquely identifies each row in the database. If the primary key can be empty, the record cannot be uniquely identifies, which will lead to data confusion. When using self-incremental integer columns or UUIDs as primary keys, you should consider factors such as efficiency and space occupancy and choose an appropriate solution.

Master SQL LIMIT clause: Control the number of rows in a query Master SQL LIMIT clause: Control the number of rows in a query Apr 08, 2025 pm 07:00 PM

SQLLIMIT clause: Control the number of rows in query results. The LIMIT clause in SQL is used to limit the number of rows returned by the query. This is very useful when processing large data sets, paginated displays and test data, and can effectively improve query efficiency. Basic syntax of syntax: SELECTcolumn1,column2,...FROMtable_nameLIMITnumber_of_rows;number_of_rows: Specify the number of rows returned. Syntax with offset: SELECTcolumn1,column2,...FROMtable_nameLIMIToffset,number_of_rows;offset: Skip

Can mysql store arrays Can mysql store arrays Apr 08, 2025 pm 05:09 PM

MySQL does not support array types in essence, but can save the country through the following methods: JSON array (constrained performance efficiency); multiple fields (poor scalability); and association tables (most flexible and conform to the design idea of ​​relational databases).

How to optimize MySQL performance for high-load applications? How to optimize MySQL performance for high-load applications? Apr 08, 2025 pm 06:03 PM

MySQL database performance optimization guide In resource-intensive applications, MySQL database plays a crucial role and is responsible for managing massive transactions. However, as the scale of application expands, database performance bottlenecks often become a constraint. This article will explore a series of effective MySQL performance optimization strategies to ensure that your application remains efficient and responsive under high loads. We will combine actual cases to explain in-depth key technologies such as indexing, query optimization, database design and caching. 1. Database architecture design and optimized database architecture is the cornerstone of MySQL performance optimization. Here are some core principles: Selecting the right data type and selecting the smallest data type that meets the needs can not only save storage space, but also improve data processing speed.

See all articles