总结一些步骤和操作:
1、首先创建一个GUI的应用,如下图所示
2、设计UI界面
2.1怎么设计信号槽
这里以on_openImg_clicked()为例,这个是用来打开图像的,按照上边的顺序进行添加。一般来说,槽的命名方式一般为on_****_clicked(),同理使用这种方式命名on_Process_clicked(),用以处理图像。
3、编程
3.1框架结构
3.2 主要程序内容
helloworld.h头文件
#pragma once
#include <QtWidgets/QMainWindow>
#include "ui_helloworld.h"
#include<QGraphicsScene>
#include<QGraphicsView>
#include<opencv2\imgproc\imgproc.hpp>
#include <opencv2\core\core.hpp>
#include <opencv2\highgui\highgui.hpp> //opencv申明
#include <qfiledialog.h> //getopenfilename 类申明
#include <qlabel.h> //label类
using namespace cv;
using namespace std;
class helloworld : public QMainWindow
{
Q_OBJECT;
public:
helloworld(QWidget *parent = Q_NULLPTR);
~helloworld();
//添加槽函数
private slots:
void on_openImg_clicked();
//按格式on_控件名_clicked命名函数,QT会默认完成函数和按钮动作的链接,如果不这样命名的话就去设置信号槽函数
void on_Process_clicked();
//void on_checkBox();
private:
Ui::helloworldClass ui;
Mat image;
QLabel* label;
QLabel* label_2;
};
主程序helloworld.cpp
#include "helloworld.h"
#include<QImage>
#include<QDebug>
using namespace cv;
using namespace std;
helloworld::helloworld(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
}
helloworld::~helloworld()
{
//析构函数
}
void helloworld::on_openImg_clicked()
{
QString filename;
filename = QFileDialog::getOpenFileName(this,tr("选择图像"),"", tr("Images (*.png *.bmp *.jpg *.tif *.GIF )"));
if (filename.isEmpty())
{return;}
else
{
string str = filename.toStdString(); // 将filename转变为string类型;
image = imread(str);
cvtColor(image, image, COLOR_BGR2RGB);
cv::resize(image, image, Size(300, 200));
QImage img = QImage((const unsigned char*)(image.data), image.cols, image.rows,image.step, QImage::Format_RGB888);
label = new QLabel();
label->setPixmap(QPixmap::fromImage(img));
label->resize(QSize(img.width(), img.height()));
ui.scrollArea->setWidget(label);
}
}
void helloworld::on_Process_clicked()
{
//flip(image, image, 4);//反转函数 0 上下反转;整数,水平发转;负数,水平垂直均反转
cvtColor(image, image, COLOR_BGR2GRAY);
QImage img1 = QImage((const unsigned char*)(image.data), image.cols, image.rows, QImage::Format_Grayscale8);
label_2 = new QLabel(); label_2->setPixmap(QPixmap::fromImage(img1));
label_2->resize(QSize(img1.width(), img1.height()));
ui.scrollArea_2->setWidget(label_2);
}
运行函数main.cpp
#include "helloworld.h"
#include <QtWidgets/QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
helloworld w;
w.show();
return a.exec();
}
4、注意事项
有个很关键的点就是,图像的类型是有变化的,Mat图像是BGR色彩空间,而QImage是RGB色彩空间的,需要进行转换,而且QImage的图像格式有很多种,包括图像位的差别,需要在编程的时候主要到。
图像格式转换的问题: https://blog.youkuaiyun.com/wr132/article/details/54428144
windows平台下基于QT和OpenCV搭建图像处理平台: https://www.cnblogs.com/jsxyhelu/p/8023995.html
备注:源文件已经上传,链接是:https://download.youkuaiyun.com/download/lida0013/12306259