Home > Enterprise >  Uncaught TypeError: Cannot convert "undefined" to int in Opencv.js
Uncaught TypeError: Cannot convert "undefined" to int in Opencv.js

Time:07-17

I am trying to detect document from an image locally by uploading from input file. To detect those followed steps available online by adding grayscale and blur to image and canny edge now when trying to find contours it's giving error.

Error when drawing contour

Also, when I tried the steps through console it ran perfectly without giving any errors. Any idea why this is happening?

Console commands

Here is my full code:

function fileLoad(input) {
  if (input.files && input.files[0]) {
    let reader = new FileReader();
    reader.onload = (e) => {
      document.getElementById('ip').src = e.target.result;
    }

    reader.readAsDataURL(input.files[0]);
  }

}

function drawContours() {
  let org_img = cv.imread('ip');
  let img = new cv.Mat();

  // change color and adding gaussian blur

  cv.cvtColor(org_img, img, cv.COLOR_RGBA2GRAY, 0);
  cv.GaussianBlur(img, img, new cv.Size(5, 5), 0, 0, cv.BORDER_DEFAULT);

  console.log('chnage color and blur added');

  // canny edge

  cv.Canny(img, img, 75, 200, 3, false);

  console.log('canny done');

  // find contours
  console.log('init draw', img);

  let con = new cv.MatVector() ;
  cv.findContours(img, con, new cv.Mat(), cv.RETR_CCOMP, cv.CHAIN_APPPROX_SIMPLE);

  console.log('contours found', con);

  cv.drawContours(org_img, con, -1, new cv.Scalar(125, 120, 20), 1, cv.LINE_8, new cv.Mat(), 100);

  // for(let i=0; i< con.size(); i  ){
  //     cv.drawContours(org_img, con, i, new cv.Scalar(125,100,20), 1, cv.LINE_8, new cv.Mat(), 100) ;
  // }

  console.log('finish draw');

  cv.imshow('op', org_img);
}

function ready() {
  cv['onRuntimeInitialized'] = () => {
    console.log('opencv loaded');
    // init() ;
  }
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    function ready() {
  cv['onRuntimeInitialized'] = () => {
    //console.log('opencv loaded');
  }
}
  </script>
  <input type="file" accept="image/jpeg" onchange="fileLoad(this);" style="display: block;">
  <img id="ip" width="300" height="400" />
  <canvas width="300" height="400" id="op"></canvas>

  <button onclick="drawContours()">draw contour</button>
  <script asnyc src="https://docs.opencv.org/4.6.0/opencv.js" onl oad="ready()"></script>
</body>

</html>

CodePudding user response:

As suggested by @Shrimp I wrote cv.CHAIN_APPROX_SIMPLE with cv.CHAIN_APPPROX_SIMPLE so that's why error is for argument having undefined.

  • Related