How to find contour vertices in JS? Editing/Understanging FindContours Points in JS

asked 2019-02-11 08:50:16 -0600

Lucy8 gravatar image

I want to draw a small circle in each vertex of the largest contour. I successfully found the largest contour but how to find the highest points on it?

I saw this example and this is exactly what I want to do but the answer is for c++. How to do this in JS? I've tried to write in JS but no success. Here is the simplified code that I wrote

const contours = new cv.MatVector();
const hierarchy = new cv.Mat();
cv.findContours(src, contours, hierarchy, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE);

const contoursSize = contours.size();

const contoursToDraw = new cv.MatVector();

for (let i = 0; i < contoursSize; ++i) {
const cnt = contours.get(i);

const cntSize = cnt.size().width * target.size().height;
for (let j = 0; j < cntSize; j++)
    const [x, y] = cnt.charPtr(j); //cnt[j] -> ?
    const vertex = { x, y };
    console.log('vertex', vertex);
    cv.putText(cnt,'some text', vertex, cv.FONT_HERSHEY_SIMPLEX,1, [255, 0, 255, 255]);, vertex, 3, [0, 255, 0, 255], cv.FILLED);


Then drawing contours on image and showing image.

What is the equivalent of ctr[i][j] in javascript? In general, if we have some Mat object

const imgElement = document.querySelector('#imageSrc');
const src = cv.imread(imgElement);

how access to its points coordinates?

edit retag flag offensive close merge delete



can't completely answer, but contours are usually lists of int32 points, so your cnt.charPtr(j) looks wrong

berak gravatar imageberak ( 2019-02-11 09:07:51 -0600 )edit

After your comment, I've tried intPtr instead of charPtr

const [x, y] = cnt.intPtr(j);

and now it's work, thank you!! Is there a way to find how much these points are far from the vertical and horizontal edges?

Lucy8 gravatar imageLucy8 ( 2019-02-12 01:16:29 -0600 )edit

^^ i'm glad to hear that !

how much these points are far from the vertical and horizontal edges?

the edges of what ? the image borders ? isn't that already in the coords ? e.g. dist to the bottom is img.rows-y

berak gravatar imageberak ( 2019-02-12 01:30:36 -0600 )edit

Yes, I mean from the image borders and again you are right img.rows-y is what I need, thanks!!

Lucy8 gravatar imageLucy8 ( 2019-02-12 01:48:06 -0600 )edit