Search code examples
qtopencvqt5qpixmap

QPixmap fromImage gives segment fault on image converted from cv::mat


I simplified the code and it is like this:

Mat mat = imread("xxx.jpg"); //Successfully read the image, confirmed by cvShowImage.

if (mat.empty())
{
    qDebug() << "Couldn't load image";
    return;
}

Mat cpy = mat.clone();
cvtColor(mat,cpy,CV_BGR2RGB);
QImage image(cpy.data, cpy.cols, cpy.rows, cpy.step, QImage::Format_RGB888);

try {
    pm = QPixmap::fromImage(image); //crash line
} catch(std::exception const &ex){
    qDebug()<<ex.what();
}

however the program just crashed without any debug log.. I've tried many images and the result is same. I tried to find the "stack trace" and it seems give segfault on this..

enter image description here


Solution

  • okay.. just change the conversion code to

    QImage image(cpy.data, cpy.cols, cpy.rows, cpy.step, QImage::Format_RGB888);
    image = image.rgbSwapped();
    

    solved it. Actually I don't know why this fixed it. Maybe because I should use COLOR_BGR2RGB rather than CV_BGR2RGB..