如何在Python中使用PyQt显示RGB图像?

时间:2019-07-17 14:24:31

标签: python-3.x pyqt5

我有一个名为rgb_array的具有3个通道(RGB)的矩阵阵列。

我想使用PyQt进行显示。

跟随stackoverflow中的一些(旧)帖子,我编写了以下代码(基于gym-minigrid

from PyQt5.QtGui import QPixmap
from PyQt5.QtGui import QImage
from PyQt5.QtWidgets import QLabel
from PyQt5.QtWidgets import QMainWindow, QWidget

class Window(QMainWindow):
    """
    Simple application window to render the environment into
    """

    def __init__(self):
        super().__init__()
        # Image label to display the rendering
        self.imgLabel = QLabel()

        # Create a main widget for the window
        mainWidget = QWidget(self)
        self.setCentralWidget(mainWidget)

        # Show the application window
        self.show()
        self.setFocus()

    def setPixmap(self, pixmap):
        self.imgLabel.setPixmap(pixmap)


rgb_array = ...  # my image
height, width, _ = rgb_array.shape
bytes_per_line = 3 * width

qt_img = QImage(rgb_array.data, width, height, bytes_per_line, QImage.Format_RGB888)
pixmap = QPixmap.fromImage(qt_img)

window = Window()

window.setPixmap(pixmap)

但是每次我运行它时,都会遇到细分错误。任何想法 ?谢谢!

1 个答案:

答案 0 :(得分:1)

尝试一下:

from PyQt5.QtGui import QPixmap, QImage
from PyQt5.QtWidgets import QMainWindow, QWidget, QLabel, QApplication, QGridLayout

import cv2

class Window(QMainWindow):
    """
    Simple application window to render the environment into
    """

    def __init__(self):
        super().__init__()
        # Image label to display the rendering
        self.imgLabel = QLabel()

        # Create a main widget for the window
        mainWidget = QWidget(self)
        self.setCentralWidget(mainWidget)

        layout = QGridLayout(mainWidget)        # +
        layout.addWidget(self.imgLabel)         # +

        # Show the application window
#        self.show()
        self.setFocus()

"""
rgb_array = 'im.png'    # my image
height, width, _ = rgb_array.shape
bytes_per_line = 3 * width
qt_img = QImage(rgb_array.data, width, height, bytes_per_line, QImage.Format_RGB888)
pixmap = QPixmap.fromImage(qt_img)
window = Window()
window.setPixmap(pixmap)
"""

if __name__ == '__main__':
    import sys

    rgb_array = cv2.imread('Ok.png')
    rgb_array = cv2.cvtColor(rgb_array, cv2.COLOR_BGR2RGB)
    h, w, ch = rgb_array.shape
    bytesPerLine = ch * w
    qImg = QImage(rgb_array.data, w, h, bytesPerLine, QImage.Format_RGB888)

    app = QApplication(sys.argv)

    w = Window()
    w.imgLabel.setPixmap(QPixmap.fromImage(qImg))

    w.show()
    sys.exit(app.exec_())

enter image description here