3

I am a beginner in opencv programing, i m trying to read an image(cv::Mat) and copy its data to some vector of Uchar and then create the image back from the vector.

i.e read Mat , convert Mat to std::vector and then create a Mat from that vector again.

The vector is needed for intermediate transformation of pixel data. I reffered Convert Mat to Array/Vector in OpenCV

For the the conversion of vector-Mat.

int main()
{
    Mat image = imread("c:\\cv\\abc.bmp");
    std::vector<unsigned char> src_vec;
    src_vec.assign(image.datastart, image.dataend);
    cv::Mat dest(src_vec, true);
    try {
        imwrite("dest.bmp", dest);

    }
    catch (runtime_error& ex) {
        fprintf(stderr, "Exception saving the image: %s\n", ex.what());
        return 1;
    }
    return 0;
}

The output image seems to be garbage,how can I set the dest Mat with the vector data or is it that I am creating the vector itself in a wrong way. Any guidance will be helpful.

Community
  • 1
  • 1
Hummingbird
  • 647
  • 8
  • 27

1 Answers1

1

You are missing the header information. The vector contains only the pixels data. You have to save the header data somewhere and pass it to the mat again. In the following example, the header data was taken directly from the source image. You may save it also in some integer variables and pass it to the header of the new mat again.

Mat image = imread("c:\\cv\\abc.bmp");
    std::vector<unsigned char> src_vec;
    src_vec.assign(image.datastart, image.dataend);
    cv::Mat dest(image.rows,image.cols,image.type());
    dest.data = src_vec.data();
    try {
        imshow("sss", dest);
        cv::waitKey();
        //or show using imshow - nothing is shown
    }
    catch (runtime_error& ex) {
        fprintf(stderr, "Exception saving the image: %s\n", ex.what());
        return 1;
    }
    return 0;

P.S. try not to use \\ it is a Windows thing. Use /, it is cross-platform.

Humam Helfawi
  • 19,566
  • 15
  • 85
  • 160