Copy Mat in opencv

Robotic Vn picture Robotic Vn · Jul 16, 2015 · Viewed 25.6k times · Source

I try to copy a image to other image using opencv, but I got a problem. Two image is not the same, like this:

enter image description here

This is the code I used:

#include <opencv2\opencv.hpp>

#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <cmath>
#include <iostream>
#include <opencv2\opencv.hpp>
int main()
{
    cv::Mat inImg =    cv::imread("C:\\Users\\DUY\\Desktop\\basic_shapes.png");  
    //Data point copy  
    unsigned char * pData = inImg.data;  

    int width = inImg.rows;  
    int height = inImg.cols;  

    cv::Mat outImg(width, height, CV_8UC1);  
    //data copy using memcpy function  
    memcpy(outImg.data, pData, sizeof(unsigned char)*width*height);  

   //processing and copy check  
   cv::namedWindow("Test");  
   imshow("Test", inImg);  

   cv::namedWindow("Test2");  
   imshow("Test2", outImg);  

   cvWaitKey(0);  
}

Answer

David Safrastyan picture David Safrastyan · Jul 16, 2015

Simply use .clone() function of cv::Mat:

cv::Mat source = cv::imread("basic_shapes.png");
cv::Mat dst = source.clone();

This will do the trick. You are making an image with one channel only (which means only shades of gray are possible) with CV_8UC1, you could use CV_8UC3 or CV_8UC4 but for simply copying stick with the clone function.