给出区域轮廓点集,通过drawContours
函数填充区域,生成mask掩模,然后利用copyTo得到剪裁图像。
注意:这些轮廓的点的坐标必须是int型的,利用perspectiveTransform得到的物体轮廓坐标不是整形,必须转成整型才可以利用drawContours得到mask掩模。否则会有很多的Assertion错误。
主要代码
#include<iostream>
#include<opencv2\opencv.hpp>
using namespace std;
using namespace cv;
int main()
{
Mat src = imread("F:/testdata/input.png");
Mat mask = Mat::zeros(src.size(), CV_8UC1);
Mat dst;
vector<vector<Point2i>> contours;
vector<Point2i> points;
points.push_back(Point2i(100, 100));
points.push_back(Point2i(50, 150));
points.push_back(Point2i(100, 200));
points.push_back(Point2i(200, 200));
points.push_back(Point2i(220, 150));
points.push_back(Point2i(200, 100));
contours.push_back(points);
drawContours(mask, contours, 0, Scalar::all(255), -1);
imshow("src", src);
src.copyTo(dst, mask);
imshow("dst", dst);
waitKey(0);
return 0;
}