예제 #1
0
class GraphicsView(QGraphicsView):
    def __init__(self, **kwargs):
        super(GraphicsView, self).__init__(**kwargs)
        self._scene = QGraphicsScene(parent=self)

        self.current_image = QGraphicsPixmapItem()
        self._scene.addItem(self.current_image)

        self.setScene(self._scene)
        self.fitInView(self._scene.sceneRect(), Qt.KeepAspectRatio)
        self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.setMouseTracking(True)
        self.setRenderHint(QPainter.Antialiasing)

    def update_image(self, img: np.ndarray):
        rgb_image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        h, w, ch = rgb_image.shape
        bytes_per_line = ch * w
        qimg = QImage(rgb_image.data, w, h, bytes_per_line,
                      QImage.Format_RGB888)
        pixmap = QPixmap.fromImage(qimg)
        self.current_image.setPixmap(pixmap)
        self._scene.setSceneRect(0, 0, w, h)
        self.fitInView(self._scene.sceneRect(), Qt.KeepAspectRatio)

    def resizeEvent(self, e):
        self.fitInView(self._scene.sceneRect(), Qt.KeepAspectRatio)

    def wheelEvent(self, e):
        if e.angleDelta().y() > 0:
            self.scale(1.25, 1.25)
        elif e.angleDelta().y() < 0:
            self.scale(0.85, 0.85)

    def mousePressEvent(self, e):
        # シーン上のマウス位置を取得する
        pos = self.mapToScene(e.pos())
        if e.button() == Qt.LeftButton:
            if e.modifiers() == Qt.NoModifier:
                pass
            elif e.modifiers() == Qt.AltModifier:
                self.setDragMode(QGraphicsView.ScrollHandDrag)
        QGraphicsView.mousePressEvent(self, e)

    def mouseReleaseEvent(self, e):
        QGraphicsView.mouseReleaseEvent(self, e)
        if e.button() == Qt.LeftButton:
            self.setDragMode(QGraphicsView.NoDrag)

    def calc_offset(self, p: QPoint):
        offset_x = p.x() - int(self.viewport().width() / 2)
        offset_y = p.y() - int(self.viewport().height() / 2)
        return QPoint(offset_x, offset_y)
예제 #2
0
    def __init__(self, item):
        super().__init__()

        self._shown = False
        self.modified_callback = None

        scene = QGraphicsScene()
        self.scene = scene

        self.scene_item = item
        scene.addItem(item)

        layout = QBoxLayout(QBoxLayout.TopToBottom, self)

        scene_view = View(self)
        self.scene_view = scene_view
        scene_view.setScene(scene)
        scene_view.setMinimumSize(350, 350)
        scene_view.setRenderHint(QPainter.Antialiasing)
        layout.addWidget(scene_view)

        self.double_click_callback = None
        self.mouse_press_callback = None
        if hasattr(self.scene_item, "mouse_pressed_in"):
            self.mouse_press_callback = self.scene_item.mouse_pressed_in
        if hasattr(self.scene_item, "double_clicked_in_background"):
            self.double_click_callback = \
                self.scene_item.double_clicked_in_background
        if hasattr(self.scene_item, "mouse_moved_in_scene"):
            self.scene_view.mouse_move_callback = \
                self.scene_item.mouse_moved_in_scene

        self.menus = []
        view_menu = QMenu("&View")
        self.view_menu = view_menu
        self.menus.append(view_menu)
        export_menu = QMenu("&Export")
        self.menus.append(export_menu)

        self.tools = []

        fit_action = QAction("&Fit", self)
        fit_action.setShortcut("0")
        fit_action.setIcon(QIcon.fromTheme("zoom-fit-best"))
        fit_action.setStatusTip("Fit the entire scene to the viewport")
        fit_action.triggered.connect(self.scene_view.fit_all_in_view)
        view_menu.addAction(fit_action)
        self.tools.append(fit_action)

        reset_action = QAction("&Reset (1:1)", self)
        reset_action.setShortcut("9")
        reset_action.setIcon(QIcon.fromTheme("zoom-original"))
        reset_action.setStatusTip("Reset the view to 100% scale")
        reset_action.triggered.connect(self.scene_view.reset_scale)
        view_menu.addAction(reset_action)
        self.tools.append(reset_action)

        zoom_in_action = QAction("Zoom &In", self)
        zoom_in_action.setShortcuts(["+", "="])
        zoom_in_action.setStatusTip("Zoom in")
        zoom_in_action.triggered.connect(lambda: self.scene_view.zoom_in())
        view_menu.addAction(zoom_in_action)

        zoom_out_action = QAction("Zoom &Out", self)
        zoom_out_action.setShortcuts(["-", "_"])
        zoom_out_action.setStatusTip("Zoom out")
        zoom_out_action.triggered.connect(lambda: self.scene_view.zoom_out())
        view_menu.addAction(zoom_out_action)

        export_svg_action = QAction("As &SVG...", self)
        export_svg_action.setStatusTip("Export the current tab as an SVG file")
        export_svg_action.triggered.connect(lambda: export_as_svg(self.scene))
        export_menu.addAction(export_svg_action)

        export_png_action = QAction("As PN&G...", self)
        export_png_action.setStatusTip("Export the current tab as an PNG file")
        export_png_action.triggered.connect(lambda: export_as_png(self.scene))
        export_menu.addAction(export_png_action)

        export_pdf_action = QAction("As &PDF...", self)
        export_pdf_action.setStatusTip("Export the current tab as an PDF file")
        export_pdf_action.triggered.connect(lambda: export_as_pdf(self.scene))
        export_menu.addAction(export_pdf_action)

        export_svg_clip_action = QAction("To Clipboard as SVG", self)
        export_svg_clip_action.setStatusTip(
            "Export the current tab to the clipoard in SVG format")
        export_svg_clip_action.triggered.connect(
            lambda: export_to_clipboard_as_svg(self.scene))
        export_menu.addAction(export_svg_clip_action)

        export_image_clip_action = QAction("To &Clipboard as Image", self)
        export_image_clip_action.setStatusTip(
            "Export the current tab to the clipoard as an image")
        export_image_clip_action.triggered.connect(
            lambda: export_to_clipboard_as_image(self.scene))
        export_menu.addAction(export_image_clip_action)

        self.resize(800, 600)
예제 #3
0
class MapView(QGraphicsView):
    """A map of reaction boxes"""
    def __init__(self, appdata: CnaData, name: str):
        self.scene = QGraphicsScene()
        QGraphicsView.__init__(self, self.scene)
        palette = self.palette()
        palette.setColor(QPalette.Base, Qt.white)
        self.setPalette(palette)

        self.appdata = appdata
        self.name = name
        self.setAcceptDrops(True)
        self.drag = False
        self.reaction_boxes: Dict[str, ReactionBox] = {}
        self._zoom = 0
        self.drag = False
        self.drag_start = None

        # initial scale
        self._zoom = self.appdata.project.maps[self.name]["zoom"]
        if self._zoom > 0:
            for _ in range(1, self._zoom):
                self.scale(INCREASE_FACTOR, INCREASE_FACTOR)
        if self._zoom < 0:
            for _ in range(self._zoom, -1):
                self.scale(DECREASE_FACTOR, DECREASE_FACTOR)

        # connect events to methods
        self.horizontalScrollBar().valueChanged.connect(self.on_hbar_change)
        self.verticalScrollBar().valueChanged.connect(self.on_vbar_change)

    def on_hbar_change(self, x):
        self.appdata.project.maps[self.name]["pos"] = (
            x, self.verticalScrollBar().value())

    def on_vbar_change(self, y):
        self.appdata.project.maps[self.name]["pos"] = (
            self.horizontalScrollBar().value(), y)

    def dragEnterEvent(self, event: QGraphicsSceneDragDropEvent):
        event.setAccepted(True)
        event.accept()
        event.acceptProposedAction()

    def dragMoveEvent(self, event: QGraphicsSceneDragDropEvent):
        event.setAccepted(True)
        point = event.pos()
        point_item = self.mapToScene(point)
        r_id = event.mimeData().text()

        if r_id in self.appdata.project.maps[self.name]["boxes"].keys():
            self.appdata.project.maps[self.name]["boxes"][r_id] = (
                point_item.x(), point_item.y())
            self.mapChanged.emit(r_id)
        else:
            self.appdata.project.maps[self.name]["boxes"][r_id] = (
                point_item.x(), point_item.y())
            self.reactionAdded.emit(r_id)

        self.update()

    def dragLeaveEvent(self, _event):
        self.update()

    def dropEvent(self, event: QGraphicsSceneDragDropEvent):
        self.drag = False
        point = event.pos()
        point_item = self.mapToScene(point)
        identifier = event.mimeData().text()
        self.appdata.project.maps[self.name]["boxes"][identifier] = (
            point_item.x(), point_item.y())
        self.mapChanged.emit(identifier)
        self.update()

    def wheelEvent(self, event):
        modifiers = QApplication.queryKeyboardModifiers()
        if modifiers == Qt.ControlModifier:
            if event.angleDelta().y() > 0:
                self.appdata.project.maps[
                    self.name]["bg-size"] *= INCREASE_FACTOR
            else:
                self.appdata.project.maps[
                    self.name]["bg-size"] *= DECREASE_FACTOR

            self.mapChanged.emit("dummy")
            self.update()

        if event.angleDelta().y() > 0:
            self.zoom_in()
        else:
            self.zoom_out()

    def fit(self):
        self.fitInView(self.scene.sceneRect(), Qt.KeepAspectRatio)

    def zoom_in(self):
        self._zoom += 1

        self.appdata.project.maps[self.name]["zoom"] = self._zoom
        self.scale(INCREASE_FACTOR, INCREASE_FACTOR)

    def zoom_out(self):
        self._zoom -= 1

        self.appdata.project.maps[self.name]["zoom"] = self._zoom
        self.scale(DECREASE_FACTOR, DECREASE_FACTOR)

    def mousePressEvent(self, event: QMouseEvent):
        self.drag = True
        self.drag_start = event.pos()
        super(MapView, self).mousePressEvent(event)

    def mouseMoveEvent(self, event: QGraphicsSceneMouseEvent):
        modifiers = QApplication.queryKeyboardModifiers()
        if modifiers == Qt.ControlModifier:
            if self.drag:
                point = event.pos()
                move_x = self.drag_start.x() - point.x()
                move_y = self.drag_start.y() - point.y()
                self.drag_start = point
                for key, val in self.appdata.project.maps[
                        self.name]["boxes"].items():
                    self.appdata.project.maps[self.name]["boxes"][key] = (
                        val[0] - move_x, val[1] - move_y)
                self.mapChanged.emit("dummy")
                self.update()
        else:
            if self.drag:
                self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
                self.translate(1, 1)
            super(MapView, self).mouseMoveEvent(event)

    def mouseReleaseEvent(self, event: QMouseEvent):
        if self.drag:
            self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
            self.translate(1, 1)
        self.drag = False
        super(MapView, self).mouseReleaseEvent(event)

    def update_selected(self, string):

        for r_id in self.reaction_boxes:
            if string.lower() in r_id.lower():
                self.reaction_boxes[r_id].item.setHidden(False)
            elif string.lower() in self.reaction_boxes[r_id].name.lower():
                self.reaction_boxes[r_id].item.setHidden(False)
            else:
                self.reaction_boxes[r_id].item.setHidden(True)

    def focus_reaction(self, reaction: str):
        x = self.appdata.project.maps[self.name]["boxes"][reaction][0]
        y = self.appdata.project.maps[self.name]["boxes"][reaction][1]
        self.centerOn(x, y)

    def highlight_reaction(self, string):
        # hide other boxes
        # for id in self.reaction_boxes:
        #     self.reaction_boxes[id].item.setHidden(True)

        treffer = self.reaction_boxes[string]
        treffer.item.setHidden(False)

        treffer.set_color(Qt.magenta)

    def update(self):
        self.scene.clear()
        background = QGraphicsSvgItem(
            self.appdata.project.maps[self.name]["background"])
        background.setFlags(QGraphicsItem.ItemClipsToShape)
        background.setScale(self.appdata.project.maps[self.name]["bg-size"])
        self.scene.addItem(background)

        for r_id in self.appdata.project.maps[self.name]["boxes"]:
            try:
                name = self.appdata.project.cobra_py_model.reactions.get_by_id(
                    r_id).name
                box = ReactionBox(self, r_id, name)
                box.setPos(
                    self.appdata.project.maps[self.name]["boxes"][r_id][0],
                    self.appdata.project.maps[self.name]["boxes"][r_id][1])
                self.scene.addItem(box)
                self.reaction_boxes[r_id] = box
            except KeyError:
                print("failed to add reaction box for", r_id)

        self.set_values()

        # set scrollbars
        self.horizontalScrollBar().setValue(
            self.appdata.project.maps[self.name]["pos"][0])
        self.verticalScrollBar().setValue(
            self.appdata.project.maps[self.name]["pos"][1])

    def set_values(self):
        for r_id in self.appdata.project.maps[self.name]["boxes"]:
            if r_id in self.appdata.project.scen_values.keys():
                self.reaction_boxes[r_id].set_val_and_color(
                    self.appdata.project.scen_values[r_id])
            elif r_id in self.appdata.project.comp_values.keys():
                self.reaction_boxes[r_id].set_val_and_color(
                    self.appdata.project.comp_values[r_id])

    def remove_box(self, reaction: str):
        del self.appdata.project.maps[self.name]["boxes"][reaction]
        del self.reaction_boxes[reaction]
        self.update()
        self.reactionRemoved.emit(reaction)

    # def emit_doubleClickedReaction(self, reaction: str):
    #     print("emit_doubleClickedReaction")
    #     self.doubleClickedReaction.emit(reaction)

    def value_changed(self, reaction: str, value: str):
        self.reactionValueChanged.emit(reaction, value)
        self.reaction_boxes[reaction].recolor()

    switchToReactionMask = Signal(str)
    maximizeReaction = Signal(str)
    minimizeReaction = Signal(str)
    reactionRemoved = Signal(str)
    reactionValueChanged = Signal(str, str)
    reactionAdded = Signal(str)
    mapChanged = Signal(str)
예제 #4
0
    def spacing(self):
        return self._spacing

    def setSpacing(self, spacing):
        self._spacing = spacing


if __name__ == '__main__':
    import sys
    from qtpy.QtWidgets import QApplication, QGraphicsView, QGraphicsScene
    from qtpy.QtGui import QCursor
    app = QApplication(sys.argv)
    v = QGraphicsView()
    s = QGraphicsScene()
    v.setSceneRect(0, 0, 200, 200)
    v.setScene(s)
    # GRADIENT
    g = drawColorTypeGradient(attrs.HUE, 100, 100)
    g.setFinalStop(0, 300)
    s.setBackgroundBrush(QBrush(g))

    #LINE
    l = DualColoredLineSegment()
    l.setLine(0, 0, 300, 300)
    s.addItem(l)

    v.show()
    v.move(QCursor.pos())
    sys.exit(app.exec_())
예제 #5
0
class MyForm(QMainWindow):
    def __init__(self, width, height, pixel_ratio, path):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # overwrite dimesions specified in slideShow3.py, as they are specific to MacBookPro display, and QTDesigner
        # has its own idea on what they should be.  This code should work on any size display
        self.resize(width, height)
        self.ui.graphicsView.setGeometry(QtCore.QRect(0, 0, width, height))
        self.ui.menubar.setGeometry(QtCore.QRect(0, 0, width, 0))

        self.width = width
        self.height = height
        self.pixel_ratio = pixel_ratio
        self.path = path
        self.imageFiles = []
        self.slideIndex = -1
        self.random_index_number = 0
        self.random = ""
        self.imageFiles, self.random_index, self.path, self.max_index = self.getImageNames2(
        )
        self.helpFile = os.path.join(
            os.path.dirname(os.path.realpath(sys.argv[0])), "instructions.png")
        #print(self.helpFile)
        self.scene = QGraphicsScene(self)
        #self.scene.setAlignment(QtCore.Qt.AlignCenter)
        self.ui.actionDir.triggered.connect(self.openFileNameDialog)
        self.ui.actionStart_Slide_Show.triggered.connect(self.slide_show)
        self.ui.actionRandom_Slide_Show.triggered.connect(
            self.random_slide_show)
        eventFilter = MouseEventFilter(self.scene)
        self.scene.installEventFilter(eventFilter)
        self.ui.actionHelp.triggered.connect(self.helpWindow)

        #self.show()
        self.showFullScreen()

    extension = staticmethod(lambda f: f.split('.').pop().lower())
    filename = staticmethod(lambda f: f.split('/').pop())

    def openFileNameDialog(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        self.fileName, _ = QFileDialog.getOpenFileName(
            self,
            "QFileDialog.getOpenFileName()",
            "",
            "All Files (*);;Python Files (*.py)",
            options=options)
        if self.fileName:
            self.path = os.path.dirname(self.fileName)
            self.imageFiles = []
            self.random_index = []
            self.max_index = []
            self.imageFiles, self.random_index, self.path, self.max_index = self.getImageNames2(
            )
            self.slideIndex = self.imageFiles.index(self.fileName) - 1

    def getImageNames2(self):
        "get the names of all images on disc or from the web (which are cached locally)"

        if not self.path:
            self.path = os.getcwd()
        if self.path[-1] != '/':
            self.path += '/'
        try:
            os.listdir(self.path)
        except:
            error_dialog = QtWidgets.QErrorMessage()
            error_dialog.showMessage(
                'Error in path' + self.path
            )  # https://stackoverflow.com/questions/40227047/python-pyqt5-how-to-show-an-error-message-with-pyqt5
            return [], self.path

        for i in GlobDirectoryWalker(self.path, "*.*"):
            if os.path.isfile(i):
                if self.checkImageType(i): self.imageFiles.append(i)

        max_index = len(self.imageFiles) - 1

        self.imageFiles.sort()

        random_index = list(range(max_index + 1))
        random.shuffle(random_index)
        return self.imageFiles, random_index, self.path, max_index

    def slide(self, i):
        self.pixmap = QtGui.QPixmap()
        #self.pixmap.setAlignment(QtCore.Qt.AlignCenter)
        self.pixmap.load(self.imageFiles[i])
        self.pixmap.setDevicePixelRatio(
            self.pixel_ratio
        )  # https://stackoverflow.com/questions/50127246/pyqt-5-10-enabling-high-dpi-support-for-macos-poor-pixmap-quality
        #self.pixmap4 = self.pixmap.scaled(self.width * self.pixel_ratio, (self.height * self.pixel_ratio)-45, Qt.KeepAspectRatio)
        self.pixmap4 = self.pixmap.scaled(self.width * self.pixel_ratio,
                                          (self.height * self.pixel_ratio),
                                          Qt.KeepAspectRatio)
        try:
            self.scene.removeItem(self.item)
        except:
            print("failed to remove item")
        self.item = QGraphicsPixmapItem(self.pixmap4)
        self.scene.addItem(self.item)
        #myapp.setWindowTitle(os.path.basename(self.imageFiles[i]))
        self.setWindowTitle(os.path.basename(self.imageFiles[i]))
        self.ui.graphicsView.setScene(self.scene)

    def slide_show(self):
        self.random = 0
        self.next_slide()

    def random_slide_show(self):
        self.random = 1
        self.next_slide()

    def next_slide(self):
        if self.random == 0:
            self.increment_slide()
        else:
            self.random_next()

    def prev_slide(self):
        if self.random == 0:
            self.decrement_slide()
        else:
            self.random_prev()

    def random_next(self):
        "display the next random slide"
        self.random_index_number += 1
        try:
            self.slideIndex = self.random_index[self.random_index_number]
            self.slide(self.slideIndex)
        except IndexError:
            self.random_index_number = 0
            self.slideIndex = self.random_index[self.random_index_number]
            self.slide(self.slideIndex)
        return False

    def random_prev(self):
        "display the previous random slide"
        self.random_index_number -= 1
        #self.ImageWindow.clear()
        try:
            self.slideIndex = self.random_index[self.random_index_number]
            self.slide(self.slideIndex)
        except IndexError:
            self.random_index_number = self.max_index
            self.slideIndex = self.random_index[self.random_index_number]
            self.slide(self.slideIndex)
        return False

    def increment_slide(self):
        "display a higher slide"
        print("in increment_slide")
        self.slideIndex += 1
        if self.slideIndex > self.max_index:
            self.slideIndex = 0
            print('Max index hit')
        self.slide(self.slideIndex)
        return False

    def decrement_slide(self):
        "display a lower slide"
        self.slideIndex -= 1
        if self.slideIndex < 0:
            self.slideIndex = self.max_index
        self.slide(self.slideIndex)
        return False

    def checkImageType(self, f):
        "check to see if we have an file with an image extension"
        ext = self.extension(f)
        chk = [
            i for i in ['jpg', 'gif', 'ppm', 'tif', 'png', 'jpeg'] if i == ext
        ]
        if chk == []: return False
        return True

    def helpWindow(self):
        self.pixmap = QtGui.QPixmap()
        #self.pixmap.setAlignment(QtCore.Qt.AlignCenter)
        self.pixmap.load(self.helpFile)
        self.pixmap.setDevicePixelRatio(
            self.pixel_ratio
        )  # https://stackoverflow.com/questions/50127246/pyqt-5-10-enabling-high-dpi-support-for-macos-poor-pixmap-quality
        #self.pixmap4 = self.pixmap.scaled(self.width * self.pixel_ratio, (self.height * self.pixel_ratio)-45, Qt.KeepAspectRatio)
        self.pixmap4 = self.pixmap.scaled(self.width * self.pixel_ratio,
                                          (self.height * self.pixel_ratio),
                                          Qt.KeepAspectRatio)
        try:
            self.scene.removeItem(self.item)
        except:
            print("failed to remove item")
        self.item = QGraphicsPixmapItem(self.pixmap4)
        self.scene.addItem(self.item)
        #myapp.setWindowTitle(os.path.basename("Instructions"))
        self.setWindowTitle(os.path.basename("Instructions"))
        self.ui.graphicsView.setScene(self.scene)

    def keyPressEvent(self, e):
        if e.key() == Qt.Key_Escape:
            self.Quit()
        if e.key() == Qt.Key_Q:
            self.Quit()
        if e.key() == Qt.Key_Space:
            self.next_slide()
        if e.key() == Qt.Key_N:
            self.random_next()
        if e.key() == Qt.Key_P:
            self.random_prev()
        if e.key() == Qt.Key_Comma:
            self.decrement_slide()
        if e.key() == Qt.Key_Period:
            self.increment_slide()
        if e.key() == Qt.Key_H:
            self.helpWindow = self.helpWindow()
        if e.key() == Qt.Key_BracketLeft:
            self.slideIndex = self.decrement_slide()

    def mousePressEvent(self, e):
        if e.button() == QtCore.Qt.LeftButton:
            print("trapped left mouse click")
            self.next_slide()
        if e.button() == QtCore.Qt.RightButton:
            print("trapped right mouse click")
            self.prev_slide()

    def Quit(self):
        sys.exit(app.exec_())
예제 #6
0
class GraphicsView(QGraphicsView):

    def __init__(self, parent=None):

        super(GraphicsView, self).__init__(parent)

        self.scene = QGraphicsScene()
        self.pixmapItem = QGraphicsPixmapItem()
        self.scene.setSceneRect(0, 0, 500, 500)
        self.setScene(self.scene)
        self.scene.addItem(self.pixmapItem)
        #would eventually make this fit to size of screen, waiting cause it's annoying.

        self.buildingParams = []
        self.scalef = [1, 1]

        self.Buildings()
    
    def Buildings(self):
        
        filename = os.getcwd() + "\examplebuildings.png"
        img = cv2.imread(filename)
        imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

        ret,thresh = cv2.threshold(imgray, 250, 255, 0)
        contours , h = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

        MinCntArea = 5000.
        MaxCntArea = 100000.

        for cnt in contours:
            
            if cv2.contourArea(cnt) > MinCntArea and cv2.contourArea(cnt) < MaxCntArea:
                
                cv2.drawContours(img, cnt, -1, (0, 255, 0), 3) # this is a green rectangle which shows the found contour

                #cv2.circle(img, (min(cnt.T[0][0]), min(cnt.T[1][0])), 4, 4) #makes a circle around the upper left corner

                #np.set_printoptions(threshold=np.inf) #this is to make it so that the whole numpy array prints to the terminal

                self.buildingParams.append([min(cnt.T[0][0]), min(cnt.T[1][0]), max(cnt.T[0][0])-min(cnt.T[0][0]), max(cnt.T[1][0])-min(cnt.T[1][0])]) # x, y, height, width
                
        # copy and paste these three lines if you would like to see what an opencv images looks like anywhere in the program
        #cv2.imshow('img', img)
        #cv2.waitKey(0)
        #cv2.destroyAllWindows()

        #cv2.rectangle(img, (self.buildingParams[0][0], self.buildingParams[0][1]), 
        #                   (self.buildingParams[0][0] + self.buildingParams[0][2], self.buildingParams[0][1] + self.buildingParams[0][3]),
        #                   (255, 0, 0), -1) # draws a blue filled in rectangle - did this to make sure I had the indicies correct for x, y, width, and height

        height, width, channel = img.shape
        bytesPerLine = 3*width
        qimg = QImage(img.data, width, height, bytesPerLine, QImage.Format_RGB888).rgbSwapped()

        ##### need to add not null checks here

        self.ogimage = QPixmap.fromImage(qimg)
        self.image = self.ogimage.scaled(self.scene.width(), self.scene.height())
        self.pixmapItem.setPixmap(self.image)

        self.updateScalef()
        self.buildingParams += self.scalef

        for i in range(len(self.buildingParams)-2):

            parameters = self.buildingParams
            rect = GraphicsRectItem(QRectF(QPointF(parameters[i][0] * parameters[4],
                                                                parameters[i][1] * parameters[5]),
                                                                QPointF((parameters[i][0] + parameters[i][2]) * parameters[4],
                                                                (parameters[i][1] + parameters[i][3]) * parameters[5])))
            
            rect.setAcceptHoverEvents(True)
            self.scene.addItem(rect)

        

    def updateScalef(self):

        self.scalef[0] = self.image.width()/self.ogimage.width()
        self.scalef[1] = self.image.height()/self.ogimage.height()

    def mousePressEvent(self, e):
        print(e.pos())
예제 #7
0
class MovieSelectionWindow(QDialog):

    __scene__ = None
    __poster_url__ = 'https://image.tmdb.org/t/p/original'
    __possibilities__ = None
    acceptedId = -1

    def __init__(self, oFile, possibilities):
        self.acceptedId = -1
        QDialog.__init__(self)

        self.ui = Ui_MovieSelection()
        self.ui.setupUi(self)

        self.ui.btnEnterId.clicked.connect(self.enterId)
        self.ui.btnEnterTitle.clicked.connect(self.enterTitle)
        self.ui.btnAccept.clicked.connect(self.accept)

        self.ui.tablePossibilities.horizontalHeader().setVisible(True)
        self.ui.tablePossibilities.verticalHeader().setVisible(True)
        self.ui.tablePossibilities.cellClicked.connect(self.selectionChanged)
        self.ui.lblOriginalFile.setText(oFile)

        self.__possibilities__ = possibilities
        self.actualizeTable()

    def showImage(self, posterPath: str):
        self.removeImage()
        imgData = requests.get(self.__poster_url__ + posterPath)
        pix = QPixmap()
        pix.loadFromData(imgData.content)
        item = QGraphicsPixmapItem(pix)
        self.__scene__ = QGraphicsScene(self)
        self.__scene__.addItem(item)
        self.ui.graphicsView.setScene(self.__scene__)
        self.resizeImage()

    def removeImage(self):
        if self.__scene__ != None:
            self.__scene__.clear()
        self.__scene__ = None

    def resizeEvent(self, event):
        QDialog.resizeEvent(self, event)
        self.resizeImage()

    def resizeImage(self):
        if (self.__scene__ != None):
            self.ui.graphicsView.fitInView(self.__scene__.sceneRect(),
                                           mode=Qt.KeepAspectRatio)
            self.ui.graphicsView.show()

    def actualizeTable(self):
        self.ui.tablePossibilities.clearContents()

        r = 0
        for p in self.__possibilities__:
            if 'title' not in p.__dict__ or 'release_date' not in p.__dict__:
                self.__possibilities__.remove(p)
                continue
            self.ui.tablePossibilities.setRowCount(r + 1)
            self.ui.tablePossibilities.setItem(r, 0, QTableWidgetItem(p.title))
            self.ui.tablePossibilities.setItem(
                r, 1, QTableWidgetItem(p.release_date[:4]))
            r += 1

        self.ui.tablePossibilities.clearSelection()

    def selectionChanged(self, row, column):
        self.ui.txtOverview.clear()
        self.ui.txtOverview.appendPlainText(
            self.__possibilities__[row].overview)
        self.ui.lblTitle.setText(self.__possibilities__[row].title + ' (' +
                                 self.__possibilities__[row].release_date[:4] +
                                 ')')
        if self.__possibilities__[row].poster_path != None:
            self.showImage(self.__possibilities__[row].poster_path)
        else:
            self.removeImage()

    def enterId(self):
        select = CustomEnterWindow(True)
        select.setWindowModality(Qt.WindowModal)
        mw = qtmodern.windows.ModernWindow(select)
        mw.setWindowModality(Qt.WindowModal)
        mw.show()
        select.ui.txtId.setFocus()

        loop = QEventLoop()
        select.finished.connect(loop.quit)
        loop.exec()

        if select.result != None and select.result.isdecimal():
            self.acceptedId = int(select.result)
            self.close()

    def __enterTitleWindow__(self, search):
        select = CustomEnterWindow(False)
        select.setWindowModality(Qt.WindowModal)
        mw = qtmodern.windows.ModernWindow(select)
        mw.setWindowModality(Qt.WindowModal)
        mw.show()
        select.ui.txtId.setFocus()

        loop = QEventLoop()
        select.finished.connect(loop.quit)
        loop.exec()

        if select.result != None:
            self.__possibilities__ = search(select.result)
            self.actualizeTable()

    def enterTitle(self):
        self.__enterTitleWindow__(Movie().search)

    def accept(self):
        self.acceptedId = self.__possibilities__[
            self.ui.tablePossibilities.currentRow()].id
        self.close()