61

I need to copy a cv::Mat image (source) to an ROI of another (Destination) cv::Mat image.

I found this reference, but it seems that it does not work for my case. Do you have any pointers how could I do this using the OpenCV C++ interface?

Community
  • 1
  • 1
theosem
  • 1,174
  • 3
  • 10
  • 22

3 Answers3

92

OpenCV 2.4:

src.copyTo(dst(Rect(left, top, src.cols, src.rows)));

OpenCV 2.x:

Mat dst_roi = dst(Rect(left, top, src.cols, src.rows));
src.copyTo(dst_roi);
Andrey Kamaev
  • 29,582
  • 6
  • 94
  • 88
  • thanks! I did it like this and works great: bboxImage.copyTo(destImage.colRange(startCol,startCol+bboxImage.cols).rowRange(startRow,startRow+bboxImage.rows)); – theosem May 07 '12 at 13:02
  • 2
    Yields `no matching function for call to ‘cv::Mat::copyTo(cv::Mat)’ viewtest2.cpp:172:61: note: candidates are: /usr/include/opencv2/core/core.hpp:1651:10: note: void cv::Mat::copyTo(cv::OutputArray) const` in OpenCV 2.4.6. Second solution does work however, but it results into an image with just src. – pbond Aug 06 '13 at 18:15
  • 6
    what is the difference between previous version of opencv? why the code differs? – nkint Dec 11 '13 at 13:16
  • `src.copyTo(dst(Rect(left, top, src.cols, src.rows));` 3x '(' and 2x ')'? `Mat dst_roi = dst(Rect(left, top, src.cols, src.rows);` 2x '(' and 1x ')'? Untested code? – TimZaman Mar 02 '14 at 11:10
  • Is this dst_roi, a pointer to the certain part of the destination image? I guess it should be so.. – Samitha Chathuranga Sep 20 '15 at 08:07
  • 1
    valgrind reports memory leaks when I do this with OpenCV 3.2. But it works ^^ – lawilog Jan 05 '18 at 16:51
  • @lawilog Did you ever figure out how to do this without leaking memory? I'm running into the same issue, and am surprised that there is such a big bug in commonly used OpenCV stuff... – logidelic Jan 24 '20 at 16:06
12

In addition or correction to above answers, if you want to copy a smaller region of open Mat to another Mat, you should do:

src(Rect(left,top,width, height)).copyTo(dst);
Angie Quijano
  • 4,167
  • 3
  • 25
  • 30
Mich
  • 3,188
  • 4
  • 37
  • 85
10

Did work for me this way:

Mat imgPanel(100, 250, CV_8UC1, Scalar(0));
Mat imgPanelRoi(imgPanel, Rect(0, 0, imgSrc.cols, imgSrc.rows));
imgSrc.copyTo(imgPanelRoi);

imshow("imgPanel", imgPanel);
waitKey();

I am using Opencv 2.4.9 Based on Andrey's answer.

Renato Aloi
  • 300
  • 2
  • 9