Posted on :: Tags: , , , ,

When writing Qt GUI code for a deep learning system, a common task is converting an image (read from disk or camera using OpenCV) from a NumPy array to a QImage for display in a widget.

There are basically two problems to address: NumPy arrays often have data types with more than 8 bits, and OpenCV reads images in BGR format rather than the more common RGB.

The following Python (3.5+) code demonstrates the solution:

import PySide2.QtGui as qtg
import numpy as np

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