首页 > 解决方案 > 将 cv::mat 转换为 QImage

问题描述

就像标题说的我正在尝试将 cv::mat 转换为 QImage。我正在做的是在垫子上使用 equalizeHist() 函数,然后将其转换为 QImage 以显示在 Qt 的小部件窗口中。我知道垫子可以正常工作并正确加载图像,因为均衡后的图像将使用 imshow() 显示在新窗口中,但是当将此垫子转换为 QImage 时,我无法将其显示在窗口中。我相信问题在于从垫子到 QImage 的转换,但找不到问题。下面是我的代码片段的一部分。

Mat image2= imread(directoryImage1.toStdString(),0);
//cv::cvtColor(image2,image2,COLOR_BGR2GRAY);
Mat histEquImg;
equalizeHist(image2,histEquImg);
imshow("Histogram Equalized Image 2", histEquImg);
//QImage img=QImage((uchar*) histEquImg.data, histEquImg.cols, histEquImg.rows, histEquImg.step, QImage::Format_ARGB32);
imageObject= new QImage((uchar*) histEquImg.data, histEquImg.cols, histEquImg.rows, histEquImg.step, QImage::Format_RGB888);
image = QPixmap::fromImage(*imageObject);
scene=new QGraphicsScene(this); //create a frame for image 2
scene->addPixmap(image); //put image 1 inside of the frame
ui->graphicsView_4->setScene(scene); //put the frame, which contains image 3, to the GUI
ui->graphicsView_4->fitInView(scene->sceneRect(),Qt::KeepAspectRatio); //keep the dimension ratio of image 3

没有错误发生,程序不会崩溃。提前致谢。

标签: c++qtopencvqt5

解决方案


您的问题是将 QImage 转换为cv::Mat,当使用标志 0cv::imread表示读数为灰度时,您正在使用格式为QImage::Format_RGB888 的转换。我使用以下函数将转换cv::MatQImage

static QImage MatToQImage(const cv::Mat& mat)
{
    // 8-bits unsigned, NO. OF CHANNELS=1
    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);
        return 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);
        return img.rgbSwapped();
    }
    return QImage();
}

之后,我发现您在评论时对如何QGraphicsViewQGraphicsScene工作有误解:将包含图像 3 的框架放到 GUI中,ui->graphicsView_4->setScene(scene);您不是在设置框架而是在设置场景,并且场景应该只设置一次,最好在构造函数。

// constructor
scene = new QGraphicsScene(this);
ui->graphicsView->setScene(scene);

因此,当您要加载图像时,只需使用场景:

cv::Mat image= cv::imread(filename.toStdString(), CV_LOAD_IMAGE_GRAYSCALE);

cv::Mat histEquImg;
equalizeHist(image, histEquImg);

QImage qimage = MatToQImage(histEquImg);
QPixmap pixmap = QPixmap::fromImage(qimage);
scene->addPixmap(pixmap);
ui->graphicsView->fitInView(scene->sceneRect(), Qt::KeepAspectRatio);

完整的示例可以在以下链接中找到。


推荐阅读