Ask Your Question
0

Get number of pixels within a contour

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

Heathcliff86 gravatar image

Hi,

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
2

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

Guanta gravatar image

If you can use OpenCV 3.0 then the solution could be to use the new connectedComponents functions, s. http://docs.opencv.org/trunk/d3/dc0/g... . It's not even much faster than findContours but gives you also the area.

edit flag offensive delete link more
0

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

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

Question Tools

1 follower

Stats

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

Seen: 7,047 times

Last updated: Mar 25 '15