Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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