Beispiel #1
0
def imread(filename):
    """
    Read an image using QT's QImage.load
    """
    qtimg = QImage()
    if not qtimg.load(filename):
        # QImage.load() returns false on failure, so raise an exception
        raise IOError('Unable to load file %s' % filename)
    if qtimg.depth() == 1:
        raise IOError('1-bit images currently not supported')
    # TODO: Warn about other odd formats we don't currently handle properly,
    # such as the odd 16-bit packed formats QT supports
    arrayptr = qtimg.bits()
    # QT may pad the image, so we need to use bytesPerLine, not width for
    # the conversion to a numpy array
    bytes_per_pixel = qtimg.depth() // 8
    pixels_per_line = qtimg.bytesPerLine() // bytes_per_pixel
    img_size = pixels_per_line * qtimg.height() * bytes_per_pixel
    arrayptr.setsize(img_size)
    img = np.array(arrayptr)
    # Reshape and trim down to correct dimensions
    if bytes_per_pixel > 1:
        img = img.reshape((qtimg.height(), pixels_per_line, bytes_per_pixel))
        img = img[:, :qtimg.width(), :]
    else:
        img = img.reshape((qtimg.height(), pixels_per_line))
        img = img[:, :qtimg.width()]
    # Strip qt's false alpha channel if needed
    # and reorder color axes as required
    if bytes_per_pixel == 4 and not qtimg.hasAlphaChannel():
        img = img[:, :, 2::-1]
    elif bytes_per_pixel == 4:
        img[:, :, 0:3] = img[:, :, 2::-1]
    return img
Beispiel #2
0
    def resizeEvent(self, event):
        old = QImage(self.m_image)

        width = max(self.geometry().width(), old.width())
        height = max(self.geometry().height(), old.height())

        if width > old.width() or height > old.height():
            self.m_image = QImage(width, height, QImage.Format_RGB32)
            self.m_image.fill(colorTable[self.m_backgroundColorIndex %
                                         len(colorTable)].rgba())
            p = QPainter(self.m_image)
            p.drawImage(0, 0, old)

        self.scheduleRender()
Beispiel #3
0
def ConvertQtImageToNumPy(qt_image: QG.QImage):

    width = qt_image.width()
    height = qt_image.height()

    if qt_image.depth() == 1:

        # this is probably super wrong, but whatever for now
        depth = 1

    else:

        # 8, 24, 32 etc...
        depth = qt_image.depth() // 8

    data_bytearray = qt_image.bits()

    if QP.qtpy.PYSIDE2:

        data_bytes = bytes(data_bytearray)

    elif QP.qtpy.PYQT5:

        data_bytes = data_bytearray.asstring(height * width * depth)

    numpy_image = numpy.fromstring(data_bytes, dtype='uint8').reshape(
        (height, width, depth))

    return numpy_image
Beispiel #4
0
def imread(filename):
    """
    Read an image using QT's QImage.load
    """
    warn(
        '`qt` plugin is deprecated and will be removed in 0.20. '
        'For alternatives, refer to '
        'https://scikit-image.org/docs/stable/user_guide/visualization.html',
        FutureWarning,
        stacklevel=2)
    qtimg = QImage()
    if not qtimg.load(filename):
        # QImage.load() returns false on failure, so raise an exception
        raise IOError('Unable to load file %s' % filename)
    if qtimg.depth() == 1:
        raise IOError('1-bit images currently not supported')
    # TODO: Warn about other odd formats we don't currently handle properly,
    # such as the odd 16-bit packed formats QT supports
    arrayptr = qtimg.bits()
    # QT may pad the image, so we need to use bytesPerLine, not width for
    # the conversion to a numpy array
    bytes_per_pixel = qtimg.depth() // 8
    pixels_per_line = qtimg.bytesPerLine() // bytes_per_pixel
    img_size = pixels_per_line * qtimg.height() * bytes_per_pixel
    arrayptr.setsize(img_size)
    img = np.array(arrayptr)
    # Reshape and trim down to correct dimensions
    if bytes_per_pixel > 1:
        img = img.reshape((qtimg.height(), pixels_per_line, bytes_per_pixel))
        img = img[:, :qtimg.width(), :]
    else:
        img = img.reshape((qtimg.height(), pixels_per_line))
        img = img[:, :qtimg.width()]
    # Strip qt's false alpha channel if needed
    # and reorder color axes as required
    if bytes_per_pixel == 4 and not qtimg.hasAlphaChannel():
        img = img[:, :, 2::-1]
    elif bytes_per_pixel == 4:
        img[:, :, 0:3] = img[:, :, 2::-1]
    return img
Beispiel #5
0
    def show_image(self, img):
        self.resize(200, 200)

        try:
            rgb_image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        except cv2.error:
            return

        h, w, ch = rgb_image.shape
        bytes_per_line = ch * w
        qt_image = QImage(rgb_image.data, w, h, bytes_per_line, QImage.Format_RGB888)
        img_w = qt_image.width()
        img_h = qt_image.height()
        proportion = img_w / img_h
        self.resize(self.width() * proportion, self.height())
        qt_image = qt_image.scaled(self.width(), self.height())
        self.setPixmap(QPixmap(qt_image))
        self.node.update_shape()
Beispiel #6
0
def get_font_array(sz, chars=DEFAULT_CHARS):
    from qtpy.QtGui import QFont, QPainter, QColor

    font = QFont()
    font.setFixedPitch(True)
    font.setPixelSize(int(sz))
    font.setStyleStrategy(QFont.NoAntialias)
    dummy = QImage(10, 10, QImage.Format_ARGB32)
    pnt = QPainter(dummy)
    pnt.setFont(font)
    metric = pnt.fontMetrics()
    rct = metric.boundingRect(chars)
    pnt.end()
    h = rct.height()
    w = rct.width()
    img = QImage(w, h, QImage.Format_ARGB32)
    paint = QPainter()
    paint.begin(img)
    paint.setFont(font)
    paint.setBrush(QColor(255, 255, 255))
    paint.setPen(QColor(255, 255, 255))
    paint.drawRect(0, 0, w + 1, h + 1)
    paint.setPen(QColor(0, 0, 0))
    paint.setBrush(QColor(0, 0, 0))
    paint.drawText(0, paint.fontMetrics().ascent(), chars)
    paint.end()
    try:
        try:
            # PyQt4 (at least until Qt 4.8)
            data = img.bits().asstring(img.numBytes())
        except AttributeError:
            if PYSIDE2:
                # PySide2
                data = bytes(img.bits())
            else:
                # PyQt5
                data = img.bits().asstring(img.byteCount())
    except SystemError:
        # PyQt4 (4.11.3) and PyQt5 (5.3.2) on Python 3
        return
    npy = np.frombuffer(data, np.uint8)
    npy.shape = img.height(), int(img.bytesPerLine() / 4), 4
    return npy[:, :, 0]
Beispiel #7
0
def graph2icon(g: Graph,
               width: int,
               node_mode: bool,
               show_label: bool,
               monochrome: bool,
               *,
               except_node: Optional[int] = None,
               engine: str = "",
               pos: Optional[_Pos] = None) -> QIcon:
    """Draw a generalized chain graph."""
    if engine:
        pos = engine_picker(g, engine, node_mode)
    if pos is None:
        raise ValueError("no engine selected")
    if not pos:
        pixmap = QPixmap(width, width)
        pixmap.fill(Qt.transparent)
        return QIcon(pixmap)

    width_bound = -float('inf')
    for x, y in pos.values():
        if abs(x) > width_bound:
            width_bound = x
        if abs(y) > width_bound:
            width_bound = y
    width_bound *= 2.5
    image = QImage(QSize(int(width_bound), int(width_bound)),
                   QImage.Format_ARGB32_Premultiplied)
    image.fill(Qt.transparent)
    painter = QPainter(image)
    painter.translate(image.width() / 2, image.height() / 2)
    pen = QPen()
    r = int(width_bound / 50)
    pen.setWidth(r)
    painter.setPen(pen)
    _font.setPixelSize(r * 6)
    painter.setFont(_font)

    # Draw edges
    if node_mode:
        for l1, l2 in g.edges:
            if except_node in {l1, l2}:
                pen.setColor(Qt.gray)
            else:
                pen.setColor(Qt.black)
            painter.setPen(pen)

            painter.drawLine(QPointF(pos[l1][0], -pos[l1][1]),
                             QPointF(pos[l2][0], -pos[l2][1]))
    else:
        color = color_qt('dark-gray') if monochrome else LINK_COLOR
        color.setAlpha(150)
        painter.setBrush(QBrush(color))
        for link in g.vertices:
            if link == except_node:
                pen.setColor(Qt.gray)
            else:
                pen.setColor(Qt.black)
            painter.setPen(pen)

            painter.drawPolygon(*convex_hull([(pos[n][0], -pos[n][1])
                                              for n, edge in edges_view(g)
                                              if link in edge],
                                             as_qpoint=True))

    # Draw vertices
    for k, (x, y) in pos.items():
        if node_mode:
            color = color_num(len(list(g.neighbors(k))) - 1)
            if k == except_node:
                color.setAlpha(150)
        else:
            if monochrome:
                color = Qt.black
            elif except_node in dict(edges_view(g))[k]:
                color = color_qt('green')
            else:
                color = color_qt('blue')
        pen.setColor(color)
        painter.setPen(pen)
        painter.setBrush(QBrush(color))
        point = QPointF(x, -y)
        painter.drawEllipse(point, r, r)
        if show_label:
            pen.setColor(Qt.darkMagenta)
            painter.setPen(pen)
            painter.drawText(point, str(k))
    painter.end()
    return QIcon(QPixmap.fromImage(image).scaledToWidth(width))