Reputation: 73
Lets say I was given a boundingRect based on some points and stored it into a Rect object.
How can I use those points and create a mask in openCV? that is, everything outside the bounding rectangle is masked (or set white)
I've tried several different methods and was able to get it to work using a convexHull and fillign with a polygon but can't seem to get it to work with the boundingRect
Upvotes: 2
Views: 5356
Reputation: 50667
You can call fillConvexPoly()
by passing the four end points of the bounding Rect
.
// assume all four end points are stored in "vector<Point> roi_vertices" already
// the order of the vertices don't matter
Mat mask = Mat(height, width, CV_8UC1, Scalar(0));
// Create Polygon from vertices
vector<Point> roi_poly;
approxPolyDP(roi_vertices, roi_poly, 1.0, true);
// Fill polygon white
fillConvexPoly(mask, &roi_poly[0], (int)roi_poly.size(), 255, 8, 0);
P.S.: the above method will also work for generating masks for any (convex) polygons.
Upvotes: 5
Reputation: 14053
Draw your rectangle with CV_FILLED option and invert it, like
Rect boundRect(x,y,W,H);
Mat mask(rows,cols,CV_8UC1,Scalar(0));
rectangle(mask,boundRect,Scalar(255),CV_FILLED,8,0);
bitwise_not(mask,mask);
or in another way without using invert, just create a white image and then draw rectangle using CV_FILLED option but with black color(Scalar(0)).
That is
Rect boundRect(x,y,W,H);
Mat mask(rows,cols,CV_8UC1,Scalar(255));
rectangle(mask,boundRect,Scalar(255),CV_FILLED,8,0);
Upvotes: 1