Search code examples
python-3.xpyqt5python-imaging-libraryqdockwidget

How to display RGB image in pyqt


I Have a image in RBG Mode, when i try to display it on qdockWidget, the image does not appear properly. I can print the image in "L" mode. what i am missing. Thanks in Advance :)enter image description here

Below is the code:

from PyQt5 import QtWidgets, QtGui
from PyQt5.QtWidgets import (QApplication, QMainWindow)
from PyQt5.QtCore import Qt

from reportlab.graphics.shapes import *

from PIL import ImageQt
from PIL import Image, ImageDraw


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.resize(800, 600)

        dockWidget = QtWidgets.QDockWidget()
        dockWidget.setWindowTitle("Image Viewer")

        w, h = 220, 190
        shape = [(40, 40), (w - 10, h - 10)]

        # creating new Image object
        img = Image.new("RGB", (w, h))

        # create rectangleimage
        img1 = ImageDraw.Draw(img)
        img1.rectangle(shape, fill="#800080", outline="green")
        img.show()

        QtImage1 = ImageQt.ImageQt(img)
        QtImage2 = QtGui.QImage(QtImage1)
        pixmap = QtGui.QPixmap.fromImage(QtImage2)
        label = QtWidgets.QLabel('testing', self)
        label.setPixmap(pixmap)

        dockWidget.setWidget(label)
        dockWidget.setFloating(False)
        self.addDockWidget(Qt.RightDockWidgetArea, dockWidget)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    myWidget = MainWindow()
    myWidget.show()

    sys.exit(app.exec_())

Solution

  • The problem is that "img" and "QtImage1", "QtImage2" and "pixmap" share the same buffer that causes the error, the solution is to copy the image:

    qimage = ImageQt.ImageQt(img).copy()
    pixmap = QtGui.QPixmap.fromImage(qimage)
    label = QtWidgets.QLabel()
    label.setPixmap(pixmap)