Skip to content

Instantly share code, notes, and snippets.

@smex
Last active September 1, 2021 09:46
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save smex/5287589 to your computer and use it in GitHub Desktop.
Save smex/5287589 to your computer and use it in GitHub Desktop.
Convert numpy arrays (from opencv) to QImage
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
@fepegar
Copy link

fepegar commented Feb 14, 2017

Does this work? I always get an empty qim.

@fepegar
Copy link

fepegar commented Feb 20, 2017

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