c++ - 需要复制一张图片到另一张图片的ROI

标签 c++ opencv image-processing

我正在尝试将一个图像层复制到另一个图像 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);

输入源是enter image description here 输入目标是enter image description here

但是得到的输出是同一个dest图像。 然后我试图在复制之前保存 destinationROI。我得到的输出是 enter image description here哪一个是正确的。复制 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 数的两个矩阵:

  1. 将两个图像加载为 3 channel 矩阵 CV_8UC3事实上,您发布的图像都是 3 个 channel

  2. 在执行 roi 和复制操作之前,使用 cvtColor 转换为相同数量的 channel 。

关于c++ - 需要复制一张图片到另一张图片的ROI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32680172/

相关文章:

image-processing - 如何将通过http post接收到的png图像加载为OpenCV IplImage格式

image-processing - 什么是3D DICOM文件以及区别3D和2D dicom文件

c++ - 复制构造函数和 getter 错误(增变函数)

c++ - ATL CComPtr 附加、分离和析构函数

java - 将字节显示为无符号

python - 如何锐化opencv python中的边缘

visual-studio-2010 - 在 pictureBox (Visual C++ 2010) 中显示 cv::Mat (opencv 2.4.3)

c# 在保持宽高比的同时将图像调整为不同的大小

C++ 读取多列文件

c++ - 如何以编程方式更改 RDP 登录名/密码?