无法通过类传递调整大小的QLabel几何

时间:2019-05-31 12:40:59

标签: python python-3.x opencv pyqt pyqt5

我正在使用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_())

1 个答案:

答案 0 :(得分:1)

您的变量self.currentQRectmouseReleaseEvent中设置。因此,当执行主程序中的 print 时,它仍然无效。

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

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_())