コード例 #1
0
def numpy2qimage(data, colortable=GRAY_COLORTABLE):
    '''Convert a numpy array into a QImage.

    .. note:: requires sip >= 4.7.5.

    '''

    has_colortable = False

    if data.dtype in (np.uint8, np.ubyte, np.byte):
        if data.ndim == 2:
            h, w = data.shape
            image = _aligned(data)
            format_ = QtGui.QImage.Format_Indexed8
            has_colortable = True

        elif data.ndim == 3 and data.shape[2] == 3:
            h, w = data.shape[:2]
            image = np.zeros((h, w, 4), data.dtype)
            image[:, :, 2::-1] = data
            image[..., -1] = 255
            format_ = QtGui.QImage.Format_RGB32

        elif data.ndim == 3 and data.shape[2] == 4:
            h, w = data.shape[:2]
            image = np.require(data, np.uint8, 'CO')  # 'CAO'
            format_ = QtGui.QImage.Format_ARGB32

        else:
            raise ValueError('unable to convert data: shape=%s, '
                             'dtype="%s"' % (data.shape,
                                             np.dtype(data.dtype)))

    elif data.dtype == np.uint16 and data.ndim == 2:
        # @TODO: check
        h, w = data.shape
        image = _aligned(data)
        format_ = QtGui.QImage.Format_RGB16

    elif data.dtype == np.uint32 and data.ndim == 2:
        h, w = data.shape
        image = np.require(data, data.dtype, 'CO')  # 'CAO'
        #format_ = QtGui.QImage.Format_ARGB32
        format_ = QtGui.QImage.Format_RGB32

    else:
        raise ValueError(
            'unable to convert data: shape=%s, dtype="%s"' % (
                data.shape, np.dtype(data.dtype)))

    result = QtGui.QImage(image.data, w, h, format_)
    result.ndarray = image
    if has_colortable:
        result.setColorTable(colortable)

    return result
コード例 #2
0
    def onOpen(self):
        filters = [
            self.tr('All files (*)'),
        ]
        filters.extend('%s file (*.%s)' % (str(f).upper(), str(f))
                       for f in QtGui.QImageReader.supportedImageFormats())

        filename, filter_ = QtWidgets.QFileDialog.getOpenFileName(
            self, self.tr('Load picture'),
            QtCore.QDir.home().absolutePath(),
            ';;'.join(filters))  # , filters[1])
        if filename:
            if '.svg' in filename:
                item = QtSvg.QGraphicsSvgItem(filename)
            else:
                image = QtGui.QImage(filename)
                item = QtWidgets.QGraphicsPixmapItem(image)

            item.setFlag(QtWidgets.QGraphicsItem.ItemIsSelectable, True)
            item.setFlag(QtWidgets.QGraphicsItem.ItemIsMovable, True)

            self.scene.addItem(item)