OpenCV 将子矩阵复制到图像的另一个 ROI

OpenCV copying submatrix into another ROI of image

我需要将图像的一个子矩阵移动到同一图像的另一个地方:这意味着将这个子矩阵向下移动。所以我开发了下一个代码

Mat image;
image = cv::imread(buffer, 1);

nlines = 10;

for ( k = 0; k < nlines; k++ ) 
{
    for ( j = 401; j < ncolmax; j++ )
    {
        for ( i = nrowmax-1; i >= 555 ; i--)
        {
            intensity = image.at<uchar>(i-1,j);
            image.at<uchar>(i,j) = intensity.val[0];
        }
        image.at<uchar>(i,j) = 255;
     }
}

正确的图片:http://i.stack.imgur.com/daFMw.png

但是,为了提高代码速度,我想使用子矩阵的副本,我已经实现了这段代码:

Mat aux = image.colRange(pixel[1],image.cols-1).rowRange(pixel[0]+nlineas,nrowmax-1);

Mat newsubmatrix = image.colRange(pixel[1],image.cols-1).rowRange(pixel[0],nrowmax-1-nlineas);

newsubmatrix.copyTo(aux);

正如您在下面的图片中看到的那样无法正常工作-link

http://i.stack.imgur.com/0gr9P.png

这就是将图像的一部分从位置 rectBefore 复制到位置 rectAfter 的方法。

你只需要指定两个矩形的xy坐标,以及widthheight(两者必须相等) .

#include <opencv2\opencv.hpp>
using namespace cv;

int main()
{
    Mat3b img = imread("path_to_image");

    int roi_width = 200;
    int roi_height = 100;
    Rect rectBefore(270, 100, roi_width, roi_height);
    Rect rectAfter(500, 400, roi_width, roi_height);

    Mat3b dbg1 = img.clone();
    rectangle(dbg1, rectBefore, Scalar(0,255,0), 2);

    Mat3b roiBefore = img(rectBefore).clone();  // Copy the data in the source position
    Mat3b roiAfter = img(rectAfter);            // Get the header to the destination position

    roiBefore.copyTo(roiAfter);

    Mat3b dbg2 = img.clone();
    rectangle(dbg2, rectAfter, Scalar(0,0,255), 2);

    return 0;
}

这会将绿色矩形 rectBefore 中的图像部分复制到红色矩形 rectAfter

dbg1

dbg2