Qt + OpenCV 读取并显示图像
原创
©著作权归作者所有:来自51CTO博客作者SongpingWang的原创作品,请联系作者获取转载授权,否则将追究法律责任
文章目录
一、创建应用&UI
拖拽两个组件:QLable,QPushButton,
写代码并显示图像
.pro文件添加:
INCLUDEPATH += E:\opencv3\opencv\sources\build\install\include\
E:\opencv3\opencv\sources\build\install\include\opencv2\
E:\opencv3\opencv\sources\build\install\include\opencv
LIBS += -L E:\opencv3\opencv\sources\build\install\x64\mingw\lib\libopencv_*.a
二、代码与效果演示
mainwindow.cpp
#include <QFileDialog>
#include <QFile>
#include <QMainWindow>
#include <opencv2/opencv.hpp>
#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,"打开图像","","Image file(*.png *.jpg *.jpeg *.bmp)");
if(!QFile::exists(filename)){
return;
}
ui->statusbar->showMessage(filename);
cv::Mat src = cv::imread(filename.toLatin1().data());
if(src.empty()){
ui->statusbar->showMessage("图像不存在!");
return;
}
cv::Mat temp;
if(src.channels()==4)
cv::cvtColor(src,temp,cv::COLOR_BGRA2RGB);
else if (src.channels()==3)
cv::cvtColor(src,temp,cv::COLOR_BGR2RGB);
else
cv::cvtColor(src,temp,cv::COLOR_GRAY2RGB);
QImage img = QImage((uchar*)temp.data,temp.cols,temp.rows,temp.step,QImage::Format_RGB888);
ui->label->setPixmap(QPixmap::fromImage(img));
ui->label->resize(ui->label->pixmap()->size());
filename.clear();
}
这里使用了QImage::QImage (uchar * data, int width, int height, int bytesPerLine, Format format)
构造函数,否则可能出现无法正确显示图像的错误(下图右)。