Last active
September 1, 2021 09:46
-
-
Save smex/5287589 to your computer and use it in GitHub Desktop.
Convert numpy arrays (from opencv) to QImage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from PyQt4.QtGui import QImage, qRgb | |
import numpy as np | |
class NotImplementedException: | |
pass | |
gray_color_table = [qRgb(i, i, i) for i in range(256)] | |
def toQImage(im, copy=False): | |
if im is None: | |
return QImage() | |
if im.dtype == np.uint8: | |
if len(im.shape) == 2: | |
qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_Indexed8) | |
qim.setColorTable(gray_color_table) | |
return qim.copy() if copy else qim | |
elif len(im.shape) == 3: | |
if im.shape[2] == 3: | |
qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_RGB888); | |
return qim.copy() if copy else qim | |
elif im.shape[2] == 4: | |
qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_ARGB32); | |
return qim.copy() if copy else qim | |
raise NotImplementedException |
To make this work, I had to do:
im = np.require(im, np.uint8, 'C')
qImage = toQImage(im)
As seen here.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Does this work? I always get an empty qim.