def render(self): # simplified pg.ImageITem if self.image is None or self.image.size == 0: return if isinstance(self.lut, collections.Callable): lut = self.lut(self.image) else: lut = self.lut image = self.image levels = self.levels if self.axisOrder == 'col-major': image = image.transpose((1, 0, 2)[:image.ndim]) argb, alpha = pg.makeARGB(image, lut=lut, levels=levels) # format is bgra argb[np.isnan(image)] = (100, 100, 100, 255) # replace unknown values with a color w = 1 if np.any(self.selection): max_sel = np.max(self.selection) colors = DiscreteVariable(values=map(str, range(max_sel))).colors fargb = argb.astype(np.float32) for i, color in enumerate(colors): color = np.hstack((color[::-1], [255])) # qt color sel = self.selection == i+1 # average the current color with the selection color argb[sel] = (fargb[sel] + w*color) / (1+w) alpha = True argb[:, :, 3] = np.maximum((self.selection > 0)*255, 100) self.qimage = pg.makeQImage(argb, alpha, transpose=False)
def render(self): #Convert data to QImage for display. #profile = debug.Profiler() if self.image is None or self.image.size == 0: return if isinstance(self.lut, collections.Callable): lut = self.lut(self.image) else: lut = self.lut if False:#self.autoDownsample: # reduce dimensions of image based on screen resolution o = self.mapToDevice(QtCore.QPointF(0,0)) x = self.mapToDevice(QtCore.QPointF(1,0)) y = self.mapToDevice(QtCore.QPointF(0,1)) w = Point(x-o).length() h = Point(y-o).length() xds = int(1/max(1, w)) yds = int(1/max(1, h)) image = pg.downsample(self.image, xds, axis=0) image = pg.downsample(image, yds, axis=1) else: image = self.image imageRGBA = makeRGBAImage(image,self.cppLut) imageNew = imageRGBA argb, alpha = pg.makeARGB(imageNew.transpose((1, 0, 2)[:imageNew.ndim]), lut=None, levels=None) self.qimage = pg.makeQImage(argb, alpha, transpose=False)
def makeARGB(*args, **kwds): img, alpha = pg.makeARGB(*args, **kwds) if kwds.get('useRGBA'): # endian independent out = img elif sys.byteorder == 'little': # little-endian ARGB32 to B,G,R,A out = img else: # big-endian ARGB32 to B,G,R,A out = img[..., [3, 2, 1, 0]] return out, alpha
def render(self): # simplified pg.ImageITem if self.image is None or self.image.size == 0: return if isinstance(self.lut, collections.Callable): lut = self.lut(self.image) else: lut = self.lut image = self.image levels = self.levels if self.axisOrder == 'col-major': image = image.transpose((1, 0, 2)[:image.ndim]) argb, alpha = pg.makeARGB(image, lut=lut, levels=levels) argb[np.isnan(image)] = (100, 100, 100, 255 ) # replace unknown values with a color self.qimage = pg.makeQImage(argb, alpha, transpose=False)
def test_makeARGB(): # Many parameters to test here: # * data dtype (ubyte, uint16, float, others) # * data ndim (2 or 3) # * levels (None, 1D, or 2D) # * lut dtype # * lut size # * lut ndim (1 or 2) # * useRGBA argument # Need to check that all input values map to the correct output values, especially # at and beyond the edges of the level range. def checkArrays(a, b): # because py.test output is difficult to read for arrays if not np.all(a == b): comp = [] for i in range(a.shape[0]): if a.shape[1] > 1: comp.append('[') for j in range(a.shape[1]): m = a[i, j] == b[i, j] comp.append( '%d,%d %s %s %s%s' % (i, j, str(a[i, j]).ljust(15), str(b[i, j]).ljust(15), m, ' ********' if not np.all(m) else '')) if a.shape[1] > 1: comp.append(']') raise Exception("arrays do not match:\n%s" % '\n'.join(comp)) def checkImage(img, check, alpha, alphaCheck): assert img.dtype == np.ubyte assert alpha is alphaCheck if alpha is False: checkArrays(img[..., 3], 255) if np.isscalar(check) or check.ndim == 3: checkArrays(img[..., :3], check) elif check.ndim == 2: checkArrays(img[..., :3], check[..., np.newaxis]) elif check.ndim == 1: checkArrays(img[..., :3], check[..., np.newaxis, np.newaxis]) else: raise Exception('invalid check array ndim') # uint8 data tests im1 = np.arange(256).astype('ubyte').reshape(256, 1) im2, alpha = pg.makeARGB(im1, levels=(0, 255)) checkImage(im2, im1, alpha, False) im3, alpha = pg.makeARGB(im1, levels=(0.0, 255.0)) checkImage(im3, im1, alpha, False) im4, alpha = pg.makeARGB(im1, levels=(255, 0)) checkImage(im4, 255 - im1, alpha, False) im5, alpha = pg.makeARGB(np.concatenate([im1] * 3, axis=1), levels=[(0, 255), (0.0, 255.0), (255, 0)]) checkImage(im5, np.concatenate([im1, im1, 255 - im1], axis=1), alpha, False) im2, alpha = pg.makeARGB(im1, levels=(128, 383)) checkImage(im2[:128], 0, alpha, False) checkImage(im2[128:], im1[:128], alpha, False) # uint8 data + uint8 LUT lut = np.arange(256)[::-1].astype(np.uint8) im2, alpha = pg.makeARGB(im1, lut=lut) checkImage(im2, lut, alpha, False) # lut larger than maxint lut = np.arange(511).astype(np.uint8) im2, alpha = pg.makeARGB(im1, lut=lut) checkImage(im2, lut[::2], alpha, False) # lut smaller than maxint lut = np.arange(128).astype(np.uint8) im2, alpha = pg.makeARGB(im1, lut=lut) checkImage(im2, np.linspace(0, 127.5, 256, dtype='ubyte'), alpha, False) # lut + levels lut = np.arange(256)[::-1].astype(np.uint8) im2, alpha = pg.makeARGB(im1, lut=lut, levels=[-128, 384]) checkImage(im2, np.linspace(191.5, 64.5, 256, dtype='ubyte'), alpha, False) im2, alpha = pg.makeARGB(im1, lut=lut, levels=[64, 192]) checkImage( im2, np.clip(np.linspace(384.5, -127.5, 256), 0, 255).astype('ubyte'), alpha, False) # uint8 data + uint16 LUT lut = np.arange(4096)[::-1].astype(np.uint16) // 16 im2, alpha = pg.makeARGB(im1, lut=lut) checkImage(im2, np.arange(256)[::-1].astype('ubyte'), alpha, False) # uint8 data + float LUT lut = np.linspace(10., 137., 256) im2, alpha = pg.makeARGB(im1, lut=lut) checkImage(im2, lut.astype('ubyte'), alpha, False) # uint8 data + 2D LUT lut = np.zeros((256, 3), dtype='ubyte') lut[:, 0] = np.arange(256) lut[:, 1] = np.arange(256)[::-1] lut[:, 2] = 7 im2, alpha = pg.makeARGB(im1, lut=lut) checkImage(im2, lut[:, None, ::-1], alpha, False) # check useRGBA im2, alpha = pg.makeARGB(im1, lut=lut, useRGBA=True) checkImage(im2, lut[:, None, :], alpha, False) # uint16 data tests im1 = np.arange(0, 2**16, 256).astype('uint16')[:, None] im2, alpha = pg.makeARGB(im1, levels=(512, 2**16)) checkImage(im2, np.clip(np.linspace(-2, 253, 256), 0, 255).astype('ubyte'), alpha, False) lut = (np.arange(512, 2**16)[::-1] // 256).astype('ubyte') im2, alpha = pg.makeARGB(im1, lut=lut, levels=(512, 2**16 - 256)) checkImage(im2, np.clip(np.linspace(257, 2, 256), 0, 255).astype('ubyte'), alpha, False) lut = np.zeros(2**16, dtype='ubyte') lut[1000:1256] = np.arange(256) lut[1256:] = 255 im1 = np.arange(1000, 1256).astype('uint16')[:, None] im2, alpha = pg.makeARGB(im1, lut=lut) checkImage(im2, np.arange(256).astype('ubyte'), alpha, False) # float data tests im1 = np.linspace(1.0, 17.0, 256)[:, None] im2, alpha = pg.makeARGB(im1, levels=(5.0, 13.0)) checkImage(im2, np.clip(np.linspace(-128, 383, 256), 0, 255).astype('ubyte'), alpha, False) lut = (np.arange(1280)[::-1] // 10).astype('ubyte') im2, alpha = pg.makeARGB(im1, lut=lut, levels=(1, 17)) checkImage(im2, np.linspace(127.5, 0, 256).astype('ubyte'), alpha, False) # test sanity checks class AssertExc(object): def __init__(self, exc=Exception): self.exc = exc def __enter__(self): return self def __exit__(self, *args): assert args[0] is self.exc, "Should have raised %s (got %s)" % ( self.exc, args[0]) return True with AssertExc(TypeError): # invalid image shape pg.makeARGB(np.zeros((2, ), dtype='float')) with AssertExc(TypeError): # invalid image shape pg.makeARGB(np.zeros((2, 2, 7), dtype='float')) with AssertExc(): # float images require levels arg pg.makeARGB(np.zeros((2, 2), dtype='float')) with AssertExc(): # bad levels arg pg.makeARGB(np.zeros((2, 2), dtype='float'), levels=[1]) with AssertExc(): # bad levels arg pg.makeARGB(np.zeros((2, 2), dtype='float'), levels=[1, 2, 3]) with AssertExc(): # can't mix 3-channel levels and LUT pg.makeARGB(np.zeros((2, 2)), lut=np.zeros((10, 3), dtype='ubyte'), levels=[(0, 1)] * 3) with AssertExc( ): # multichannel levels must have same number of channels as image pg.makeARGB(np.zeros((2, 2, 3), dtype='float'), levels=[(1, 2)] * 4) with AssertExc(): # 3d levels not allowed pg.makeARGB(np.zeros((2, 2, 3), dtype='float'), levels=np.zeros([3, 2, 2]))
def img2tex(image): x = image.transpose(1, 0, 2) texture, _ = pg.makeARGB(x, useRGBA=True) return texture
z_yaxis = np.zeros(10) pts_yaxis = np.vstack([yaxis, z_yaxis, x_yaxis]).transpose() plt_yaxis = gl.GLLinePlotItem(pos=pts_yaxis, color=axis_color, width=linewidthaxis, antialias=True) wGL.addItem(plt_yaxis) ## make x-axis xaxis = np.linspace(-x_length, x_length, 10) y_xaxis = np.zeros(10) z_xaxis = np.zeros(10) pts_xaxis = np.vstack([y_xaxis, z_xaxis, xaxis]).transpose() plt_xaxis = gl.GLLinePlotItem(pos=pts_xaxis, color=axis_color, width=linewidthaxis, antialias=True) wGL.addItem(plt_xaxis) ## make image for x-y plane image_shape = (2, 2) uniform_values = np.ones(image_shape) * 255 uniform_image_transparent = pg.makeARGB(uniform_values)[0] uniform_image_transparent[:, :, 3] = 100 v1 = gl.GLImageItem(uniform_image_transparent) v1.translate(-image_shape[0] / 2.0, -image_shape[1] / 2.0, 0) v1.rotate(90, 1, 0, 0) wGL.addItem(v1) # Set up some animation parameters frametime = 50 # frame refresh time in ms velocity = 1.0 / frametime counter = 0 # Function to update scene for each frame def update(): global z, z0, velocity, counter, amplitude global plt_e, rot_efield_coord, plt_e_z0, plt_arrow # , plt_e_lines
def test_makeARGB(): # Many parameters to test here: # * data dtype (ubyte, uint16, float, others) # * data ndim (2 or 3) # * levels (None, 1D, or 2D) # * lut dtype # * lut size # * lut ndim (1 or 2) # * useRGBA argument # Need to check that all input values map to the correct output values, especially # at and beyond the edges of the level range. def checkArrays(a, b): # because py.test output is difficult to read for arrays if not np.all(a == b): comp = [] for i in range(a.shape[0]): if a.shape[1] > 1: comp.append('[') for j in range(a.shape[1]): m = a[i,j] == b[i,j] comp.append('%d,%d %s %s %s%s' % (i, j, str(a[i,j]).ljust(15), str(b[i,j]).ljust(15), m, ' ********' if not np.all(m) else '')) if a.shape[1] > 1: comp.append(']') raise Exception("arrays do not match:\n%s" % '\n'.join(comp)) def checkImage(img, check, alpha, alphaCheck): assert img.dtype == np.ubyte assert alpha is alphaCheck if alpha is False: checkArrays(img[..., 3], 255) if np.isscalar(check) or check.ndim == 3: checkArrays(img[..., :3], check) elif check.ndim == 2: checkArrays(img[..., :3], check[..., np.newaxis]) elif check.ndim == 1: checkArrays(img[..., :3], check[..., np.newaxis, np.newaxis]) else: raise Exception('invalid check array ndim') # uint8 data tests im1 = np.arange(256).astype('ubyte').reshape(256, 1) im2, alpha = pg.makeARGB(im1, levels=(0, 255)) checkImage(im2, im1, alpha, False) im3, alpha = pg.makeARGB(im1, levels=(0.0, 255.0)) checkImage(im3, im1, alpha, False) im4, alpha = pg.makeARGB(im1, levels=(255, 0)) checkImage(im4, 255-im1, alpha, False) im5, alpha = pg.makeARGB(np.concatenate([im1]*3, axis=1), levels=[(0, 255), (0.0, 255.0), (255, 0)]) checkImage(im5, np.concatenate([im1, im1, 255-im1], axis=1), alpha, False) im2, alpha = pg.makeARGB(im1, levels=(128,383)) checkImage(im2[:128], 0, alpha, False) checkImage(im2[128:], im1[:128], alpha, False) # uint8 data + uint8 LUT lut = np.arange(256)[::-1].astype(np.uint8) im2, alpha = pg.makeARGB(im1, lut=lut) checkImage(im2, lut, alpha, False) # lut larger than maxint lut = np.arange(511).astype(np.uint8) im2, alpha = pg.makeARGB(im1, lut=lut) checkImage(im2, lut[::2], alpha, False) # lut smaller than maxint lut = np.arange(128).astype(np.uint8) im2, alpha = pg.makeARGB(im1, lut=lut) checkImage(im2, np.linspace(0, 127, 256).astype('ubyte'), alpha, False) # lut + levels lut = np.arange(256)[::-1].astype(np.uint8) im2, alpha = pg.makeARGB(im1, lut=lut, levels=[-128, 384]) checkImage(im2, np.linspace(192, 65.5, 256).astype('ubyte'), alpha, False) im2, alpha = pg.makeARGB(im1, lut=lut, levels=[64, 192]) checkImage(im2, np.clip(np.linspace(385.5, -126.5, 256), 0, 255).astype('ubyte'), alpha, False) # uint8 data + uint16 LUT lut = np.arange(4096)[::-1].astype(np.uint16) // 16 im2, alpha = pg.makeARGB(im1, lut=lut) checkImage(im2, np.arange(256)[::-1].astype('ubyte'), alpha, False) # uint8 data + float LUT lut = np.linspace(10., 137., 256) im2, alpha = pg.makeARGB(im1, lut=lut) checkImage(im2, lut.astype('ubyte'), alpha, False) # uint8 data + 2D LUT lut = np.zeros((256, 3), dtype='ubyte') lut[:,0] = np.arange(256) lut[:,1] = np.arange(256)[::-1] lut[:,2] = 7 im2, alpha = pg.makeARGB(im1, lut=lut) checkImage(im2, lut[:,None,::-1], alpha, False) # check useRGBA im2, alpha = pg.makeARGB(im1, lut=lut, useRGBA=True) checkImage(im2, lut[:,None,:], alpha, False) # uint16 data tests im1 = np.arange(0, 2**16, 256).astype('uint16')[:, None] im2, alpha = pg.makeARGB(im1, levels=(512, 2**16)) checkImage(im2, np.clip(np.linspace(-2, 253, 256), 0, 255).astype('ubyte'), alpha, False) lut = (np.arange(512, 2**16)[::-1] // 256).astype('ubyte') im2, alpha = pg.makeARGB(im1, lut=lut, levels=(512, 2**16-256)) checkImage(im2, np.clip(np.linspace(257, 2, 256), 0, 255).astype('ubyte'), alpha, False) lut = np.zeros(2**16, dtype='ubyte') lut[1000:1256] = np.arange(256) lut[1256:] = 255 im1 = np.arange(1000, 1256).astype('uint16')[:, None] im2, alpha = pg.makeARGB(im1, lut=lut) checkImage(im2, np.arange(256).astype('ubyte'), alpha, False) # float data tests im1 = np.linspace(1.0, 17.0, 256)[:, None] im2, alpha = pg.makeARGB(im1, levels=(5.0, 13.0)) checkImage(im2, np.clip(np.linspace(-128, 383, 256), 0, 255).astype('ubyte'), alpha, False) lut = (np.arange(1280)[::-1] // 10).astype('ubyte') im2, alpha = pg.makeARGB(im1, lut=lut, levels=(1, 17)) checkImage(im2, np.linspace(127.5, 0, 256).astype('ubyte'), alpha, False) # test sanity checks class AssertExc(object): def __init__(self, exc=Exception): self.exc = exc def __enter__(self): return self def __exit__(self, *args): assert args[0] is self.exc, "Should have raised %s (got %s)" % (self.exc, args[0]) return True with AssertExc(TypeError): # invalid image shape pg.makeARGB(np.zeros((2,), dtype='float')) with AssertExc(TypeError): # invalid image shape pg.makeARGB(np.zeros((2,2,7), dtype='float')) with AssertExc(): # float images require levels arg pg.makeARGB(np.zeros((2,2), dtype='float')) with AssertExc(): # bad levels arg pg.makeARGB(np.zeros((2,2), dtype='float'), levels=[1]) with AssertExc(): # bad levels arg pg.makeARGB(np.zeros((2,2), dtype='float'), levels=[1,2,3]) with AssertExc(): # can't mix 3-channel levels and LUT pg.makeARGB(np.zeros((2,2)), lut=np.zeros((10,3), dtype='ubyte'), levels=[(0,1)]*3) with AssertExc(): # multichannel levels must have same number of channels as image pg.makeARGB(np.zeros((2,2,3), dtype='float'), levels=[(1,2)]*4) with AssertExc(): # 3d levels not allowed pg.makeARGB(np.zeros((2,2,3), dtype='float'), levels=np.zeros([3, 2, 2]))
def img2tex(img): x = cv.cvtColor(img, cv.COLOR_BGR2RGB) texture, _ = pg.makeARGB(x, useRGBA=True) return texture
import numpy as np import pyqtgraph as pg lut1 = np.array([(0, 0, 0), (1, 1, 1), (2, 2, 2)]) vector = np.linspace(0.0, 1.0, 11) data = np.expand_dims(vector, axis=0) print("data: {}".format(data)) levels = np.amin(data), np.amax(data) for scale in [None, 2, 3]: res, _ = pg.makeARGB(data, lut1, levels=levels, scale=scale) # print("scale={}, res (shape {}): \n{}".format(scale, res.shape, res)) print("\nScale: {}".format(scale)) for idx, val in enumerate(vector): color = res[0, idx, :] print(" Value {:5.2f} -> RGBA {} ".format(val, color))
z_yaxis = np.zeros(10) pts_yaxis = np.vstack([yaxis, z_yaxis, x_yaxis]).transpose() plt_yaxis = gl.GLLinePlotItem(pos=pts_yaxis, width=linewidth, antialias=True) w.addItem(plt_yaxis) ## make x-axis xaxis = np.linspace(-x_length, x_length, 10) y_xaxis = np.zeros(10) z_xaxis = np.zeros(10) pts_xaxis = np.vstack([y_xaxis, z_xaxis, xaxis]).transpose() plt_xaxis = gl.GLLinePlotItem(pos=pts_xaxis, width=linewidth, antialias=True) w.addItem(plt_xaxis) ## make images image_shape = (8, 8) uniform_values = np.ones(image_shape) * 255 uniform_image_transparent = pg.makeARGB(uniform_values)[0] uniform_image_transparent[:, :, 3] = 65 v1 = gl.GLImageItem(uniform_image_transparent) v1.translate(-image_shape[0] / 2, -image_shape[1] / 2, 0) v1.rotate(90, 1, 0, 0) #w.addItem(v1) v = [] for i in range(0, 20): vtemp = gl.GLImageItem(uniform_image_transparent) vtemp.translate(-image_shape[0] / 2, -image_shape[1] / 2, 0) vtemp.rotate(90, 1, 0, 0) dz = float(i - 10) vtemp.translate(0, dz, 0) v.append(vtemp) w.addItem(v[i])
def preRender(self, image): imageRGBA = makeRGBAImage(image,self.cppLut) imageNew = imageRGBA argb, alpha = pg.makeARGB(imageNew.transpose((1, 0, 2)[:imageNew.ndim]), lut=None, levels=None) self.qimage = pg.makeQImage(argb, alpha, transpose=False)