下载opencv地址:
https://sourceforge.net/projects/opencvlibrary/files/
QtCreateor配置opencv库
1、将opencv解压安装到当前项目下,本人安装的是opencv-4.10.0-windows.exe
2、加上环境变量:D:\xxx\xxx\opencv\build\x64\vc16\bin
3、当前项目右键->添加库->外部库,如下图配置
4、配置完后,自动在.pro文件下追加
win32:CONFIG(release, debug|release): LIBS += -L$$PWD/opencv/build/x64/vc16/lib/ -lopencv_world4100
else:win32:CONFIG(debug, debug|release): LIBS += -L$$PWD/opencv/build/x64/vc16/lib/ -lopencv_world4100d
INCLUDEPATH += $$PWD/opencv/build/include
DEPENDPATH += $$PWD/opencv/build/include
4、当前项目右键->清除->重新构建
编写代码
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QDebug>
#include <opencv2/opencv.hpp>
using namespace cv;
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
QString imagePath = QFileDialog::getOpenFileName(this,"打开图片","D:/","(打开(*.png *.jpg *.bmp))");
Mat cvImage = imread(imagePath.toStdString());
if (cvImage.empty()) {
qDebug() << "Failed to load image";
return;
}
Mat image1;
cvtColor(cvImage,image1,COLOR_BGR2RGB);
QImage image((const unsigned char*)(image1.data), image1.cols, image1.rows, image1.step, QImage::Format_RGB888);
// 调整label的大小
int width = image1.cols;
int height = image1.rows;
if(width>600 && height>600){
double scale_percent = 50.0;
width = static_cast<int>(image1.cols * scale_percent / 100);
height = static_cast<int>(image1.rows * scale_percent / 100);
}
QSize labelSize(width, height);
// 设置label的大小
ui->label->setFixedSize(labelSize);
// 在label上显示图像并填充
ui->label->setPixmap(QPixmap::fromImage(image));
ui->label->setScaledContents(true);
ui->label->setAlignment(Qt::AlignCenter);
}