How to convert Numpy image to QImage?

When writing the GUI code in Qt for a deep learning system, a general problem is to convert an image (read from disk or camera using OpenCV) in the form of a Numpy array, to a QImage to be shown in a form or widget.

There are basically two problems: Numpy array’s data type has usually more than 8 bits and OpenCV reads the image in BGR format rather than the more general RGB.

The following Python (> 3.5) code shows how to solve these:

import PySide2.QtGui as qtg

def get_qimage(image: np.ndarray):
    assert (np.max(image) <= 255)
    image8 = image.astype(np.uint8, order='C', casting='unsafe')
    height, width, colors = image8.shape
    bytesPerLine = 3 * width

    image = qtg.QImage(image8.data, width, height, bytesPerLine,
                       qtg.QImage.Format_RGB888)

    image = image.rgbSwapped()
    return image