上文已经讲过如何使用QT+OpenCV显示图片的问题,但是小伙伴们测试之后应该会发现,上一讲的方式不能显示中文路径下的图片。本讲就告诉大家,如何使用QT+OpenCV,读取并显示中文路径下的图片。
一、先建一个新的工程
二、工程创建完成,简单设置一下UI界面
三、代码部分的编写
1、首先还是在.pro文件中添加OpenCV相关库
2、头文件
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <QFileDialog>
using namespace cv;
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_pushButton_choose_img_clicked();
void on_pushButton_show_img_clicked();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
3、源文件
#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_choose_img_clicked()
{
//获取文件路径,并放入lineEdit
QString fileName = QFileDialog::getOpenFileName(
this,
tr("选择文件"),
".",
tr("*.png *.img *.jpg"));
this->ui->lineEdit_img->setText(fileName);//将文件路径放入lineEdit
}
void MainWindow::on_pushButton_show_img_clicked()
{
//从lineEdit拿到文件路径
QString FileName= this->ui->lineEdit_img->text();
//读取图片
std::string name=FileName.toLocal8Bit().toStdString();//设置为可以读取中文路径
Mat Image = cv::imread(name);
namedWindow( "my window", WINDOW_AUTOSIZE );
imshow( "my window", Image );//显示
}
4、报错的话执行一下“构建”→“执行qmake”。
四、接下来进行测试
1、运行程序,点击“选取图片”,进行图片选择
如图,选取完图片后,会在lineEdit中显示图片路径。
2、接着点击“显示”,图片就会展示出来。
五、小伙伴们应该能看出来,读取中文路径的方法最重要的就是这一句
std::string name=FileName.toLocal8Bit().toStdString();//设置为可以读取中文路径
这句代码的意思是将QString字符串转换为本地8位的QByteArray形式,再转换为string格式。如此就实现了中文路径下图片的读取与展示。
同时相信各位也发现了另一个问题,就是目前图片的展示与主界面都是分离的,那么如何将图片展示在主界面上呢?