def rgb2qimage(rgb): """Convert the 3D numpy array `rgb` into a 32-bit QImage. `rgb` must have three dimensions with the vertical, horizontal and RGB image axes. ATTENTION: This QImage carries an attribute `ndimage` with a reference to the underlying numpy array that holds the data. On Windows, the conversion into a QPixmap does not copy the data, so that you have to take care that the QImage does not get garbage collected (otherwise PyQt will throw away the wrapper, effectively freeing the underlying memory - boom!).""" if len(rgb.shape) != 3: raise ValueError("rgb2QImage can only convert 3D arrays") if rgb.shape[2] not in (3, 4): raise ValueError( "rgb2QImage can expects the last dimension to contain exactly three (R,G,B) or four (R,G,B,A) channels") h, w, channels = rgb.shape # Qt expects 32bit BGRA data for color images: bgra = numpy.empty((h, w, 4), numpy.uint8, 'C') bgra[..., 0] = rgb[..., 2] bgra[..., 1] = rgb[..., 1] bgra[..., 2] = rgb[..., 0] if rgb.shape[2] == 3: bgra[..., 3].fill(255) fmt = QImage.Format_RGB32 else: bgra[..., 3] = rgb[..., 3] fmt = QImage.Format_ARGB32 result = QImage(bgra.data, w, h, fmt) result.ndarray = bgra return result
def gray2qimage(gray): """Convert the 2D numpy array `gray` into a 8-bit QImage with a gray colormap. The first dimension represents the vertical image axis. ATTENTION: This QImage carries an attribute `ndimage` with a reference to the underlying numpy array that holds the data. On Windows, the conversion into a QPixmap does not copy the data, so that you have to take care that the QImage does not get garbage collected (otherwise PyQt will throw away the wrapper, effectively freeing the underlying memory - boom!).""" if len(gray.shape) != 2: raise ValueError("gray2QImage can only convert 2D arrays") gray = numpy.require(gray, numpy.uint8, 'C') h, w = gray.shape result = QImage(gray.data, w, h, QImage.Format_Indexed8) result.ndarray = gray for i in range(256): result.setColor(i, QColor(i, i, i).rgb()) return result
bgra[..., 1] = rgb[..., 1] bgra[..., 2] = rgb[..., 0] if rgb.shape[2] == 3: bgra[..., 3].fill(255) fmt = QImage.Format_RGB32 else: bgra[..., 3] = rgb[..., 3] fmt = QImage.Format_ARGB32 result = QImage(bgra.data, w, h, fmt) result.ndarray = bgra return result if __name__ == '__main__': import pylab i = QImage() # i.load("qimage2ndarray_test.png") i.load("qimage2ndarray_test_lenna.jpg") v = qimage2numpy(i, "rec") v2 = qimage2numpy(i, "array") pylab.imshow(v2[..., 0]) pylab.show() # v is a recarray; make it MPL-compatible for showing: rgb = numpy.empty(v.shape + (3, ), dtype=numpy.uint8) rgb[..., 0] = v["r"] rgb[..., 1] = v["g"] rgb[..., 2] = v["b"] pylab.imshow(rgb) pylab.show()