我正在尝试将一个图像层复制到另一个图像 ROI。我的代码如下。
Mat4b src= imread("path");
Mat3b dest = imread("path");
Rect roi = Rect(179,539,src.cols,src.rows); //src.cols = 1186 and src.rows= 1134 after scaling.
Mat destinationROI = dest(roi);
src.copyTo(destinationROI);
imwrite("destinationROI.png", destinationROI);
但是得到的输出是同一个dest图像。 然后我试图在复制之前保存 destinationROI。我得到的输出是 哪一个是正确的。复制 src 也有效。但对dest图像没有任何影响。
最佳答案
这是为了确认@ypnos 有根据的猜测是正确的(不错的电话,顺便说一句)。
看看这段代码,它执行与您的操作相同的操作:
#include <opencv2\opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
Mat4b m4b(50, 50, Vec4b(0, 255, 0, 255)); // blue image, 4 channels
Mat3b m3b(100, 100, Vec3b(255, 0, 0)); // green image, 3 channels
cout << "After init:" << endl;
cout << "m4b channels: " << m4b.channels() << endl;
cout << "m3b channels: " << m3b.channels() << endl << endl;
Rect roi(0, 0, 50, 50); // roi
// Create a new header for the data inside the roi in m3b
// No data copied, just a new header.
// So destRoi has same number of channels of m3b
Mat destRoi = m3b(roi);
cout << "After roi:" << endl;
cout << "m4b channels : " << m4b.channels() << endl;
cout << "m3b channels : " << m3b.channels() << endl;
cout << "destRoi channels: " << destRoi.channels() << endl << endl;
// destination type != source type
// destRoi is newly created with the destination type
// destRoi doesn't point anymore to the data in m3b and has 4 channels now
m4b.copyTo(destRoi);
cout << "After copyTo:" << endl;
cout << "m4b channels : " << m4b.channels() << endl;
cout << "m3b channels : " << m3b.channels() << endl;
cout << "destRoi channels: " << destRoi.channels() << endl << endl;
return 0;
}
输出:
After init:
m4b channels: 4
m3b channels: 3
After roi:
m4b channels : 4
m3b channels : 3
destRoi channels: 3
After copyTo:
m4b channels : 4
m3b channels : 3
destRoi channels: 4
解决方案
通过以下方式使用具有相同 channel 数的两个矩阵:
将两个图像加载为 3 channel 矩阵
CV_8UC3
。 事实上,您发布的图像都是 3 个 channel在执行 roi 和复制操作之前,使用
cvtColor
转换为相同数量的 channel 。
关于c++ - 需要复制一张图片到另一张图片的ROI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32680172/