Please nominate your Qt Champions for 2021!

Convert between cv::mat and Qimage would make the program crash

  • @

    #include "opencv2/core/core.hpp"
    #include "opencv2/highgui/highgui.hpp"
    #include "opencv2/imgproc/imgproc.hpp"

    #include <QtGui>
    inline QImage const mat_to_qimage_ref(cv::Mat &mat)
      return QImage((unsigned char*)(, mat.cols, mat.rows, mat.step, QImage::Format_RGB32);
    int main(int argc, char *argv[])
      QApplication a(argc, argv);
      QImage img("lena2.jpg");
      cv::Mat mat(img.height(), img.width(), CV_8UC4, img.bits(), img.bytesPerLine());
      QImage img = mat_to_qimage_ref(mat); //#1
      //QImage img2((unsigned char*)(, mat.cols, mat.rows, mat.step, QImage::Format_RGB32); #2
      QLabel label;
      label.setPixmap(QPixmap::fromImage(img)); //crash at here;
      return a.exec&#40;&#41;;


    (#2) is ok, but #1 will occur undefined behavior?(my case is crash)

    Besides, if you use it as the codes below, It is okay

    cv::Mat img = cv::imread("lena2.jpg");
    QLabel label;

    Don't know what is happening, something related to cycle dependency?

Log in to reply