opencv with pyqt4对话框显示

时间:2015-09-09 05:21:07

标签: python opencv image-processing pyqt4 pyside

我试图用我的对话框(在pyqt4中创建)嵌入视频捕获。对于同样的我累了下面的代码。但它只是开始捕获并且不会在对话框中显示任何内容。 请帮助我了解以下代码中缺少的内容。 在这里,self.videoFrame是QtGui下的QLabel。

def onRun(self):
        self.playing = True
        capture = cv2.VideoCapture(0)
        data1=np.array([])

        while self.playing:

            _, data = capture.read()
            data1 = cv2.cvtColor(data, cv2.cv.CV_BGR2RGB)
            qImage = QtGui.QImage(data1, data1.shape[2], data1.shape[2], 
                QtGui.QImage.Format_RGB888)
            qImage=QtGui.QPixmap.fromImage(qImage)
            self.videoFrame.setPixmap(
            qImage)
            self.videoFrame.setScaledContents(True)            
            QtGui.qApp.processEvents()
            cv2.waitKey(5)

        cv2.destroyAllWindows() 

1 个答案:

答案 0 :(得分:1)

这有效:

from PyQt4 import QtCore,QtGui
import sys
import cv2
import numpy as np

class ImageWidget(QtGui.QWidget):
    def __init__(self,parent=None):
        super(ImageWidget,self).__init__(parent)
        self.image=None

    def setImage(self,image):
        self.image=image
        sz=image.size()
        self.setMinimumSize(sz)
        self.update()

    def paintEvent(self,event):
        qp=QtGui.QPainter()
        qp.begin(self)
        if self.image:
            qp.drawImage(QtCore.QPoint(0,0),self.image)
        qp.end()

class MainWindow(QtGui.QMainWindow):
    def __init__(self,parent=None):
        super(MainWindow,self).__init__(parent)
        self.videoFrame=ImageWidget()
        self.setCentralWidget(self.videoFrame)
        self.timer=QtCore.QTimer(self)
        self.timer.timeout.connect(self.updateImage)
        self.timer.start(30)
        self.capture = cv2.VideoCapture(0)

    def updateImage(self):
        _, img = self.capture.read()
        #img=cv2.cvtColor(img, cv.CV_BGR2RGB)
        height, width, bpc = img.shape
        bpl = bpc * width
        image = QtGui.QImage(img.data, width, height, bpl, QtGui.QImage.Format_RGB888)
        self.videoFrame.setImage(image)


def main():
    app=QtGui.QApplication(sys.argv)
    w=MainWindow()
    w.show()
    app.exec_()

if __name__=='__main__':
    main()