示例
注意:本文不会提及太多Qt的具体操作,主要介绍如何用Qt的Label控件显示OpenCV的Mat类图像。
博主是在VS中使用Qt和OpenCV的,主要使用了三个控件,Label,Push Button,Check Box,UI界面效果如下图。

OpenCV中的图像主要存储在Mat类中,要让其显示在Qt的Label控件上,必须先将其转换为Qt的QImage类。这部分代码如下:
Mat temp;
cvtColor(srcImg, temp, CV_BGR2RGB);//BGR convert to RGB
QImage Qtemp = QImage((const unsigned char*)(temp.data), temp.cols, temp.rows, temp.step, QImage::Format_RGB888);
ui.label->setPixmap(QPixmap::fromImage(Qtemp));
ui.label->resize(Qtemp.size());
ui.label->show();
ps:Mat类图像是按照BGR顺序存储的图像,而QImage是按照RGB顺序存储的,在类型转换前需要将通道更改。
效果如下:

代码
Qt.h文件
#pragma once
#pragma execution_character_set("utf-8")//display chinese words
#include <QtWidgets/QMainWindow>
#include <opencv2/opencv.hpp>
#include "ui_MatdisplayinQt.h"
using namespace cv;
class MatdisplayinQt : public QMainWindow
{
Q_OBJECT
public:
MatdisplayinQt(QWidget *parent = Q_NULLPTR);
int isGray = 0;
Mat srcImg, grayImg;
private:
Ui::MatdisplayinQtClass ui;
private slots:
void on_checkBox_clicked();
void on_pushButton_clicked();
};
Qt.cpp文件
#include "MatdisplayinQt.h"
MatdisplayinQt::MatdisplayinQt(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
}
void MatdisplayinQt::on_pushButton_clicked()
{
srcImg = imread("00.jpg");
cvtColor(srcImg, grayImg, CV_BGR2GRAY);
Mat temp;
QImage Qtemp;
if (!isGray)
{
cvtColor(srcImg, temp, CV_BGR2RGB);//BGR convert to RGB
Qtemp = QImage((const unsigned char*)(temp.data), temp.cols, temp.rows, temp.step, QImage::Format_RGB888);
}
else
{
cvtColor(grayImg, temp, CV_GRAY2RGB);//GRAY convert to RGB
Qtemp = QImage((const unsigned char*)(temp.data), temp.cols, temp.rows, temp.step, QImage::Format_RGB888);
}
ui.label->setPixmap(QPixmap::fromImage(Qtemp));
ui.label->resize(Qtemp.size());
ui.label->show();
}
void MatdisplayinQt::on_checkBox_clicked()
{
if (ui.checkBox->isChecked())
{
isGray = 1;
}
else
{
isGray = 0;
}
}
main.cpp文件
#include "MatdisplayinQt.h"
#include <QtWidgets/QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MatdisplayinQt w;
w.show();
return a.exec();
}
本文介绍如何在Qt界面的Label控件中显示由OpenCV处理的Mat图像,通过将BGR顺序的Mat图像转换为RGB顺序的QImage实现。

332

被折叠的 条评论
为什么被折叠?



