-1

How can I save an area of one image in a new image with the same size as the first image? For example if I had an image like this:

enter image description here

I want to create another image like this:

enter image description here

This is what I tried:

#include <opencv2/opencv.hpp>
#include "iostream"

using namespace cv;
using namespace std;

int main()
{
    Mat src = imread("1.png");
    Mat dst;

    src(Rect(85, 45, 100, 100)).copyTo(dst);
    imshow("tmask", dst);

    waitKey(0);
    return 0;
}

But the result will be like this:

enter image description here

which is not what I wanted.

It is necessary for the program to not initialize the size of Mat dst for reasons that are too long to write here. How can I generate the second image above (dst) without initializing the size of it?

Hadi GhahremanNezhad
  • 2,377
  • 5
  • 29
  • 58
  • 1
    I assume that you know what you want although it seems weird. I guess you can either `dst = src.clone();` and then work on `dst` or create mask and use second `copyTo(img,mask)` overloaded version: https://docs.opencv.org/3.4/d3/d63/classcv_1_1Mat.html#a626fe5f96d02525e2604d2ad46dd574f – michelson Sep 14 '19 at 23:36

1 Answers1

1

create a new image and copy the subimage to roi

cv:: Mat img = cv::imread(...);
cv::Rect roi(x,y,w,h);

cv::Mat subimage= img(roi); // embedded
cv::Mat subimageCopied = subimage.clone(); // copied

cv::Mat newImage=cv::Mat::zeros(img.size(), img.type);

img(roi).copyTo(newImage(roi)); // this line is what you want.

If you have access to the original image, but are not allowed to use its siute information, you can use .copyTo with a mask, but then you have to use the size information to create the mask...

Delgan
  • 18,571
  • 11
  • 90
  • 141
Micka
  • 19,585
  • 4
  • 56
  • 74