复制非矩形ROI OpenCV

11
我想用C++ OpenCV复制一个不是矩形的图像部分。已知该部分的角点在图像中。我希望将它粘贴到另一张图像上的确切位置。请问有谁可以帮助我?
源图像和目标图像大小相同。
以下是源图像示例,我知道p1,p2,p3,p4的位置,我想将该部分复制到新图像中。 enter image description here 我已经有了目标图像。例如下面的图像是目标图像,我只想将源图像的标记部分粘贴到目标图像中。我该如何操作? enter image description here 最终输出应该类似于这个: enter image description here 谢谢,
1个回答

21
  1. 首先使用你的四个坐标创建一个遮罩图像。

  2. 现在,使用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);  

请看下面的结果:
请查看以下的结果:

enter image description here

编辑: 根据您下面的留言,这里是您需要遵循的步骤:
  1. First create Mask image as described above

  2. Copy the the source image to new Mat dst1 using the mask.

  3. Invert your mask and copy destination image to a new Mat dst2

  4. 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]

enter image description here


嗨,哈里斯,感谢您的友好回复。但我不想让源图像变黑。我认为我的问题没有解释清楚。所以,我又编辑了一下问题。谢谢。 - MMH
你的目标图像尺寸不同? - Haris
因为它们只是编辑过的图片,不是真正的输出。 - MMH
嗨,哈里斯,谢谢你的更新。我没有理解第三点,请你能否解释一下? - MMH
让我们在聊天中继续这个讨论:http://chat.stackoverflow.com/rooms/48840/discussion-between-haris-and-mmh - Haris
非常感谢。这真的帮了我很大的忙。 - MMH

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接