C++ opencv Mat 到 QPixmap 错误

C++ opencv Mat to QPixmap errors

我正在尝试编写一个函数,将灰度 OpenCv Mat 放入 Qt QPixmap,然后放入 QLabel。

三分之一的时间有效。

三分之一的时间,它会扭曲图像...

变成

其余时间,程序崩溃,特别是在 fromImage() 行。

我知道传入的 Mat 对象在每种情况下都是灰度和非空的。这是有问题的代码...

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

下面是我平时用来把cv::Mat转换成QPixmap或者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);
}