首页 > 解决方案 > 如何在 python GUI 中显示 cv2 视频?

问题描述

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

方法 1:使用 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')))

任何有关如何在另一个小部件/在同一窗口中播放视频的帮助将不胜感激。

标签: pythonopencvpyqtpyqt5cv2

解决方案


while循环内部,您需要再次转换frame为 a 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()

推荐阅读