首先使用你的四个坐标创建一个遮罩图像。
现在,使用Mat::copyTo()将你的黑色图像复制到源图像中,你可以使用上面的遮罩。
为源大小分配黑色图像和遮罩。
Mat src=imread("img.png",1);
Mat black(src.rows, src.cols, src.type(), cv::Scalar::all(0));
Mat mask(src.rows, src.cols, CV_8UC1, cv::Scalar(0));
现在使用
drawContours创建蒙版图像,这里应该使用CV_FILLED作为轮廓厚度。
例如:
vector< vector<Point> > co_ordinates;
co_ordinates.push_back(vector<Point>());
co_ordinates[0].push_back(P1);
co_ordinates[0].push_back(P2);
co_ordinates[0].push_back(P3);
co_ordinates[0].push_back(P4);
drawContours( mask,co_ordinates,0, Scalar(255),CV_FILLED, 8 );
最后使用上述掩码将黑色图像复制到源图像。
black.copyTo(src,mask);
请看下面的结果:
请查看以下的结果:
编辑:
根据您下面的留言,这里是您需要遵循的步骤:
First create Mask image as described above
Copy the the source image to new Mat dst1 using the mask.
Invert your mask and copy destination image to a new Mat dst2
For final result just add up dest1 and dest2 to new Mat.
Suppose you already created mask as above
Copy source to new Mat
Mat dst1;
src.copyTo(dst1,mask);
现在反转掩膜,并将目标图像复制到新 Mat 中。
Mat dst2;
bitwise_not(mask,mask);
dst.copyTo(dst2,mask);
通过将两者相加得到最终结果
Mat result=dest1+dest2;
如果你的两张图片尺寸不同,可以使用以下代码:
在这里,您应该使用图像 ROI 进行复制、创建掩模等操作。
![Mat src=imread("src.png",1);
Mat dst=imread("dest.jpg",1);
int new_w=0;
int new_h=0;
if(src.cols>dst.cols)
new_w=dst.cols;
else
new_w=src.cols;
if(src.rows>dst.rows)
new_h=dst.rows;
else
new_h=src.rows;
Rect rectROI(0,0,new_w,new_h);
Mat mask(new_h, new_w, CV_8UC1, cv::Scalar(0));
Point P1(107,41);
Point P2(507,61);
Point P3(495,280);
Point P4(110,253);
vector< vector<Point> > co_ordinates;
co_ordinates.push_back(vector<Point>());
co_ordinates\[0\].push_back(P1);
co_ordinates\[0\].push_back(P2);
co_ordinates\[0\].push_back(P3);
co_ordinates\[0\].push_back(P4);
drawContours( mask,co_ordinates,0, Scalar(255),CV_FILLED, 8 );
Mat srcROI=src(rectROI);
Mat dstROI=dst(rectROI);
Mat dst1;
Mat dst2;
srcROI.copyTo(dst1,mask);
imwrite("dst1.jpg",dst1);
bitwise_not(mask,mask);
dstROI.copyTo(dst2,mask);
dstROI.setTo(0);
dstROI=dst1+dst2;
imshow("final result",dst);][4]