def input_to_rect_item(self, input_stream: QDataStream,
                        item: QGraphicsRectItem):
     self.input_to_shape_item(input_stream, item)
     # Type
     rect = QRectF()
     # Read
     input_stream >> rect
     # Set
     item.setRect(rect)
Beispiel #2
0
 def __init__(self, scene: QGraphicsScene, parent: QMainWindow):
     QGraphicsView.__init__(self, scene, parent)
     self.crop_rect = QRect(QPoint(0, 0), QSize(0, 0))
     self.g_rect = QGraphicsRectItem(QRectF(self.crop_rect))
     self.setParent(parent)
     self.app = self.parent()
     self.crop_btn = self.parent().crop_button
     self.mouse_down = False
     self.g_rect.setPen(QPen(Qt.red, 1, Qt.SolidLine))
     self.g_rect.setBrush(QBrush(Qt.red, Qt.Dense6Pattern))
     self.mouse_pos = QPoint(0, 0)
     self.adjustment = ''
     self.annotation = False
 def __init__(self, shape, item_type, pixmap):
     self.shape: QGraphicsItem = shape
     self.name: str = "undefined"
     if item_type == QGraphicsRectItem.type(QGraphicsRectItem()):
         self.name: str = "rectangle"
     elif item_type == QGraphicsEllipseItem.type(QGraphicsEllipseItem()):
         self.name: str = "ellipse"
     elif item_type == QGraphicsPolygonItem.type(QGraphicsPolygonItem()):
         if shape.polygon().size() == 3:
             self.name: str = "triangle"
         else:
             self.name: str = "polygon"
     elif item_type == QGraphicsLineItem.type(QGraphicsLineItem()):
         self.name: str = "line"
     self.pixmap: QPixmap = pixmap
Beispiel #4
0
 def reset(self):
     self.crop_rect = QRect(QPoint(0, 0), QSize(0, 0))
     self.g_rect = QGraphicsRectItem(QRectF(self.crop_rect))
     self.g_rect.setPen(QPen(Qt.red, 1, Qt.SolidLine))
     self.g_rect.setBrush(QBrush(Qt.red, Qt.Dense6Pattern))
     self.setMouseTracking(False)
     self.unsetCursor()
     self.mouse_pos = QPoint(0, 0)
     self.adjustment = ''
     self.mouse_down = False
     if self.crop_btn.isChecked():
         self.app.reload()
         self.setCursor(Qt.CrossCursor)
     if self.annotation:
         self.setCursor(Qt.CrossCursor)
 def shape_to_pixelmap(item_type, pen, brush, shape) -> QPixmap:
     pixmap = QPixmap(50, 50)
     pixmap.fill(Qt.transparent)
     painter = QPainter(pixmap)
     painter.setRenderHint(QPainter.Antialiasing)
     painter.setPen(pen)
     painter.setBrush(brush)
     if item_type == QGraphicsRectItem.type(QGraphicsRectItem()):
         painter.drawRect(QRect(10, 15, 30, 20))
     elif item_type == QGraphicsEllipseItem.type(QGraphicsEllipseItem()):
         painter.drawEllipse(QRect(10, 10, 30, 30))
     elif item_type == QGraphicsPolygonItem.type(QGraphicsPolygonItem()):
         if shape.polygon().size() == 3:
             painter.drawPolygon(QPolygon([QPoint(10, 40), QPoint(40, 40), QPoint(25, 10)]))
         else:
             painter.drawPolygon(QPolygon([QPoint(12, 40), QPoint(23, 36),
                                           QPoint(37, 24), QPoint(23, 12), QPoint(7, 16)]))
     elif item_type == QGraphicsLineItem.type(QGraphicsLineItem()):
         painter.drawLine(QLine(10, 40, 40, 10))
     return pixmap
 def load_items(self, file_name: str, gim):
     input_file = QFile(file_name)
     if input_file.open(QIODevice.ReadOnly):
         input_stream = QDataStream(input_file)
         while not input_stream.atEnd():
             item_type = input_stream.readInt8()
             item_name = input_stream.readString()
             if item_type == QGraphicsRectItem.type(QGraphicsRectItem()):
                 rect = QGraphicsRectItem()
                 self.input_to_rect_item(input_stream, rect)
                 self.scene.addItem(rect)
                 gim.append_shape(rect, rect.type(), rect.pen(),
                                  rect.brush())
                 print("Rectangle loaded")
             elif item_type == QGraphicsEllipseItem.type(
                     QGraphicsEllipseItem()):
                 ellipse = QGraphicsEllipseItem()
                 self.input_to_rect_item(input_stream, ellipse)
                 self.scene.addItem(ellipse)
                 gim.append_shape(ellipse, ellipse.type(), ellipse.pen(),
                                  ellipse.brush())
                 print("Ellipse loaded")
             elif item_type == QGraphicsPolygonItem.type(
                     QGraphicsPolygonItem()):
                 polygon = QGraphicsPolygonItem()
                 self.input_to_polygon_item(input_stream, polygon)
                 self.scene.addItem(polygon)
                 gim.append_shape(polygon, polygon.type(), polygon.pen(),
                                  polygon.brush())
                 print("l polygon")
             elif item_type == QGraphicsLineItem.type(QGraphicsLineItem()):
                 line = QGraphicsLineItem()
                 self.input_to_line_item(input_stream, line)
                 self.scene.addItem(line)
                 gim.append_shape(line, line.type(), line.pen(),
                                  QBrush(Qt.black))
                 print("Line loaded")
             gim.return_shapes()[-1].name = item_name
             ItemsInputOutput.set_item_flags(self.scene)
         input_file.close()
Beispiel #7
0
 def load_tags(self):
     """Load tags from iTxt data."""
     for radio in self.radios:
         if radio.isChecked():
             self.radios[radio]['reset'].setChecked(True)
     filename = self.files[self.index]
     fqp = filename
     img = Image.open(fqp)
     img.load()
     with suppress(AttributeError):
         for key, value in img.text.items():
             if value == 'True':
                 for radio in self.radios:
                     if key == self.radios[radio]['this']:
                         radio.setChecked(True)
                         self.view.annotation = False
                         self.active_tag = ''
                         self.view.reset()
         for key, value in img.text.items():
             if key.endswith('-rect'):
                 btn = [
                     radio for radio in self.radios
                     if self.radios[radio]['this'] == key.split('-')[0]
                 ]
                 print(key, value)
                 if btn[0].isChecked():
                     coords = [int(coord) for coord in value.split(', ')]
                     rect = QGraphicsRectItem(*coords)
                     rect.setPen(QPen(Qt.magenta, 1, Qt.SolidLine))
                     rect.setBrush(QBrush(Qt.magenta, Qt.Dense4Pattern))
                     self.view.scene().addItem(rect)
                     text = self.view.scene().addText(
                         key.split('-')[0],
                         QFont('monospace', 20, 400, False))
                     text.font().setPointSize(text.font().pointSize() * 2)
                     text.update()
                     text.setX(rect.rect().x() + 10)
                     text.setY(rect.rect().y() + 10)
                     print(f'set {key}')
Beispiel #8
0
 def draw_simple_shape_to_scene(view: QGraphicsView,
                                p_prev: QPointF,
                                p_act: QPointF,
                                to_gim: bool = True) -> None:
     if view.actual_selection.value in [2, 4]:
         width = math.fabs(p_prev.x() - p_act.x())
         height = math.fabs(p_prev.y() - p_act.y())
         xmin = min(p_prev.x(), p_act.x())
         ymin = min(p_prev.y(), p_act.y())
         item: QAbstractGraphicsShapeItem
         if view.actual_selection.value == 2:
             item = QGraphicsRectItem(0, 0, width, height)
         else:
             item = QGraphicsEllipseItem(0, 0, width, height)
         item.setPos(QPointF(xmin, ymin))
         item.setPen(view.actual_pen)
         item.setBrush(view.actual_brush)
         DrawTools.set_item_flags(item)
         view.scene().addItem(item)
         view.gim.append_shape(item, item.type(), view.actual_pen,
                               view.actual_brush)
     elif view.actual_selection.value in [3, 5, 6]:
         x = p_act.x() - p_prev.x()
         y = p_act.y() - p_prev.y()
         item: QGraphicsItem
         if view.actual_selection.value == 3:
             item = QGraphicsPolygonItem(
                 QPolygonF(
                     [QPointF(0, 0),
                      QPointF(0 + x, 0),
                      QPointF(x / 2, y)]))
             item.setBrush(view.actual_brush)
         else:
             item = QGraphicsLineItem(QLineF(0, 0, x, y))
         item.setPos(p_prev)
         item.setPen(view.actual_pen)
         DrawTools.set_item_flags(item)
         view.scene().addItem(item)
         if to_gim:
             view.gim.append_shape(item, item.type(), view.actual_pen,
                                   view.actual_brush)
Beispiel #9
0
class MyView(QGraphicsView):
    """Custom graphics view class for drawing crop rectangles"""
    got_rect = Signal(tuple)

    def __init__(self, scene: QGraphicsScene, parent: QMainWindow):
        QGraphicsView.__init__(self, scene, parent)
        self.crop_rect = QRect(QPoint(0, 0), QSize(0, 0))
        self.g_rect = QGraphicsRectItem(QRectF(self.crop_rect))
        self.setParent(parent)
        self.app = self.parent()
        self.crop_btn = self.parent().crop_button
        self.mouse_down = False
        self.g_rect.setPen(QPen(Qt.red, 1, Qt.SolidLine))
        self.g_rect.setBrush(QBrush(Qt.red, Qt.Dense6Pattern))
        self.mouse_pos = QPoint(0, 0)
        self.adjustment = ''
        self.annotation = False

    def reset(self):
        self.crop_rect = QRect(QPoint(0, 0), QSize(0, 0))
        self.g_rect = QGraphicsRectItem(QRectF(self.crop_rect))
        self.g_rect.setPen(QPen(Qt.red, 1, Qt.SolidLine))
        self.g_rect.setBrush(QBrush(Qt.red, Qt.Dense6Pattern))
        self.setMouseTracking(False)
        self.unsetCursor()
        self.mouse_pos = QPoint(0, 0)
        self.adjustment = ''
        self.mouse_down = False
        if self.crop_btn.isChecked():
            self.app.reload()
            self.setCursor(Qt.CrossCursor)
        if self.annotation:
            self.setCursor(Qt.CrossCursor)

    def mousePressEvent(self, event: QMouseEvent):  # pylint: disable=invalid-name
        """Mouse event handler; begins a crop action"""
        self.mouse_down = True
        self.mouse_pos = self.mapToScene(event.pos()).toPoint()
        if self.crop_btn.isChecked() or self.annotation:
            self.crop_rect.setTopLeft(self.mapToScene(event.pos()).toPoint())
            self.scene().addItem(self.g_rect)
        if self.annotation:
            self.g_rect.setPen(QPen(Qt.magenta, 1, Qt.SolidLine))
            self.g_rect.setBrush(QBrush(Qt.magenta, Qt.Dense4Pattern))
        elif self.hasMouseTracking() and self.g_rect.isUnderMouse:
            self.adjustment = self.edge(event.pos)[1]
        else:
            QGraphicsView.mousePressEvent(self, event)

    def mouseMoveEvent(self, event: QMouseEvent):  # pylint: disable=invalid-name
        """Expand crop rectangle"""
        if self.crop_btn.isChecked() | self.annotation and self.mouse_down:
            self.crop_rect.setBottomRight(
                self.mapToScene(event.pos()).toPoint())
            self.g_rect.setRect(self.crop_rect)
        if self.hasMouseTracking():
            self.setCursor((Qt.ArrowCursor, self.edge(
                event.pos)[0])[self.is_under_mouse(self.g_rect.rect())])
            if self.mouse_down:
                self.move_rect(event.pos)

    def wheelEvent(self, event: QMouseEvent):
        if self.hasMouseTracking():
            self.reset()
        elif self.annotation:
            self.annotation = False
            self.unsetCursor()
        else:
            event.ignore()

    def is_under_mouse(self, rect: QRectF):
        widen = rect + QMarginsF(10, 10, 10, 10)
        self.g_rect.setRect(widen)
        res = self.g_rect.isUnderMouse()
        self.g_rect.setRect(rect)
        return res

    def move_rect(self, pos):
        delta = self.mapToScene(pos()).toPoint() - self.mouse_pos
        self.mouse_pos = self.mapToScene(pos()).toPoint()
        if self.adjustment == 'inside':
            self.g_rect.setRect(self.g_rect.rect().adjusted(
                delta.x(), delta.y(), delta.x(), delta.y()))
        elif self.adjustment == 'left':
            self.g_rect.setRect(self.g_rect.rect().adjusted(
                delta.x(), 0, 0, 0))
        elif self.adjustment == 'right':
            self.g_rect.setRect(self.g_rect.rect().adjusted(
                0, 0, delta.x(), 0))
        elif self.adjustment == 'top':
            self.g_rect.setRect(self.g_rect.rect().adjusted(
                0, delta.y(), 0, 0))
        elif self.adjustment == 'bottom':
            self.g_rect.setRect(self.g_rect.rect().adjusted(
                0, 0, 0, delta.y()))
        elif self.adjustment == 'top_left':
            self.g_rect.setRect(self.g_rect.rect().adjusted(
                delta.x(), delta.y(), 0, 0))
        elif self.adjustment == 'top_right':
            self.g_rect.setRect(self.g_rect.rect().adjusted(
                0, delta.y(), delta.x(), 0))
        elif self.adjustment == 'bot_left':
            self.g_rect.setRect(self.g_rect.rect().adjusted(
                delta.x(), 0, 0, delta.y()))
        elif self.adjustment == 'bot_right':
            self.g_rect.setRect(self.g_rect.rect().adjusted(
                0, 0, delta.x(), delta.y()))

    def edge(self, pos):
        event_pos = self.mapToScene(pos()).toPoint()
        rect_left = int(self.g_rect.rect().left())
        rect_right = int(self.g_rect.rect().right())
        rect_top = int(self.g_rect.rect().top())
        rect_bottom = int(self.g_rect.rect().bottom())
        on_left, on_right, on_top, on_bottom = (False, False, False, False)
        if event_pos.x() in range(rect_left - 10, rect_left + 10):
            on_left = True
        if event_pos.x() in range(rect_right - 10, rect_right + 10):
            on_right = True
        if event_pos.y() in range(rect_top - 10, rect_top + 10):
            on_top = True
        if event_pos.y() in range(rect_bottom - 10, rect_bottom + 10):
            on_bottom = True
        if (on_left and on_bottom) or (on_top and on_right):
            return (Qt.SizeBDiagCursor, ('bot_left', 'top_right')[on_right])
        if (on_left and on_top) | (on_right and on_bottom):
            return (Qt.SizeFDiagCursor, ('top_left', 'bot_right')[on_right])
        if on_left | on_right:
            return (Qt.SizeHorCursor, ('left', 'right')[on_right])
        if on_top | on_bottom:
            return (Qt.SizeVerCursor, ('top', 'bottom')[on_bottom])
        else:
            return ((Qt.OpenHandCursor, Qt.ClosedHandCursor)[self.mouse_down],
                    'inside')

    def mouseReleaseEvent(self, event: QMouseEvent):  # pylint: disable=invalid-name
        """Completes the crop rectangle."""
        self.mouse_down = False
        if self.crop_btn.isChecked() | self.annotation:
            self.crop_rect.setBottomRight(
                self.mapToScene(event.pos()).toPoint())
            self.g_rect.setRect(self.crop_rect)
            self.setMouseTracking(True)
            self.crop_btn.setChecked(False)
            self.annotation = False
            self.unsetCursor()
 def output_from_rect_item(self, output_stream: QDataStream,
                           item: QGraphicsRectItem):
     self.output_from_shape_item(output_stream, item)
     # Output
     output_stream << item.rect()