无法从类中传递调整大小的QLabel几何体

2024-09-26 22:42:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用PyQt5和OpenCV。我想创建一个类,该类读取视频帧并执行橡皮筋拉伸以生成几何体,其他类将使用该几何体来裁剪视频流(本示例中不包括第二个类)

在本例中,从网络摄像头流中捕获图像,然后进行显示。在图像上拉伸橡皮筋将生成打印的几何图形。几何图形在ReGeomVid类中打印,但不在main()类中打印。我需要将几何体放入main()。谢谢你的帮助

import sys, cv2
from PyQt5.QtWidgets import QRubberBand, QApplication, QLabel
from PyQt5.QtGui import QPixmap, QImage
from PyQt5.QtCore import QRect, QSize

class ReGeomVid (QLabel):
    def __init__(self, cap, parent=None):
        super(ReGeomVid, self).__init__(parent)
        self.cap = cap
        self.currentQRect = QRect()
        self.initUI()

    def initUI (self):        
        ret, frame = self.cap.read() #First frame read is black
        ret, frame = self.cap.read() #Second frame read is normal
        if ret == True:
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            img = QImage(frame,frame.shape[1], frame.shape[0], QImage.Format_RGB888)
            pix = QPixmap.fromImage(img)
            self.setPixmap(QPixmap(pix))

    def mousePressEvent (self, eventQMouseEvent):
        self.originQPoint = eventQMouseEvent.pos()
        print(self.originQPoint)
        self.currentQRubberBand = QRubberBand(QRubberBand.Rectangle, self)
        self.currentQRubberBand.setGeometry(QRect(self.originQPoint, QSize()))
        self.currentQRubberBand.show()

    def mouseMoveEvent (self, eventQMouseEvent):
        self.currentQRubberBand.setGeometry(QRect(self.originQPoint, eventQMouseEvent.pos()).normalized())

    def mouseReleaseEvent (self, eventQMouseEvent):
        self.currentQRubberBand.hide()
        self.currentQRect = self.currentQRubberBand.geometry()        
        self.currentQRubberBand.deleteLater()
        self.croppedPixmap = self.pixmap().copy(self.currentQRect)
        print("In mouserelease: Geometry = ", self.currentQRect)

if __name__ == '__main__':
    myQApplication = QApplication(sys.argv)
    stream = cv2.VideoCapture(0)
    x = ReGeomVid(stream)
    x.show()
    pixMainGeom = x.currentQRect
    print("In main: Geometry = ", x.currentQRect)
    sys.exit(myQApplication.exec_())

Tags: importselfreadmaindefcv2framepyqt5
1条回答
网友
1楼 · 发布于 2024-09-26 22:42:34

变量self.currentQRectmouseReleaseEvent中设置。因此,当执行main中的打印时,它仍然无效

self.currentQRect准备就绪时,使用信号运行main中的代码:

class ReGeomVid (QLabel):
    currentQRectChanged = pyqtSignal(QRect)
...
    def mouseReleaseEvent (self, eventQMouseEvent):
        ...
        self.currentQRectChanged.emit(self.currentQRect)

def printCurrentQRect(rect):
    print("In main: Geometry = ", rect)


if __name__ == '__main__':
    myQApplication = QApplication(sys.argv)
    stream = cv2.VideoCapture(0)
    x = ReGeomVid(stream)
    x.show()
    x.currentQRectChanged.connect(printCurrentQRect)
    sys.exit(myQApplication.exec_())

相关问题 更多 >

    热门问题