c++ convert uchar * to opencv mat
I have converted a cv::Mat object to uchar *
uchar *DisplayImage::MatToBytes(cv::Mat image)
{
//class data members
image_rows = image.rows;
image_cols = image.cols;
image_type = image.type();
int image_size = image.total() * image.elemSize();
uchar * image_uchar = new uchar[image_size];
std::vector<uchar> v_char;
for(int i = 0; i < image.rows; i++)
{
for(int j = 0; j < image.cols; j++)
{
v_char.push_back(*(uchar*)(image.data+ i + j));
}
}
//image_uchar is a class data member
image_uchar = &v_char[0];
//cvWaitKey(5000);
return image_uchar;
}
I now want to convert the uchar* back to Mat object. I tried using the Mat clone function but I don't really understand all the parameters for the default Mat constructor. And then I read somewhere that I can just use the default Mat constructor but I don't know what that last parameter (size_t step) means.
cv::Mat DisplayImage::BytesToMat()
{
cv::Mat img = cv::Mat(image_rows,image_cols,CV_16UC1,image_byte,0); //I am not sure about the last parameter here
cv::namedWindow("MyWindow");
cv::imshow("MyWindow",img);
cvWaitKey(500);
return img;
}
How do you convert uchar * back to Mat object? The image is a colour image by the way
I don't know your concerns, but a Mat is, in case of a CV_8UC, already a uchar array. You get the address to the first element by using
uchar *image_uchar = img.data;
Consider that in case of a 3 channel image data storage is: blue[0][0], green[0][0], red[0][0], blue[0][1], green[0][1], red[0][1],... Check out: How the image matrix is stored in the memoryt
When you want a Mat out of a uchar array use
Mat byteImage = Mat(rows, cols, CV_8UC3, image_uchar);
in case of a 3 channel byte image. It isn't necessary to specify size_t step because it is AUTO_STEP by default.
Thanks, the link was 'slots' helpful although there parts I find confusing there but I will read some more as I am still leaerning