【OpenCV+Qt】在Qt界面中显示OpenCV处理的图像

本文介绍如何在Qt界面的Label控件中显示由OpenCV处理的Mat图像,通过将BGR顺序的Mat图像转换为RGB顺序的QImage实现。

文章目录

示例

注意:本文不会提及太多Qt的具体操作,主要介绍如何用Qt的Label控件显示OpenCV的Mat类图像。
博主是在VS中使用Qt和OpenCV的,主要使用了三个控件,LabelPush ButtonCheck 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();
}
评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值