想要在qt的控件label中显示opencv处理后的Mat格式图像,首先要将Mat类型转换成QImage类型,转换函数如下:
/************Mat转QImage函数*****************************************************************************************/
/***************************************************************************************************************************************/
QImage MainWindow::cvMat2QImage(const Mat& mat)
{
// 8-bits unsigned, NO. OF CHANNELS = 1
if(mat.type() == CV_8UC1)
{
QImage qimage(mat.cols, mat.rows, QImage::Format_Indexed8);
// Set the color table (used to translate colour indexes to qRgb values)
qimage.setColorCount(256);
for(int i = 0; i < 256; i++)
{
qimage.setColor(i, qRgb(i, i, i));
}
// Copy input Mat
uchar *pSrc = mat.data;
for(int row = 0; row < mat.rows; row ++)
{
uchar *pDest = qimage.scanLine(row);
memcpy(pDest, pSrc, mat.cols);
pSrc += mat.step;
}
return qimage;
}
// 8-bits unsigned, NO. OF CHANNELS = 3
else if(mat.type() == CV_8UC3)
{
// Copy input Mat
const uchar *pSrc = (const uchar*)mat.data;
// Create QImage with same dimensions as input Mat
QImage image(pSrc, mat.cols, mat.rows, mat.step, QImage::Format_RGB888);
return image.rgbSwapped();
}
else if(mat.type() == CV_8UC4)
{
// Copy input Mat
const uchar *pSrc = (const uchar*)mat.data;
// Create QImage with same dimensions as input Mat
QImage image(pSrc, mat.cols, mat.rows, mat.step, QImage::Format_ARGB32);
return image.copy();
}
else
{
return QImage();
}
}
转换成QImage后,想要在label中显示出来,按照下面这样就好了,qImg1是QImage类型。
//等比列显示闭运算后的图片
qImg1 = cvMat2QImage(img);
QPixmap pixmap1 = QPixmap::fromImage(qImg1);//转化成可以显示的格式
int with1 = ui->dealimage->width();
int height1 = ui->dealimage->height();
QPixmap fitpixmap1 = pixmap1.scaled(with1, height1, Qt::KeepAspectRatio, Qt::SmoothTransformation); // 按比例缩放
ui->dealimage->setPixmap(fitpixmap1);