How to get individual contours (and fill them) in OpenCV?

I try to separate the contours of the image (to find homogeneous areas), so I applied cvCanny and then cvFindContours, then I use the following code to draw 1 outline every time I press a key:

for( ; contours2 != 0; contours2 = contours2->h_next ){ cvSet(img6, cvScalar(0,0,0)); CvScalar color = CV_RGB( rand()&255, rand()&255, rand()&255 ); cvDrawContours(img6, contours2, color, cvScalarAll(255), 100); //cvFillConvexPoly(img6,(CvPoint *)contours2,sizeof (contours2),color); area=cvContourArea(contours2); cvShowImage("3",img6); printf(" %d", area); cvWaitKey(); } 

But in the first iteration, he draws ALL contours, in the second he draws ALL except one, the third draws everything except two, etc.

And if I use the cvFillConvexPoly function, it fills most of the screen (although, as I wrote this, I realized that a convex polygon will not work for me, I only need to fill the contour of the contour)

So, how can I take only 1 path in each iteration of for instead of all the other paths?

Thanks.

+6
source share
1 answer

You need to change the last parameter that you pass to the function, which is currently 100 , by 0 or a negative value, depending on whether you want to draw child elements.

According to the documentation ( http://opencv.willowgarage.com/documentation/drawing_functions.html#drawcontours ) the function has the following signature:

 void cvDrawContours(CvArr *img, CvSeq* contour, CvScalar external_color, CvScalar hole_color, int max_level, int thickness=1, int lineType=8) 

Of the same documents, max_level has the following purpose (the most applicable part is highlighted in bold):

max_level - maximum level for drawn outlines. If 0, only the contour is drawn . If 1, the circuit and all circuits following it at the same level. If 2, all circuits are next and all circuits are one level below circuits, etc. If the value is negative, the function does not draw the contours following the path, but draws the child's contours of the path to $ | \ texttt {max_ level} | -1 $ level.

Edit:

To fill the path, use a negative value for the thickness parameter:

Thickness - The thickness of the lines on which the contours are drawn. If it is negative (e.g. = CV_FILLED), contour interiors are drawn.

+12
source

All Articles