Home > OS >  Is there any way of converting OpenCV.Mat to array in JavaScript?
Is there any way of converting OpenCV.Mat to array in JavaScript?

Time:06-09

I'm working on Mat in OpenCV. However, I need to manually calculate the Mat by myself. Is there is a way of accessing Mat likes 2D array?

const myMat = cv.matFromArray(cv, 3, 3, cv.CV_64F, [
      [1, 2, 3],
      [4, 5, 6],
      [7, 8, 9],
    ])
const newMat = someProcessThatReturnMat(myMat)

/* OpenCV in JS cannot access Mat like this */
const result = someProcess(newMat[1][2], newMat[2][0])

Thank you in advance

Updated: The problem is cv.matFromArray cannot convert 2D array to Mat. You have to use it as 1D array. That's why it never return the correct values. For example:

const myMat = cv.matFromArray(3, 3, cv.CV_64F, [1,2,3,4,5,6,7,8,9])

And then, you can access the value

const value = myMat.doubleAt(1, 2) // row 1, col 2

CodePudding user response:

You need to use the doubleAt(y,x) method.

It's double because the mat's content is CV_64F, not because you want doubles.

You can also use .data64F to access a flat Float64Array of the Mat's data.

OpenCV.js is... rough. It originated from someone's Google Summer of Code and hasn't received significant care since. Documentation amounts to some tutorials; API docs seem to be missing entirely. The "Mat" interface emulated the at() method from C , badly, instead of looking at numpy (python) or making this access feel "native" to javascript. Overloading the [] operator is possible using a Proxy but that was not implemented.

Here's an example: https://docs.opencv.org/4.x/de/d06/tutorial_js_basic_ops.html

Feel free to browse OpenCV's issues and maybe suggest some improvements.

  • Related