Ask Your Question

Get number of pixels within a contour

asked 2015-03-25 05:23:05 -0500

Heathcliff86 gravatar image


I am looking for an efficient way to get the number of pixels within a contour.

cv::contourArea is not suited, as explained in this question. For instance, if I have a single-pixel contour, the output should be 1 (cv::contourArea outputs 0). If I have a 2-pixels wide square, the output should be 4 (cv::contourArea outputs 1), and so on.

One easy (but inefficient) solution would be to use cv::drawContour and count the number of non-zero pixels. Considering I have to do this for millions of contours, this will perform bad.

Am I missing other suitable solutions, maybe involving some manipulation of contour points or other OpenCV functions?

Thank you in advance, Alessandro

edit retag flag offensive close merge delete

2 answers

Sort by ยป oldest newest most voted

answered 2015-03-25 10:16:58 -0500

Guanta gravatar image

If you can use OpenCV 3.0 then the solution could be to use the new connectedComponents functions, s. . It's not even much faster than findContours but gives you also the area.

edit flag offensive delete link more

answered 2017-05-17 04:05:54 -0500

Fadwa gravatar image

You can do that using the vector size. The output of findContours is stored in a vector, use iterators to loop on it and get the size. I am using opencv2.4

cv::findContours(inImg, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
std::vector<std::vector<cv::Point> >::iterator iteratorContours = contours.begin(); 
while (iteratorContours != contours.end()) {
cout << iteratorContours.size();
edit flag offensive delete link more
Login/Signup to Answer

Question Tools

1 follower


Asked: 2015-03-25 05:23:05 -0500

Seen: 3,868 times

Last updated: Mar 25 '15