opencv与qt5GUI融合
win.h
#ifndef WIN_H #define WIN_H #include <QWidget> #include <QDebug> #include <QFileDialog> #include<opencv2/opencv.hpp> #include <QPushButton> #include <QLabel> class win : public QWidget { Q_OBJECT public: win(QWidget *parent = nullptr); ~win(); public slots: void on_openButton_clicked(); private: QString img_name; cv::Mat src; QImage img; QLabel* label; QPixmap p; }; #endif // WIN_H
win.cpp
#include "win.h" win::win(QWidget *parent) : QWidget(parent) { this->resize(500,400); label=new QLabel(this); QPushButton* btn=new QPushButton("打开",this); btn->move(400,350); connect(btn,&QPushButton::clicked,this,&win::on_openButton_clicked); } win::~win() { } void win::on_openButton_clicked() { img_name = QFileDialog::getOpenFileName( this, tr("请选择需要打开的图片"), ".",tr("Image Files(*.png *.jpg *.jpeg *.bmp)")); if(img_name.length()<=0)return; qDebug()<<img_name; //"D:/bb/tu/a.png" //src=cv::imread(img_name); //这是错误的,因为opencv不认识Qstring src=cv::imread(img_name.toUtf8().data()); qDebug()<<img_name.toUtf8().data(); // D:/bb/tu/a.png //data()表示返回QByteArray的指针 cv::namedWindow( "src", cv::WINDOW_NORMAL ); if(!src.empty()){ cv::imshow("src",src);} img = QImage( (const unsigned char*)(src.data), src.cols, src.rows, QImage::Format_RGB888 );//把opencv图像转换成QImage图像 img=img.rgbSwapped();//RGB和BGR格式互换 //QImage是RGB顺序 opencv是BGR顺序 p.convertFromImage(img); //把QImage转换成QPixmap label->setPixmap(p); label->resize(src.cols,src.rows); }
工程下载: 链接:https://pan.baidu.com/s/1xGUo-RdYPPUuGB_cbbtFKA 提取码:6666