简体   繁体   中英

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

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM