Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 应用过滤器后在PyQt5 GUI中裁剪图像_Python_User Interface_Pyqt5_Qt Creator_Crop - Fatal编程技术网

Python 应用过滤器后在PyQt5 GUI中裁剪图像

Python 应用过滤器后在PyQt5 GUI中裁剪图像,python,user-interface,pyqt5,qt-creator,crop,Python,User Interface,Pyqt5,Qt Creator,Crop,我正在构建一个图像编辑器应用程序。我已经使用Qt Creator for GUI和OpenCV来操作图像。我希望裁剪图像并将其显示在新窗口中。下面是代码的截图和代码。 我要合并以下代码: from PyQt5 import QtCore, QtGui, QtWidgets # GUI REQUIREMENTS from PyQt5.QtGui import * from PyQt5.QtWidgets import * from PyQt5.QtCore import * import sys

我正在构建一个图像编辑器应用程序。我已经使用Qt Creator for GUI和OpenCV来操作图像。我希望裁剪图像并将其显示在新窗口中。下面是代码的截图和代码。 我要合并以下代码:

from PyQt5 import QtCore, QtGui, QtWidgets # GUI REQUIREMENTS
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import sys # RUNNING THE APP REQUIREMENTS
import cv2 as cv # FILTER REQUIREMENTS
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtWidgets import (QApplication, QDialog, QFileDialog, QGridLayout,
                         QLabel, QPushButton, QGraphicsView)
from PyQt5.QtWidgets import QGraphicsView                  
fname=''

class Ui_Form(QtWidgets.QGraphicsView):
def __init__(self, parent=None):
    super().__init__(QtWidgets.QGraphicsScene(), parent)

    self.setupUi(self)

    #QGraphicsScene class provides a surface for managing a large number of 2D graphical items
    self.pixmap_item = self.scene().addPixmap(QtGui.QPixmap())
    # alignment of the widgets
    self.setDragMode(QtWidgets.QGraphicsView.RubberBandDrag) 
    # user clicks on the scene background and drags the mouse
    self.rubberBandChanged.connect(self.onRubberBandChanged) 
    # onRubberBandChanged = selects the area
    self.last_rect = QtCore.QPointF() 
    #defines a point in the plane using floating point precision.

def setupUi(self, Form):
    Form.setObjectName("Form")
    Form.resize(800, 600)
    self.setWindowTitle("#1 Task Sagar")
    # Dimensions of the 2 wraps, 2 buttons (open n apply), 2 labels for displaying image
    self.groupBox = QtWidgets.QGroupBox(Form)
    self.groupBox.setGeometry(QtCore.QRect(40, 20, 331, 500))
    self.groupBox.setObjectName("groupBox")
    self.btn1 = QtWidgets.QPushButton(self.groupBox)
    self.btn1.setGeometry(QtCore.QRect(130, 40, 156, 23))
    self.btn1.setObjectName("btn1")
    self.btn1.clicked.connect(self.open)
    self.label = QtWidgets.QLabel(self.groupBox)
    self.label.setGeometry(QtCore.QRect(45, 90, 271, 450))
    self.label.setText("")
    self.label.setObjectName("label")

    self.groupBox_2 = QtWidgets.QGroupBox(Form)
    self.groupBox_2.setGeometry(QtCore.QRect(440, 20, 331, 500))
    self.groupBox_2.setObjectName("groupBox_2")
    self.btn2 = QtWidgets.QPushButton(self.groupBox_2)
    self.btn2.setGeometry(QtCore.QRect(110, 40, 156, 23))
    self.btn2.setObjectName("btn2")
    self.btn2.clicked.connect(self.gray_scale)
    self.label_2 = QtWidgets.QLabel(self.groupBox_2)
    self.label_2.setGeometry(QtCore.QRect(45, 90, 271, 450))
    self.label_2.setText("")
    self.label_2.setObjectName("label_2")
    self.setDragMode(QtWidgets.QGraphicsView.RubberBandDrag) 
    # user clicks on the scene background and drags the mouse
    self.rubberBandChanged.connect(self.onRubberBandChanged) 
    # onRubberBandChanged = selects the area
    self.last_rect = QtCore.QPointF() 
    #defines a point in the plane using floating point precision.


    self.retranslateUi(Form)
    QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
    _translate = QtCore.QCoreApplication.translate
    Form.setWindowTitle(_translate("Form", "#1 Task Sagar"))
    self.groupBox.setTitle(_translate("Form", "Original image"))
    self.btn1.setText(_translate("Form", "Select"))
    self.groupBox_2.setTitle(_translate("Form", "Gray"))
    self.btn2.setText(_translate("Form", "Apply"))


def setPixmap(self, pixmap):
    self.pixmap_item.setPixmap(pixmap)

def open(self):
    global fname
    imgName, imgType = QFileDialog.getOpenFileName(self, "Open picture", "", "*;;*.png;;All Files(*)")
    image = cv.imread(imgName)
    if image is None:
        print("No picture selected")
    else:
        size = (int(self.label.width()), int(self.label.height())) # width n height of label
        shrink = cv.resize(image, size, interpolation=cv.INTER_AREA) # Resize image to label size using Interpolation
        shrink = cv.cvtColor(shrink, cv.COLOR_BGR2RGB) # convert Color space
        self.QtImg = QtGui.QImage(shrink.data, #resize image in QT without distortion
                                  shrink.shape[1], # get rows, columns data and store in tuple
                                  shrink.shape[0],
                                  shrink.shape[1]*3,
                                  QtGui.QImage.Format_RGB888) # Qt color spaces rgb convert
        self.label.setPixmap(QtGui.QPixmap.fromImage(self.QtImg))
        fname = imgName
        print(imgName)
        one = 50
        two = 50


def gray_scale(self):
    global fname
    image = cv.imread(fname)
    if image is None:
        print("No picture selected")
    else:
        image = cv.cvtColor(image, cv.COLOR_BGR2GRAY) #calling gray filter from CV
        size = (int(self.label_2.width()), int(self.label_2.height())) # width n height of label
        shrink = cv.resize(image, size, interpolation=cv.INTER_AREA) # Resize image to label size using Interpolation 
        shrink = cv.cvtColor(shrink, cv.COLOR_BGR2RGB) ## convert Color space
        self.QtImg = QtGui.QImage(shrink.data, #resize image in QT without distortion
                                  shrink.shape[1], # get rows, columns data and store in tuple
                                  shrink.shape[0], 
                                  shrink.shape[1]*3, 
                                  QtGui.QImage.Format_RGB888) # Qt color spaces rgb convert
        self.label_2.setPixmap(QtGui.QPixmap.fromImage(self.QtImg))

@QtCore.pyqtSlot(QtCore.QRect, QtCore.QPointF, QtCore.QPointF) 
def onRubberBandChanged(self, rubberBandRect, fromScenePoint, toScenePoint): #This signal is emitted when the rubber band rect is changed. The viewport Rect is specified by rubberBandRect. 
    if rubberBandRect.isNull(): 
        #The drag start position and drag end position are provided in scene points with fromScenePoint and toScenePoint.
        pixmap = self.pixmap_item.pixmap() 
        # Fit to window
        rect = self.pixmap_item.mapFromScene(self.last_rect).boundingRect().toRect() 
        # the outer bounds of the item as a rectangle; all painting must be restricted to inside an item's bounding rect.
        #Maps the rectangle rect, which is in this item's scene's coordinate system, to this item's coordinate system, and returns the mapped rectangle as a polygon.
        if not rect.intersected(pixmap.rect()).isNull(): #Intersection of ROI and viewport, if viewport is null
            crop_pixmap = pixmap.copy(rect) #Returns a deep copy of the subset of the pixmap that is specified by the given rectangle.
            label_3 = QtWidgets.QLabel(pixmap=crop_pixmap) # QLabel widget provides a text or image display. 
            dialog = QtWidgets.QDialog(self) #provide a return value
            lay = QtWidgets.QVBoxLayout(dialog) #vertical alaign of boxes
            lay.addWidget(label) #Adds widget to the end of this box layout, with a stretch factor of stretch and alignment alignment.
            dialog.exec_() # Modal dialog -users cannot interact with any other window in the same application until they close the dialog
        self.last_rect = QtCore.QRectF() #QRectF class defines a rectangle in the plane using floating point precision.
    else:
        self.last_rect = QtCore.QRectF(fromScenePoint, toScenePoint)


if __name__ == '__main__':
app = QApplication(sys.argv)
fileload =  Ui_Form()
fileload.show()
sys.exit(app.exec_())
使用Qt的图像处理GUI

以下是裁剪代码,它还使用Qt并使用GraphicScene类进行裁剪:

从PyQt5导入QtCore、QtGui、QtWidgets、QtPrintSupport
类查看器(QtWidgets.QGraphicsView):
def uuu init uuu(self,parent=None):
super()
#QGraphicscene类提供了一个用于管理大量二维图形项的曲面
self.pixmap_item=self.scene().addPixmap(QtGui.QPixmap())
#pixmap将图形图像存储并显示为像素颜色值的矩形阵列。
self.setAlignment(QtCore.Qt.AlignTop | QtCore.Qt.AlignLeft)
#小部件的对齐
self.setDragMode(QtWidgets.QGraphicsView.RubberBandDrag)
#用户单击场景背景并拖动鼠标
self.rubberBandChanged.connect(self.onRubberBandChanged)
#onRubberBandChanged=选择区域
self.last_rect=QtCore.QPointF()
#使用浮点精度定义平面中的点。
def setPixmap(自身,pixmap):
self.pixmap_item.setPixmap(pixmap)
#将项目的pixmap设置为pixmap。
def重置缩放(自):
self.resetTransform()
#将此项的转换重置为标识转换。标识转换是一种数据转换,它将源数据复制到目标数据中而不进行更改
def fitToWindow(自身):
self.fitInView(self.pixmap\u项)
#缩放视图矩阵并滚动滚动条,以确保场景矩形矩形矩形适合视口内部。
@QtCore.pyqtlot(QtCore.QRect、QtCore.QPointF、QtCore.QPointF)
#QRect类使用整数精度定义平面中的矩形
def ON RUBERBANDCHANGED(自我、RUBERBANDRECT、从场景点到场景点):#更改橡皮筋rect时会发出此信号。视口矩形由rubberBandRect指定。
如果rubberBandRect.isNull():
#在具有fromScenePoint和toScenePoint的场景点中提供了拖动开始位置和拖动结束位置。
pixmap=self.pixmap\u item.pixmap()
#适合窗户
rect=self.pixmap\u item.mapFromScene(self.last\u rect.boundingRect().toRect())
#项目的外部边界为矩形;所有绘制必须限制在项目的边界矩形内。
#将此项目的场景坐标系中的矩形矩形映射到此项目的坐标系,并将映射的矩形作为多边形返回。
如果不是矩形相交(pixmap.rect()).isNull():#如果视口为空,则为ROI和视口的交点
crop_pixmap=pixmap.copy(rect)#返回给定矩形指定的pixmap子集的深度副本。
label=qtwidts.QLabel(pixmap=crop_pixmap)#QLabel小部件提供文本或图像显示。
dialog=qtwidts.QDialog(self)#提供返回值
lay=qtwidts.QVBoxLayout(对话框)#框的垂直对齐
lay.addWidget(label)#将widget添加到此框布局的末尾,拉伸因子为拉伸和对齐。
dialog.exec#Modal dialog()#Modal dialog-在关闭对话框之前,用户无法与同一应用程序中的任何其他窗口进行交互
self.last_rect=QtCore.QRectF()#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()#QPrinter类是在打印机上绘制的绘制设备。比如PIXMAP和QWidget
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打印(自我):#打印图像