0

I have a matrix array with 3 channels (RGB) named rgb_array.

I want to use PyQt to display it.

Following to some (old) posts in stackoverflow, I made the following code (based on 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)

But everytime I run it, I get a segmentation fault. Any idea ? Thanks !

dallonsi
  • 1,299
  • 1
  • 8
  • 29

1 Answers1

2

Try it:

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

S. Nick
  • 12,879
  • 8
  • 25
  • 33