将 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

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

您的问题是将 QImage 转换为cv::Mat,当在cv::imread中使用标志 0 时,意味着读数是灰度的,并且您正在使用格式为QImage::Format_RGB888 的转换。我使用以下函数将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);

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

最新更新