Reputation: 861
Given a contour, what is the efficient way of counting the pixels that belong inside the contour?
I tried using opencv function
cv::pointPolygonTest()
but the function is highly inefficient and takes a lot of time for bigger contours.
Please advice
Upvotes: 1
Views: 6820
Reputation: 1197
If contourArea
doesn't give you expected result, you can follow this approach:
Apply countNonZero
on the new submatrix and you will get the number of non-black pixel
//1. Copy the contour in a new empty Mat
Rect cRect = boundingRect(*it); //it is an iterator for your contours vector
Mat subImg = dilatedImg(cRect);
double cArea = countNonZero(subImg);
Note: if you doesn't have a binary image, you may need to threshold it before to count only the right pixels.
Upvotes: 1
Reputation: 12514
I think you could have a simple recursive traversal that fills the area started from a single contour point. It will be efficient if it goes col-first I think so you can use the row iterator.
If you care about efficiency the most, you can perhaps unroll the recursion into loops and do for-unlooping.
Upvotes: 0
Reputation: 20058
I suppose you have extracted the contours with the findContours()
function.
Then, you can use the contourArea()
directly.
cout << Contour area is << contourArea(contours[k]) ;
Upvotes: 1