# not rect ROI defined by 4 points

Hi, I would use the method countNonZero (InputArray src) on a ROI of my image; The ROI is not a rect, but it's defined by the points A, B, C, D like the red zone in the figure.

How can I use this method on this ROI? edit retag close merge delete

Sort by » oldest newest most voted

One possible solution

Mat image = imread("ball.jpg", 0);
threshold(image, image, 127, 255, THRESH_BINARY);

Point a = Point(image.cols, 20);
Point b = Point(image.cols, 50);
Point c = Point(image.cols/2, image.rows);
Point d = Point(image.cols/2+50, image.rows);
vector<Point> points;
points.push_back(a);
points.push_back(b);
points.push_back(c);
points.push_back(d);

//Find the corresponding ROI based on the poitns
convexHull(points, points);                         //to assure correct point order
Mat roi(image.rows, image.cols, CV_8U, Scalar(0));  //black image
fillConvexPoly(roi, points, Scalar(255));           //draw ROI in white

//Filter original image according to ROI
Mat filtered_image;
image.copyTo(filtered_image, roi);          //alternative: bitwise_and(image, roi, filtered_image);
int non_zero = countNonZero(filtered_image);

more

@LorenaGdL really good trick use of convexHull to assure correct point order, +1!

This solution works fine, but I have to store points after convexhull in a different vector. Adding:

cerr << "A " << points.at(0).x << " - " << points.at(0).y << endl;
cerr << "B " << points.at(1).x << " - " << points.at(1).y << endl;
cerr << "C " << points.at(2).x << " - " << points.at(2).y << endl;
cerr << "D " << points.at(3).x << " - " << points.at(3).y << endl;


Before and after convexhull i have:

A 300 - 50 B 300 - 20 C 150 - 300 D 200 - 300

A 300 - 50 B 200 - 300 C 150 - 300 D 200 - 300

And the point (300,20) disappear. With:

 vector<Point> points2;

//Find the corresponding ROI based on the poitns
convexHull(points, points2);                         //to assure correct point order


It all works fine!

Thank you

convexHull(points, points); this code may give wrong results because convexHull() is not suitable for inplace usage now. i think it's the time for feature request.

Official site

GitHub

Wiki

Documentation