繁体   English   中英

将 cv::mat 转换为 QImage

[英]Converting cv::mat to QImage

就像标题说的,我正在尝试将 cv::mat 转换为 QImage。 我正在做的是在垫子上使用 equalizeHist() 函数,然后将其转换为 QImage 以显示在 Qt 的小部件窗口中。 我知道垫子可以正常工作并正确加载图像,因为均衡的图像将使用 imshow() 显示在新窗口中,但是当将此垫子转换为 QImage 时,我无法让它在窗口中显示。 我相信问题出在从 mat 到 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

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

您的问题是 QImage 到cv::Mat的转换,当在cv::imread使用标志 0 时意味着读数是灰度的,并且您使用的是格式QImage::Format_RGB88 8 的转换。我使用以下函数将cv::Mat转换为QImage

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM