Search code examples
c++qtopencvmatqpixmap

C++ opencv Mat to QPixmap errors


I am attempting to write a function which puts a greyscale OpenCv Mat into a Qt QPixmap, then into a QLabel.

A third of the time it works.

A third of the time, it skews the image...

enter image description here

becomes

enter image description here

The rest of the time, the program crashes, specifically on the fromImage() line.

I know that the incoming Mat objects are greyscale and non-null in each case. Here is the code in question...

void MainWindow::updateCanvasLabel(Mat mat){

    imwrite("c:/pics/last-opened.jpg", mat); //to verify that Mat is
                                             // what I think it is

    QPixmap pixmap = QPixmap::fromImage(QImage((unsigned char*) mat.data,
                               mat.cols,
                               mat.rows,
                               QImage::Format_Grayscale8)); 

    ui->canvasLabel->setPixmap(pixmap);
    ui->canvasLabel->setScaledContents(true);
}

Solution

  • The following is what I normally use to convert cv::Mat to QPixmap or QImage:

    void MainWindow::updateCanvasLabel(Mat mat){
    
        QPixmap pixmap;
        if(mat.type()==CV_8UC1)
        {
            // Set the color table (used to translate colour indexes to qRgb values)
            QVector<QRgb> colorTable;
            for (int i=0; i<256; i++)
                colorTable.push_back(qRgb(i,i,i));
            // Copy input Mat
            const uchar *qImageBuffer = (const uchar*)mat.data;
            // Create QImage with same dimensions as input Mat
            QImage img(qImageBuffer, mat.cols, mat.rows, mat.step, QImage::Format_Indexed8);
            img.setColorTable(colorTable);
            pixmap = QPixmap::fromImage(img);
        }
        // 8-bits unsigned, NO. OF CHANNELS=3
        if(mat.type()==CV_8UC3)
        {
            // Copy input Mat
            const uchar *qImageBuffer = (const uchar*)mat.data;
            // Create QImage with same dimensions as input Mat
            QImage img(qImageBuffer, mat.cols, mat.rows, mat.step, QImage::Format_RGB888);
            pixmap = QPixmap::fromImage(img.rgbSwapped());
        }
        else
        {
            qDebug() << "ERROR: Mat could not be converted to QImage or QPixmap.";
            return;
        }
    
        ui->canvasLabel->setPixmap(pixmap);
        ui->canvasLabel->setScaledContents(true);
    }