Jose M. Jimenez
Jose M. Jimenez

Reputation: 91

OpenCV copying submatrix into another ROI of image

I need to move a submatrix of the image to another place of the same image: it means move down this sumbmatrix. So I have developed the next code

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

the correct image: https://i.sstatic.net/daFMw.png

However, in order to improve the speed of the code, I would like to work with copies of submatrices and I have implemented this code:

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

which does not work correctly as you can see in the picture-link below

https://i.sstatic.net/0gr9P.png

Upvotes: 2

Views: 2754

Answers (1)

Miki
Miki

Reputation: 41765

This is how you copy a portion of the image from position rectBefore to position rectAfter.

You just need to specify the x and y coordinates of the two rectangles, as well as width and height (that must be equal in both).

#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;
}

This will copy the portion of the image in the green rectangle rectBefore to the red rectangle rectAfter.

dbg1

enter image description here

dbg2

enter image description here

Upvotes: 2

Related Questions