Пример #1
0
def array_to_qimage(arr, copy=False):
    """Convert NumPy array to QImage object"""
    # https://gist.githubusercontent.com/smex/5287589/raw/toQImage.py
    if arr is None:
        return QImage()
    if len(arr.shape) not in (2, 3):
        raise NotImplementedError("Unsupported array shape %r" % arr.shape)
    data = arr.data
    ny, nx = arr.shape[:2]
    stride = arr.strides[0]  # bytes per line
    color_dim = None
    if len(arr.shape) == 3:
        color_dim = arr.shape[2]
    if arr.dtype == np.uint8:
        if color_dim is None:
            qimage = QImage(data, nx, ny, stride, QImage.Format_Indexed8)
#            qimage.setColorTable([qRgb(i, i, i) for i in range(256)])
            qimage.setColorCount(256)
        elif color_dim == 3:
            qimage = QImage(data, nx, ny, stride, QImage.Format_RGB888)
        elif color_dim == 4:
            qimage = QImage(data, nx, ny, stride, QImage.Format_ARGB32)
        else:
            raise TypeError("Invalid third axis dimension (%r)" % color_dim)
    elif arr.dtype == np.uint32:
        qimage = QImage(data, nx, ny, stride, QImage.Format_ARGB32)
    else:
        raise NotImplementedError("Unsupported array data type %r" % arr.dtype)
    if copy:
        return qimage.copy()
    return qimage
Пример #2
0
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')