Reputation: 669
I want to calculate area of detected object (that blue marker I used) inside actual ROI. I mean one of those two rectangles that are my Regions Of Interest in Threshold image (which is black and white).
How to calculate area of object (I think - sum of "recognized" cluster of pixels, which are white color) inside ROI?
I just want to consider only those pixels that are inside of concrete ROI (in below example - the left one). So all pixels beyond left ROI will not be taken into calculations.
ROIs are created like this:
rectangle( imgOriginal, Point( 20, 100 ), Point( 170, 250), Scalar( 0, 0, 255 ), +5, 4 );
rectangle( imgThresholded, Point( 20, 100 ), Point( 170, 250), Scalar( 255, 255, 255 ), +5, 4 );
rectangle( imgOriginal, Point( 450, 100 ), Point( 600, 250), Scalar( 0, 0, 255 ), +5, 4 );
rectangle( imgThresholded, Point( 450, 100 ), Point( 600, 250), Scalar( 255, 255, 255 ), +5, 4 );
Upvotes: 1
Views: 4301
Reputation: 9407
So technically you found the "largest contour" based on some color filtering, drew a rectangle around it and trying now to get its area. To get its area, OpenCv provided the function for you (How did it find that it's the largest?) so here is the function: double cv::contourArea(InputArray contour)
Here is the main page because I think you can send the contour as it is but I am not sure but check this basic example and :
vector<Point> contour;
contour.push_back(Point2f(0, 0)); // push whatever points you want
contour.push_back(Point2f(10, 0));
contour.push_back(Point2f(10, 10));
contour.push_back(Point2f(5, 4));
double area0 = contourArea(contour); // retrieve the area
vector<Point> approx;
approxPolyDP(contour, approx, 5, true);
double area1 = contourArea(approx);
cout << "area0 =" << area0 << endl <<
"area1 =" << area1 << endl <<
"approx poly vertices" << approx.size() << endl;
Upvotes: 0
Reputation: 2154
You may use cv::countNonZero
function to count non-zero pixels inside ROI in imgThresholded
image. This is exactly what you need.
cv::Rect leftROI(cv::Point(20, 100), cv::Point(170, 250));
int leftArea = cv::countNonZero(imgThresholded(leftROI));
Upvotes: 3
Reputation: 761
For specific ROI on a binary image, sweep through pixel values and count the white (255) ones. If you have more ROIs, and want to avoid those, not containing white pixels, then simply skip those, that does not contain any white pixels...
Upvotes: 0