Numpy grayscale array (2D) to RGB QImage or QPixmap in either red, green or blue



  • Hi,
    I need to convert a numpy array to a QImage (or QPixmap), I tried passing my array as the argument to QImage constructor and I also tried the .tobytes but the produced image doesn't seem correct.
    I am having a hard time with this and been working on it for over a day, some help would be very appreciated.
    I am using PySide2 on OS X.

    Thank you!



  • So I solved my problem.
    It turns out QImage needs the image to be a flat numpy array.
    Here is how it's done:

            qrgb_dict = {'r': lambda x: QtGui.qRgb(x, 0, 0),
                         'g': lambda x: QtGui.qRgb(0, x, 0),
                         'b': lambda x: QtGui.qRgb(0, 0, x)}
            colortable = [qrgb_dict[color](i) for i in range(256)]
            img = QtGui.QImage(arr, w, h, w, QtGui.QImage.Format_Indexed8)
            img.setColorTable(colortable)
    

    Where arr is an array of shape (h,w) and with uint8 values in 0-255


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.