How to get number of contours

I would like to determine the number of white areas in this picture. I tried this with the findContours function to solve where all surfaces are detected but i dont know how to get the number of all contours. I thought the number is in the hierarchy but the size of hierarchy is only 24 and there are 33 contours in the image.

This is the code is used:

vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
findContours( image, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE);


edit retag close merge delete

2

( 2019-10-28 16:46:21 -0500 )edit

if i use this command i get the number 1077

( 2019-10-28 16:49:37 -0500 )edit
1

( 2019-10-28 20:14:42 -0500 )edit

Sort by » oldest newest most voted

From the documentation:

C++: void findContours(InputOutputArray image, OutputArrayOfArrays contours, OutputArray hierarchy, int mode, int method, Point offset=Point())

contours – Detected contours. Each contour is stored as a vector of points.

hierarchy – Optional output vector, containing information about the image topology. It has as many elements as the number of contours. For each i-th contour contours[i] , the elements hierarchy[i][0] , hiearchy[i][1] , hiearchy[i][2] , and hiearchy[i][3] are set to 0-based indices in contours of the next and previous contours at the same hierarchical level, the first child contour and the parent contour, respectively. If for the contour i there are no next, previous, parent, or nested contours, the corresponding elements of hierarchy[i] will be negative.

So Hierarchies contains information about the image topology, and has the same number of elements as contours. Contours will contain all the detected contours. If contours isn't 30 but you expect it to be 30, then there is probably something going wrong beforehand. Why don't you try drawing the contours onto your image to see what is being detected?

more

( 2019-10-29 10:20:14 -0500 )edit

First thank you for the detailed answer. I have implemented your idea to draw the contours but apparently no contours are lost. There are still 33 but if i cout the size of contours the result is 24.

Mat drawing = Mat::zeros( image.size(), CV_8UC3 );

int idx = 0;
for( ; idx >= 0; idx = hierarchy[idx][0] )
{
drawContours( drawing, contours, idx, Scalar(0,0,255), 2, 8, hierarchy );
}

cout << sizeof(contours)<< endl;

( 2019-10-29 15:41:31 -0500 )edit