学习Qt中使用OpenCV处理并显示图片程序框架(QMainWindow)

参考教程:https://blog.csdn.net/qingyang8513/article/details/80378491

本次我们将图片嵌入到Qt界面中。

      OpenCV3.0以后,图像采用Mat格式进行存储,Qt中图像存储采用的是QImage类,因此,如果需要再Qt中显示OpenCV处理过程中的图像,需要将Mat类对象表示的图像转换为QImage类对象表示的图像。同时,由Mat格式采用BGR的存储顺序,而QImage格式采用的是RGB存储顺序,因此,转换过程分为两步:

      1)存储格式转换:BGR --> RGB;

      2)类型转换:Mat类 ---> QImage;

      完成QImage类对象转换后,在Qt界面中显示QImage类对象,可以采用QLabel或者QGraphicsView,两种方法分别如下面的示例所示。

创建基于QMainWindow的Qt项目

pro文件:

#-------------------------------------------------
#
# Project created by QtCreator 2019-07-11T15:22:53
#
#-------------------------------------------------

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = OpenCV_ShowImage
TEMPLATE = app

# The following define makes your compiler emit warnings if you use
# any feature of Qt which has been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

CONFIG += c++11

SOURCES += \
        main.cpp \
        mainwindow.cpp

HEADERS += \
        mainwindow.h

FORMS += \
        mainwindow.ui

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target



INCLUDEPATH += $$PWD/../opencv_qt/include\
             $$PWD/../opencv_qt/include/opencv\
              $$PWD/../opencv_qt/include/opencv2

unix|win32: LIBS += -L$$PWD/../opencv_qt/bin/ -llibopencv_calib3d410
unix|win32: LIBS += -L$$PWD/../opencv_qt/bin/ -llibopencv_core410
unix|win32: LIBS += -L$$PWD/../opencv_qt/bin/ -llibopencv_dnn410
unix|win32: LIBS += -L$$PWD/../opencv_qt/bin/ -llibopencv_features2d410
unix|win32: LIBS += -L$$PWD/../opencv_qt/bin/ -llibopencv_flann410
unix|win32: LIBS += -L$$PWD/../opencv_qt/bin/ -llibopencv_highgui410
unix|win32: LIBS += -L$$PWD/../opencv_qt/bin/ -llibopencv_imgcodecs410
unix|win32: LIBS += -L$$PWD/../opencv_qt/bin/ -llibopencv_imgproc410
unix|win32: LIBS += -L$$PWD/../opencv_qt/bin/ -llibopencv_ml410
unix|win32: LIBS += -L$$PWD/../opencv_qt/bin/ -llibopencv_objdetect410
unix|win32: LIBS += -L$$PWD/../opencv_qt/bin/ -llibopencv_photo410
unix|win32: LIBS += -L$$PWD/../opencv_qt/bin/ -llibopencv_stitching410
unix|win32: LIBS += -L$$PWD/../opencv_qt/bin/ -llibopencv_video410
unix|win32: LIBS += -L$$PWD/../opencv_qt/bin/ -llibopencv_videoio410
unix|win32: LIBS += -L$$PWD/../opencv_qt/bin/ -lopencv_ffmpeg410

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

#include "opencv2/opencv.hpp"//OpenCV文件包含
using namespace cv;          //OpenCV命名空间

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;
};

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

/*
 * 使用QLabel显示图像
*/
void MainWindow::on_pushButton_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this,tr("Open Image"),".",tr("Image File(*.png *.jpg *.jpeg *.bmp)"));
    if (fileName.isEmpty())
    {
        return;
    }

    ui->stackedWidget->setCurrentIndex(0);

    Mat srcImage = imread(fileName.toLatin1().data());//读取图片数据
    cvtColor(srcImage, srcImage, COLOR_BGR2RGB);//图像格式转换
    QImage disImage = QImage((const unsigned char*)(srcImage.data),srcImage.cols,srcImage.rows,QImage::Format_RGB888);
    ui->label->setPixmap(QPixmap::fromImage(disImage.scaled(ui->label->size(), Qt::KeepAspectRatio)));//显示图像
}

/*
 * 使用QGraphicsView显示图像
*/
void MainWindow::on_pushButton_2_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this,tr("Open Image"),".",tr("Image File(*.png *.jpg *.jpeg *.bmp)"));
    if (fileName.isEmpty())
    {
        return;
    }

    ui->stackedWidget->setCurrentIndex(1);

    Mat srcImage = imread(fileName.toLatin1().data());//读取图片数据
    cvtColor(srcImage, srcImage, COLOR_BGR2RGB);//图像格式转换
    QImage disImage = QImage((const unsigned char*)(srcImage.data),srcImage.cols,srcImage.rows,QImage::Format_RGB888);

    QGraphicsScene *scene = new QGraphicsScene;//图像显示
    scene->addPixmap(QPixmap::fromImage(disImage));
    ui->graphicsView->setScene(scene);
    ui->graphicsView->show();
}

mainwindow.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>430</width>
    <height>331</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralWidget">
   <widget class="QPushButton" name="pushButton">
    <property name="geometry">
     <rect>
      <x>170</x>
      <y>240</y>
      <width>75</width>
      <height>23</height>
     </rect>
    </property>
    <property name="text">
     <string>QLabel打开</string>
    </property>
   </widget>
   <widget class="QPushButton" name="pushButton_2">
    <property name="geometry">
     <rect>
      <x>284</x>
      <y>240</y>
      <width>111</width>
      <height>23</height>
     </rect>
    </property>
    <property name="text">
     <string>QGraphicsView打开</string>
    </property>
   </widget>
   <widget class="QStackedWidget" name="stackedWidget">
    <property name="geometry">
     <rect>
      <x>80</x>
      <y>10</y>
      <width>331</width>
      <height>221</height>
     </rect>
    </property>
    <widget class="QWidget" name="page">
     <widget class="QLabel" name="label">
      <property name="geometry">
       <rect>
        <x>10</x>
        <y>30</y>
        <width>61</width>
        <height>61</height>
       </rect>
      </property>
      <property name="text">
       <string>TextLabel</string>
      </property>
     </widget>
    </widget>
    <widget class="QWidget" name="page_2">
     <widget class="QGraphicsView" name="graphicsView">
      <property name="geometry">
       <rect>
        <x>30</x>
        <y>10</y>
        <width>256</width>
        <height>192</height>
       </rect>
      </property>
     </widget>
    </widget>
   </widget>
  </widget>
  <widget class="QMenuBar" name="menuBar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>430</width>
     <height>23</height>
    </rect>
   </property>
  </widget>
  <widget class="QToolBar" name="mainToolBar">
   <attribute name="toolBarArea">
    <enum>TopToolBarArea</enum>
   </attribute>
   <attribute name="toolBarBreak">
    <bool>false</bool>
   </attribute>
  </widget>
  <widget class="QStatusBar" name="statusBar"/>
 </widget>
 <layoutdefault spacing="6" margin="11"/>
 <resources/>
 <connections/>
</ui>

编译后运行,qLabel显示图片

QGraphicsView显示图片

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在基于Qt的项目,如果我们想要将OpenCV读取的图像显示Qt界面,可以通过以下步骤实现。 首先,在mainwindow.h头文件,我们需要包含OpenCV的头文件,并使用cv命名空间。同时,我们还需要声明一个用于显示图像的成员变量,例如QLabel或QGraphicsView。以下是一个示例的mainwindow.h头文件内容: ```cpp #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <opencv2/opencv.hpp> // OpenCV文件包含 using namespace cv; // OpenCV命名空间 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; QLabel *imageLabel; // 用于显示图像的QLabel }; #endif // MAINWINDOW_H ``` 接下来,在mainwindow.cpp源文件,我们需要在构造函数创建一个QLabel对象,并将其添加到Qt界面的布局。在按钮点击事件的槽函数,我们可以使用OpenCV的imread函数读取图像,并将其显示在QLabel上。以下是一个示例的mainwindow.cpp源文件内容: ```cpp #include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); // 创建一个QLabel对象用于显示图像 imageLabel = new QLabel(this); ui->centralWidget->layout()->addWidget(imageLabel); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_pushButton_clicked() { // 从文件读取图像 Mat img = imread("image.jpg"); if (img.empty()) { fprintf(stderr, "Can not load image\n"); return; } // 将OpenCV的Mat对象转换为Qt的QImage对象 QImage qimg(img.data, img.cols, img.rows, img.step, QImage::Format_RGB888); // 将QImage对象显示在QLabel上 imageLabel->setPixmap(QPixmap::fromImage(qimg)); imageLabel->setScaledContents(true); } void MainWindow::on_pushButton_2_clicked() { // 清空QLabel上的图像 imageLabel->clear(); } ``` 在上述示例,我们在按钮点击事件的槽函数使用imread函数读取图像,并将其转换为QImage对象。然后,我们将QImage对象显示在QLabel上,从而实现在Qt界面显示OpenCV读取的图像。 请注意,示例图像路径为"image.jpg",你需要根据实际情况修改为你的图像路径。另外,还需要在Qt的.pro文件添加对OpenCV库的链接。 希望以上信息对你有帮助!\[1\]\[2\]\[3\] #### 引用[.reference_title] - *1* *3* [【Qt_OpenCV基础篇 - 002】Qt使用OpenCV处理显示图片程序框架(QMainWindow)](https://blog.csdn.net/qingyang8513/article/details/80378491)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [使用Qt显示OpenCV读取的图片](https://blog.csdn.net/QtCompany/article/details/129087366)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值