def newToQImage(array): """Converts a numpy array to a QImage A Python version of PyQt4.Qwt5.toQImage(array) in PyQwt >= 5.2. Function written by Gerard Vermeulen """ if array.ndim != 2: raise RuntimeError('array must be 2-D') height, width = array.shape if array.dtype == numpy.uint8: # image = QImage(array, width, height, QImage.Format_Indexed8) # The next statement shows that QImage does not increase the # reference count of the buffer object to keep the data valid. image = Qt.QImage( array.tostring(), width, height, Qt.QImage.Format_Indexed8) image.setNumColors(256) for i in range(256): image.setColor(i, qRgb(i, i, i)) return image elif array.dtype == numpy.uint32: image = Qt.QImage( array.tostring(), width, height, Qt.QImage.Format_ARGB32) return image else: raise RuntimeError('array.dtype must be uint8 or uint32')
def oldToQImage(array): """Converts a numpy array to a QImage A Python version of PyQt4.Qwt5.toQImage(array) in PyQwt < 5.2. Function written by Gerard Vermeulen """ if array.ndim != 2: raise RuntimeError('array must be 2-D') nx, ny = array.shape # width, height xstride, ystride = array.strides if array.dtype == numpy.uint8: image = QImage(nx, ny, QImage.Format_Indexed8) f_array = numpy.reshape(array,(nx*ny,),order='F') for j in range(ny): pointer = image.scanLine(j) pointer.setsize(nx*array.itemsize) memory = numpy.frombuffer(pointer, numpy.uint8) first_value = j*nx last_value = (j+1)*nx memory[:] = f_array[first_value:last_value] image.setColorCount(256) for i in range(256): image.setColor(i, qRgb(i, i, i)) return image elif array.dtype == numpy.uint32: image = Qt.QImage( array.tostring(), width, height, Qt.QImage.Format_ARGB32) f_array = numpy.reshape(array,(nx*ny,),order='F') for j in xrange(ny): pointer = image.scanLine(j) pointer.setsize(nx*array.itemsize) memory = numpy.frombuffer(pointer, numpy.uint32) first_value = j*nx last_value = (j+1)*nx memory[:] = f_array[first_value:last_value] return image else: raise RuntimeError('array.dtype must be uint8 or uint32')