欢迎访问我的网站,希望内容对您有用,感兴趣的可以加入免费知识星球。

PyQt5系列教程(十六)显示opencv图片格式

PyQt5开发 迷途小书童 3年前 (2021-04-14) 3049次浏览 0个评论

软硬件环境

  • Windows 10 64bit
  • Anaconda3 with python 3.8
  • PyCharm 2021.1
  • PyQt 5.15

前言

很多朋友在做机器学习、深度学习项目时,往往都需要显示图形化的操作界面,那么第一个问题就来了,如何在 PyQt5 中显示 opencv 读取的图像?本篇,我们就来解决这个问题。

大家都知道,opencv 读取的图像是 BGR 格式,而 PyQt5 图像格式是 RGB 格式,因此想要在 PyQt5 中显示,就需要进行格式转换,另一个需要注意的是,在使用 opencvBGR 数据构建 QImage 对象时,图像格式应该使用 QImage.Format_RGB888

代码实践

我们设计一个最简单的界面,只有一个 QLabel 控件,使用它来承载 opencv 读取的图片数据。相关注释已经写在了代码里面。

import sys
import cv2
from PyQt5 import QtGui, QtWidgets

class Ui_MainWindow(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Ui_MainWindow, self).__init__(parent)

        self.ui_init()

        self.show_cv_image()

    def ui_init(self):
        '''
        画界面,非常简单,就一个label,用来承载图片
        :return:
        '''

        self.main_layout = QtWidgets.QHBoxLayout()
        self.label_image = QtWidgets.QLabel()
        self.main_layout.addWidget(self.label_image)
        self.setLayout(self.main_layout)

    def show_cv_image(self):
        '''
        使用cv2读取图片并显示
        :return:
        '''

        image = cv2.imread('logo.png')
        image = cv2.resize(image, (1200, 300))
        result = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        show_image = QtGui.QImage(result.data, result.shape[1], result.shape[0], QtGui.QImage.Format_RGB888)
        self.label_image.setPixmap(QtGui.QPixmap.fromImage(show_image))

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    ui = Ui_MainWindow()
    ui.show()
    sys.exit(app.exec_())

执行上述代码,可以得到

pyqt5_opencv

源码下载

https://github.com/xugaoxiang/learningPyQt5

喜欢 (0)

您必须 登录 才能发表评论!