c++qtopencvqimageopencv-mat

from cvMat to QImage


i want to convert an image from cvMat type to Qimage , with my actual code the application does not work; i have did it the other way (Qimage to Mat it work fine) please tell me what is going on wrong with my code

here is my code for Qimage to Mat :

Mat qimage2mat(const QImage& qimage) {
    cv::Mat mat = cv::Mat(qimage.height(), qimage.width(), CV_8UC4, (uchar*)qimage.bits(), qimage.bytesPerLine());
    cv::Mat mat2 = cv::Mat(mat.rows, mat.cols, CV_8UC3 );
    int from_to[] = { 0,0,  1,1,  2,2 };
    cv::mixChannels( &mat, 1, &mat2, 1, from_to, 3 );
    return mat2;
}

and here is my code for Mat to Qimage

QImage mat2qimage(const Mat& mat) {
    Mat rgb;
    cvtColor(mat, rgb, CV_BGR2RGB);
    return QImage((const unsigned char*)(rgb.data), rgb.cols, rgb.rows, QImage::Format_RGB888);
}

thank you by advance


Solution

  • as @SpamBot mentioned, the data is freed when Mat goes out of scope. try deep copying the data:

    QImage mat2qimage(const Mat& mat) 
    {
        Mat rgb;
        cvtColor(mat, rgb, CV_BGR2RGB);
        return QImage((const unsigned char*)(rgb.data), rgb.cols, rgb.rows, QImage::Format_RGB888).copy();
    }