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

时间:2015-08-28 16:48:33

标签: c++ opencv matrix copy

我需要将图像的子矩阵移动到同一图像的另一个位置:它意味着向下移动此sumbmatrix。所以我开发了下一个代码

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);

无法正常工作,如下面的图片链接所示

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

1 个答案:

答案 0 :(得分:1)

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

您只需指定两个矩形的xy坐标,以及widthheight(两者必须相等)。< / p>

#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

enter image description here

<强> DBG2

enter image description here