【问题标题】:How to display a cv2 video inside a python GUI? [duplicate]如何在 python GUI 中显示 cv2 视频? [复制]
【发布时间】:2019-11-26 07:15:43
【问题描述】:

我正在使用 Python/PyQt5 创建一个 GUI,它应该在同一窗口中显示视频以及其他小部件。我已经尝试了不同的方法来解决这个问题,但似乎仍然无法让它发挥作用。

方法一: 使用 OpenCV/cv2 在像素图中添加视频仅显示视频的第一帧。

方法 2: 我已经设法使用 cv2 播放视频,但是它会在新窗口中打开。

方法 3: 我也尝试使用 QVideoWidget,但显示一个空白屏幕并且视频无法播放。

# only shows an image from the video, but in the correct place
        cap = cv2.VideoCapture('video.mov')
        ret, frame = cap.read()
        if ret:
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            img = QImage(frame, frame.shape[1], frame.shape[0], QImage.Format_RGB888)
            pix = QPixmap.fromImage(img)
            pix = pix.scaled(600, 400, Qt.KeepAspectRatio, Qt.SmoothTransformation)
            self.ui.label_7.setPixmap(pix)

        # opens new window
        cap = cv2.VideoCapture('video.mov')

        while (cap.isOpened()):
            ret, frame = cap.read()

            self.ui.frame = cv2.imshow('frame', frame)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break

        cap.release()

        # shows a blank screen 
        self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface)
        videoWidget = self.ui.vid_widget
        self.mediaPlayer.setVideoOutput(videoWidget)
        self.mediaPlayer.setMedia(QMediaContent(QUrl.fromLocalFile('video.mov')))

非常感谢任何有关如何在另一个小部件中/在同一窗口中播放视频的帮助。

【问题讨论】:

    标签: python opencv pyqt pyqt5 cv2


    【解决方案1】:

    while 循环内,您需要再次将frame 转换为QPixmap,类似于您上面所做的,然后更新ui

    cap = cv2.VideoCapture('video.mov')
    
    while (cap.isOpened()):
        ret, frame = cap.read()
        if not ret:
            break
    
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        img = QImage(frame, frame.shape[1], frame.shape[0], QImage.Format_RGB888)
        pix = QPixmap.fromImage(img)
        pix = pix.scaled(600, 400, Qt.KeepAspectRatio, Qt.SmoothTransformation)
        self.ui.label_7.setPixmap(pix)    
    
        self.ui.frame = pix  # or img depending what `ui.frame` needs
    
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    
    cap.release()
    

    【讨论】:

    • 谢谢,成功了!
    猜你喜欢
    • 1970-01-01
    • 2021-05-20
    • 2019-06-15
    • 1970-01-01
    • 2020-07-07
    • 2018-09-07
    • 1970-01-01
    • 1970-01-01
    • 2018-01-18
    相关资源
    最近更新 更多