C++ opencv Mat to QPixmap errors

匆匆过客 提交于 2020-01-03 02:28:08

问题


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...

becomes

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

回答1:


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


来源:https://stackoverflow.com/questions/45724457/c-opencv-mat-to-qpixmap-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!