新建一个GUI项目,QT4为 Qt4 Gui Application,QT5为 Qt Widgets Application,基类选择 QMainWindow
项目实现功能:两个按钮,一个用于在文件夹中选择图片并预览图片,一个按钮用于反转该图片。项目代码如下:
.pro 代码段,关于加入opencv头文件和库函数的代码根据自己开发环境而定。
#------------------------------------------------- # # Project created by QtCreator 2015-07-29T14:41:15 # #------------------------------------------------- QT += core gui greaterThan(QT_MAJOR_VERSION, 4): QT += widgets TARGET = opencv-test-GUI TEMPLATE = app SOURCES += main.cpp mainwindow.cpp HEADERS += mainwindow.h FORMS += mainwindow.ui INCLUDEPATH+=D:\useropencvqt\include\opencv D:\useropencvqt\include\opencv2 D:\useropencvqt\include LIBS+=D:\useropencvqt\lib\libopencv_calib3d2411.dll.a D:\useropencvqt\lib\libopencv_contrib2411.dll.a D:\useropencvqt\lib\libopencv_core2411.dll.a D:\useropencvqt\lib\libopencv_features2d2411.dll.a D:\useropencvqt\lib\libopencv_flann2411.dll.a D:\useropencvqt\lib\libopencv_gpu2411.dll.a D:\useropencvqt\lib\libopencv_highgui2411.dll.a D:\useropencvqt\lib\libopencv_imgproc2411.dll.a D:\useropencvqt\lib\libopencv_legacy2411.dll.a D:\useropencvqt\lib\libopencv_ml2411.dll.a D:\useropencvqt\lib\libopencv_objdetect2411.dll.a D:\useropencvqt\lib\libopencv_video2411.dll.a
.h 代码段,注意加入了opencv2的头文件和QFileDialog头文件。
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QFileDialog> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private slots: void on_pushButton_clicked(); void on_pushButton_2_clicked(); private: Ui::MainWindow *ui; cv::Mat src;//用于预览图片的 Mat 对象 }; #endif // MAINWINDOW_H
与.h 文件对应的 .cpp 代码段
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_pushButton_clicked()//第一个按钮 { QString fileName = QFileDialog::getOpenFileName(this, tr("Open Image"), ".", tr("Image Files(*.png *.jpg *.jpeg *.bmp)")); src = cv::imread(fileName.toLatin1().data());//Qt4的话用 fileName.toAscii().data() cv::namedWindow("src",0); cv::imshow("src",src); } void MainWindow::on_pushButton_2_clicked()//第二个按钮 { cv::flip(src, src, 1); cv::namedWindow("result", 0); cv::imshow("result", src); }
main.cpp 代码段,貌似不需要做任何修改
#include "mainwindow.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); }
若要在 Gui 界面上预览最后处理的图像,则在 Gui 界面添加一个 Label 标签,然后将第二个按钮的处理函数改成:
void MainWindow::on_pushButton_2_clicked() { cv::flip(src, src, 1); cv::cvtColor(src, src, CV_BGR2RGB); QImage img = QImage((const unsigned char* )(src.data), src.cols, src.rows, QImage::Format_RGB888); ui->label->setPixmap(QPixmap::fromImage(img)); ui->label->resize(ui->label->pixmap()->size()); }
并且加入头文件 :
#include <opencv2/imgproc/imgproc.hpp>
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-11-02 23:30:26