Copy mat in opencv

I am trying to copy an image to another image using opencv, but I had a problem. Two images do not match, for example:

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);  
}
+4
source share
5 answers

Just use the .clone () function of cv :: Mat

cv::Mat source= imread("read my image");
cv::Mat dst = source.clone();

This will do the trick. You make an image with only one channel (this means that only grayscale is possible) with CV_8UC1, you can use CV_8UC3 or CV_8UC 4, but for simple copying with the clone function.

+9
source

In fact, you do not want to copy the data, since you start with an RGB image CV_8UC3, and want to work with a grayscale image CV_8UC1.

cvtColor, RGB .

#include <opencv2\opencv.hpp>
#include <iostream>

using namespace cv;

int main()
{
    Mat inImg = cv::imread("C:\\Users\\DUY\\Desktop\\basic_shapes.png"); // inImg is CV_8UC3 
    Mat outImg;
    cvtColor(inImg, outImg, COLOR_RGB2GRAY); // Now outImg is CV_8UC1

    //processing and copy check  
    imshow("Test", inImg);  
    imshow("Test2", outImg);  
    waitKey();  
}

memcopy uchar :

BGR BGR BGR BGR  ...

, (G ):

G G G G ...

, outImg .

, outImage :

cv::Mat outImg(width, height, CV_8UC3);  // Instead of CV_8UC1
+5

- opencv clone :

cv::Mat outImg = inImg.clone();
+2

. cv::Mat outImg(width, height, CV_8UC1); , CV_8UC1, 8- . , , . , total pixels * 8-bits, 1/3 ( , 3 , 8 , 24- ) , , 1/4 ( -, 4- 8- 32- ).

TL;DR: - , , .

+2

.

 #include <opencv2/opencv.hpp>  
 #include <opencv2/highgui/highgui.hpp>  
 #include <opencv2/imgproc/imgproc.hpp>  
 #include <cmath> 
 int main()  
 {  
    cv::Mat inImg = cv::imread("1.jpg");  

    cv::Mat outImg = inImg.clone();   

   cv::namedWindow("Test");  
   imshow("Test", inImg);

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

   cvWaitKey(0);  
}
+2
source

Source: https://habr.com/ru/post/1598253/


All Articles