Important: Please read the Qt Code of Conduct -

QImage & openCV cause crashes

  • Hey

    I've got a bit of an issue. I'm trying to process some Mat in openCV & throw it into QImage, but for some reason, QImage crashes with this message :

    Mat thu = mImage.clone(); //mImage is cv::Mat.
    setGammaExposure(thu, 2.2f, 1.0f);
    if (thu.channels() == 4) {
         cvtColor(thu, thu, COLOR_RGBA2RGB);
    mThumbnail = QImage(, thu.cols, thu.rows, QImage::Format_RGB888).copy();

    The crash happens on QImage part. Not always, since this takes a snapshot of image that gets constantly updated. What I don't understand is why openCV works just fine processing the image, but QImage has a 50/50% chance of crash. Its pretty random when it happens.

    How can I solve this?


    Edit, further testing showed me that its definitelyt on QImage, I added cv::window to show result of the mat and everything there looks "correct" so its down to QImage...


  • Lifetime Qt Champion


    Can you show the stack trace you get ?

  • @SGaist The screenshot above is almost all I get. Before that Its just my function running copying memory and passing it around - nothing to Qt related there.

    I did a number of tests now. From what I can tell, putting my cv::Mat in header and never deleting it helped the crashes... QImage no longer copies the data, only reads from my mat. - that appear to be a lot more stable. However when I try to do this >

    mQImage = QImage(, thu.cols, thu.rows, QImage::Format_RGB888);
    mThumbnail = mQImage.scaled(QSize(200, 200), Qt::KeepAspectRatio, Qt::SmoothTransformation);

    I'm crashing now on scaled function... sigh :- (

    A standalone test goes like this >

        QVector<uchar> data(w * h * 4 * sizeof(float));
        qDebug() << "UCHAR! " << sizeof(uchar) << " Float : " << sizeof(float);
        memcpy(&data[0], image->getPixelData(), w * h * 4 * sizeof(float));
        cv::Mat img = cv::Mat(Size(w, h), CV_32FC4,;
        cv::pow(img, 1 / 2.2, img);
        img.convertTo(img, CV_8U, 255);
        cvtColor(img, img, COLOR_RGBA2RGB);
        QImage i = QImage(, w, h, QImage::Format_RGB888).copy();

  • Lifetime Qt Champion

    Where exactly does it crash? Please provide a backtrace.
    And please read the documentation the QImage ctor:

    The buffer must remain valid throughout the life of the QImage and all copies that have not been modified or otherwise detached from the original buffer. The image does not delete the buffer at destruction. You can provide a function pointer cleanupFunction along with an extra pointer cleanupInfo that will be called when the last copy is destroyed.

Log in to reply