Skip to content

Instantly share code, notes, and snippets.

@Trevol
Forked from smex/toQImage.py
Created May 4, 2020 19:00
Show Gist options
  • Save Trevol/cc35d97fe422517003de4265431d6585 to your computer and use it in GitHub Desktop.
Save Trevol/cc35d97fe422517003de4265431d6585 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment