如何组合这两个代码?(python图像查看器+;通过鼠标拖动进行图像ROI裁剪)

如何组合这两个代码?(python图像查看器+;通过鼠标拖动进行图像ROI裁剪),python,opencv,pyqt,pyqt5,Python,Opencv,Pyqt,Pyqt5,我是Python和PyQt的初学者。我尝试根据Acbeter的代码创建图像查看器,并希望添加图像裁剪功能。使用这两个代码,最终我想创建一个代码,在其中我可以打开某个图像,裁剪图像的特定部分,并在另一个窗口中显示它。您想帮助如何组合这两个代码吗 acbetter的图像查看器代码 使用QLabel在基于QScrollara的查看器中实现裁剪是不必要的复杂,因为转换跟踪起来很复杂,相反,使用QGraphicsView、QGraphicscene和QGraphicsPixmapItem实现相同的逻辑。

我是Python和PyQt的初学者。我尝试根据Acbeter的代码创建图像查看器,并希望添加图像裁剪功能。使用这两个代码,最终我想创建一个代码,在其中我可以打开某个图像,裁剪图像的特定部分,并在另一个窗口中显示它。您想帮助如何组合这两个代码吗

  • acbetter的图像查看器代码

  • 使用QLabel在基于QScrollara的查看器中实现裁剪是不必要的复杂,因为转换跟踪起来很复杂,相反,使用QGraphicsView、QGraphicscene和QGraphicsPixmapItem实现相同的逻辑。大部分逻辑已经实现,如下所示:

    从PyQt5导入QtCore、QtGui、QtWidgets、QtPrintSupport
    类查看器(QtWidgets.QGraphicsView):
    def uuu init uuu(self,parent=None):
    super()
    self.pixmap_item=self.scene().addPixmap(QtGui.QPixmap())
    self.setAlignment(QtCore.Qt.AlignTop | QtCore.Qt.AlignLeft)
    self.setBackgroundRole(QtGui.QPalette.Dark)
    self.setDragMode(QtWidgets.QGraphicsView.RubberBandDrag)
    self.rubberBandChanged.connect(self.onRubberBandChanged)
    self.last_rect=QtCore.QPointF()
    def setPixmap(自身,pixmap):
    self.pixmap_item.setPixmap(pixmap)
    def缩放(自身):
    自评量表(1.25,1.25)
    def zoomOut(自身):
    自评量表(0.8,0.8)
    def重置缩放(自):
    self.resetTransform()
    def fitToWindow(自身):
    self.fitInView(self.pixmap\u项)
    @QtCore.pyqtlot(QtCore.QRect、QtCore.QPointF、QtCore.QPointF)
    橡胶上的def已更改(自、橡胶和RECT、从场景点到场景点):
    如果rubberBandRect.isNull():
    pixmap=self.pixmap\u item.pixmap()
    rect=self.pixmap\u item.mapFromScene(self.last\u rect.boundingRect().toRect())
    如果不是矩形相交(pixmap.rect()).isNull():
    裁剪_pixmap=pixmap.copy(rect)
    label=qtwidts.QLabel(pixmap=crop\u pixmap)
    dialog=qtwidts.QDialog(self)
    lay=qtwidts.QVBoxLayout(对话框)
    lay.addWidget(标签)
    dialog.exec()
    self.last_rect=QtCore.QRectF()
    其他:
    self.last_rect=QtCore.QRectF(从场景点到场景点)
    类QImageViewer(qtwidts.QMainWindow):
    def uuu init uuu(self,parent=None):
    super()。\uuuu init\uuuuu()
    self.view=Viewer()
    self.setCentralWidget(self.view)
    self.printer=QtPrintSupport.QPrinter()
    self.createActions()
    self.createMenus()
    self.setWindowTitle(“图像查看器”)
    自我调整大小(800600)
    def打开(自):
    文件名,u=QtWidgets.QFileDialog.getOpenFileName(
    自己
    “QFileDialog.getOpenFileName()”,
    "",
    “图像(*.png*.jpeg*.jpg*.bmp*.gif)”,
    )
    如果文件名为:
    pixmap=QtGui.QPixmap(文件名)
    如果pixmap.isNull():
    QtWidgets.QMessageBox.information(
    self“图像查看器”无法加载%s。%fileName
    )
    返回
    self.view.setPixmap(pixmap)
    self.printAct.setEnabled(True)
    self.fitToWindowAct.setEnabled(真)
    self.updateActions()
    如果不是self.fittowAct.isChecked():
    通过
    #self.imageLabel.adjustSize()文件
    def打印(自我):
    dialog=QtPrintSupport.QPrintDialog(self.printer,self)
    if dialog.exec_389;()
    pixmap=self.view.pixmap\u item.pixmap()
    painter=QtGui.QPainter(self.printer)
    rect=painter.viewport()
    size=pixmap.size()
    size.scale(rect.size(),QtCore.Qt.KeepAspectRatio)
    painter.setViewport(rect.x(),rect.y(),size.width(),size.height())
    painter.setWindow(pixmap.rect())
    painter.drawPixmap(0,0,pixmap)
    def fitToWindow(自身):
    如果self.FittowAct.isChecked():
    self.view.fitToWindow()
    其他:
    self.view.resetZoom()
    self.updateActions()
    关于(自我)的定义:
    qtwidts.QMessageBox.about(
    自己
    “关于图像查看器”,
    “图像查看器示例显示了如何组合”
    “QLabel和QScrollArea用于显示图像。QLabel为”
    通常用于显示文本,但也可以显示
    “图像。QScrollArea提供了一个滚动视图”
    “另一个小部件。如果子小部件超过
    “帧,QScrollArea自动提供滚动条。

    ” “该示例演示了QLabel的扩展能力” 其内容(QLabel.scaledContents)和QScrollara的 “自动调整其内容大小的功能” (QScrollArea.WidgetResizeable),可用于实现 “缩放和缩放功能。

    ” “此外,该示例还显示了如何使用QPaint来” “打印图像。

    ”, ) def createActions(自我): self.openAct=qtwidts.QAction( “打开…”,self,快捷键=“Ctrl+O”,已触发=self.Open ) self.printAct=qtwidts.QAction( “打印…”,self,shortcut=“Ctrl+P”,enabled=False,triggered=self.Print_ ) self.exitAct=qtwidts.QAction( “E&xit”,self,shortcut=“Ctrl+Q”,triggered=self.close ) self.zoomInAct=qtwidts.QAction( “放大和放大(25%)”, 自己 快捷键=“Ctrl++”, 启用=错误, 已触发=self.view.zoomIn, ) self.zoomOutAct=qtwidts.QAction( “放大和缩小(25%)”, 自己 快捷键=“Ctrl+-”,
    from PyQt5.QtCore import Qt
    from PyQt5.QtGui import QImage, QPixmap, QPalette, QPainter
    from PyQt5.QtPrintSupport import QPrintDialog, QPrinter
    from PyQt5.QtWidgets import QLabel, QSizePolicy, QScrollArea, QMessageBox, QMainWindow, QMenu, QAction, \
        qApp, QFileDialog
    
    
    class QImageViewer(QMainWindow):
        def __init__(self):
            super().__init__()
    
            self.printer = QPrinter()
            self.scaleFactor = 0.0
    
            self.imageLabel = QLabel()
            self.imageLabel.setBackgroundRole(QPalette.Base)
            self.imageLabel.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
            self.imageLabel.setScaledContents(True)
    
            self.scrollArea = QScrollArea()
            self.scrollArea.setBackgroundRole(QPalette.Dark)
            self.scrollArea.setWidget(self.imageLabel)
            self.scrollArea.setVisible(False)
    
            self.setCentralWidget(self.scrollArea)
    
            self.createActions()
            self.createMenus()
    
            self.setWindowTitle("Image Viewer")
            self.resize(800, 600)
    
        def open(self):
            options = QFileDialog.Options()
            # fileName = QFileDialog.getOpenFileName(self, "Open File", QDir.currentPath())
            fileName, _ = QFileDialog.getOpenFileName(self, 'QFileDialog.getOpenFileName()', '',
                                                      'Images (*.png *.jpeg *.jpg *.bmp *.gif)', options=options)
            if fileName:
                image = QImage(fileName)
                if image.isNull():
                    QMessageBox.information(self, "Image Viewer", "Cannot load %s." % fileName)
                    return
    
                self.imageLabel.setPixmap(QPixmap.fromImage(image))
                self.scaleFactor = 1.0
    
                self.scrollArea.setVisible(True)
                self.printAct.setEnabled(True)
                self.fitToWindowAct.setEnabled(True)
                self.updateActions()
    
                if not self.fitToWindowAct.isChecked():
                    self.imageLabel.adjustSize()
    
        def print_(self):
            dialog = QPrintDialog(self.printer, self)
            if dialog.exec_():
                painter = QPainter(self.printer)
                rect = painter.viewport()
                size = self.imageLabel.pixmap().size()
                size.scale(rect.size(), Qt.KeepAspectRatio)
                painter.setViewport(rect.x(), rect.y(), size.width(), size.height())
                painter.setWindow(self.imageLabel.pixmap().rect())
                painter.drawPixmap(0, 0, self.imageLabel.pixmap())
    
        def zoomIn(self):
            self.scaleImage(1.25)
    
        def zoomOut(self):
            self.scaleImage(0.8)
    
        def normalSize(self):
            self.imageLabel.adjustSize()
            self.scaleFactor = 1.0
    
        def fitToWindow(self):
            fitToWindow = self.fitToWindowAct.isChecked()
            self.scrollArea.setWidgetResizable(fitToWindow)
            if not fitToWindow:
                self.normalSize()
    
            self.updateActions()
    
        def about(self):
            QMessageBox.about(self, "About Image Viewer",
                              "<p>The <b>Image Viewer</b> example shows how to combine "
                              "QLabel and QScrollArea to display an image. QLabel is "
                              "typically used for displaying text, but it can also display "
                              "an image. QScrollArea provides a scrolling view around "
                              "another widget. If the child widget exceeds the size of the "
                              "frame, QScrollArea automatically provides scroll bars.</p>"
                              "<p>The example demonstrates how QLabel's ability to scale "
                              "its contents (QLabel.scaledContents), and QScrollArea's "
                              "ability to automatically resize its contents "
                              "(QScrollArea.widgetResizable), can be used to implement "
                              "zooming and scaling features.</p>"
                              "<p>In addition the example shows how to use QPainter to "
                              "print an image.</p>")
    
        def createActions(self):
            self.openAct = QAction("&Open...", self, shortcut="Ctrl+O", triggered=self.open)
            self.printAct = QAction("&Print...", self, shortcut="Ctrl+P", enabled=False, triggered=self.print_)
            self.exitAct = QAction("E&xit", self, shortcut="Ctrl+Q", triggered=self.close)
            self.zoomInAct = QAction("Zoom &In (25%)", self, shortcut="Ctrl++", enabled=False, triggered=self.zoomIn)
            self.zoomOutAct = QAction("Zoom &Out (25%)", self, shortcut="Ctrl+-", enabled=False, triggered=self.zoomOut)
            self.normalSizeAct = QAction("&Normal Size", self, shortcut="Ctrl+S", enabled=False, triggered=self.normalSize)
            self.fitToWindowAct = QAction("&Fit to Window", self, enabled=False, checkable=True, shortcut="Ctrl+F",
                                          triggered=self.fitToWindow)
            self.aboutAct = QAction("&About", self, triggered=self.about)
            self.aboutQtAct = QAction("About &Qt", self, triggered=qApp.aboutQt)
    
        def createMenus(self):
            self.fileMenu = QMenu("&File", self)
            self.fileMenu.addAction(self.openAct)
            self.fileMenu.addAction(self.printAct)
            self.fileMenu.addSeparator()
            self.fileMenu.addAction(self.exitAct)
    
            self.viewMenu = QMenu("&View", self)
            self.viewMenu.addAction(self.zoomInAct)
            self.viewMenu.addAction(self.zoomOutAct)
            self.viewMenu.addAction(self.normalSizeAct)
            self.viewMenu.addSeparator()
            self.viewMenu.addAction(self.fitToWindowAct)
    
            self.helpMenu = QMenu("&Help", self)
            self.helpMenu.addAction(self.aboutAct)
            self.helpMenu.addAction(self.aboutQtAct)
    
            self.menuBar().addMenu(self.fileMenu)
            self.menuBar().addMenu(self.viewMenu)
            self.menuBar().addMenu(self.helpMenu)
    
        def updateActions(self):
            self.zoomInAct.setEnabled(not self.fitToWindowAct.isChecked())
            self.zoomOutAct.setEnabled(not self.fitToWindowAct.isChecked())
            self.normalSizeAct.setEnabled(not self.fitToWindowAct.isChecked())
    
        def scaleImage(self, factor):
            self.scaleFactor *= factor
            self.imageLabel.resize(self.scaleFactor * self.imageLabel.pixmap().size())
    
            self.adjustScrollBar(self.scrollArea.horizontalScrollBar(), factor)
            self.adjustScrollBar(self.scrollArea.verticalScrollBar(), factor)
    
            self.zoomInAct.setEnabled(self.scaleFactor < 3.0)
            self.zoomOutAct.setEnabled(self.scaleFactor > 0.333)
    
        def adjustScrollBar(self, scrollBar, factor):
            scrollBar.setValue(int(factor * scrollBar.value()
                                   + ((factor - 1) * scrollBar.pageStep() / 2)))
    
    
    if __name__ == '__main__':
        import sys
        from PyQt5.QtWidgets import QApplication
    
        app = QApplication(sys.argv)
        imageViewer = QImageViewer()
        imageViewer.show()
        sys.exit(app.exec_())
    
    import cv2 
    mouse_is_pressing = False
    start_x, start_y = -1, -1
    
    def mouse_callback(event, x, y, flags, param):
        global start_x, start_y, mouse_is_pressing 
    
        img_result = src.copy()
    
        if event == cv2.EVENT_LBUTTONDOWN:
    
            mouse_is_pressing = True
            start_x, start_y = x,y
    
            cv2.circle(img_result, (x,y), 10, (0,255,0),-1)
            cv2.imshow("img_color", img_result)
    
        elif event == cv2.EVENT_MOUSEMOVE:
            if mouse_is_pressing: 
                cv2.rectangle(img_result, (start_x, start_y), (x,y), (0,255,0), 3)
                cv2.imshow("img_color", img_result)
    
        elif event == cv2.EVENT_LBUTTONUP:
            mouse_is_pressing = False 
    
            img_part = img_result[start_y:y, start_x:x]
            cv2.imshow("img_color", img_result)
            cv2.imshow("img_part", img_part)
    
    src = cv2.imread("D:/python data/image/image.jpg")
    cv2.imshow("img_color", src)
    cv2.setMouseCallback("img_color", mouse_callback)
    cv2.waitKey(0)
    cv2.destroyAllWindows()