OpenCV: How to create a mask in the shape of a polygon?

Abs picture Abs · Apr 17, 2017 · Viewed 7.5k times · Source

I have a list of points which are the vertices of a polygon, like this:

std::vector<cv::Point2d> polygonPoints;

I need to create a mask for the goodFeaturesToTrack function in openCV. For a rectangle, the easiest way to fill the desired area with 1's is like this:

cv::Mat mask = cv::Mat::zeros(img.rows, img.cols, CV_8U);
mask(boundingbox) = 1;

How do I do this with a polygon that has 10+ edges? Is there an equivalent solution for n-sided polygons?

Answer

Abs picture Abs · Apr 17, 2017

Managed to find an answer that works!

cv::Mat mask = cv::Mat::zeros(img->rows, img->cols, CV_8U);
cv::Point pts[5] = {
    cv::Point(1, 6),
    cv::Point(2, 7),
    cv::Point(3, 8),
    cv::Point(4, 9),
    cv::Point(5, 10)
};
cv::fillConvexPoly( mask, pts, 5, cv::Scalar(1) );