PySide2 播放视频

import os
import sys
import traceback

from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *

import home_ui
import cv2

print('os:', sys.platform)
if sys.platform.lower().startswith('linux'):
    os.environ.pop("QT_QPA_PLATFORM_PLUGIN_PATH")


class HomeWindow(QMainWindow):

    def __init__(self):
        super(HomeWindow, self).__init__()
        self.ui = home_ui.Ui_MainWindow()
        self.ui.setupUi(self)

        self.frame_timer = QTimer()
        self.video_capture = cv2.VideoCapture('a.mp4')
        self.fps = self.video_capture.get(cv2.CAP_PROP_FPS)

        self.frame_timer.timeout.connect(self.display_video_stream)
        self.frame_timer.start(int(1000 // self.fps))

    def display_video_stream(self):
        display_with = self.ui.label_video.width()
        display_height = self.ui.label_video.height()
        try:
            ret, cv_img = self.video_capture.read()
            if not ret:
                return False
            rgb_image = cv2.cvtColor(cv_img, cv2.COLOR_BGR2RGB)
            h, w, ch = rgb_image.shape
            bytes_per_line = ch * w
            convert_to_qt_format = QImage(rgb_image.data, w, h, bytes_per_line, QImage.Format_RGB888)
            p = convert_to_qt_format.scaled(display_with, display_height, Qt.KeepAspectRatio)
            self.ui.label_video.setPixmap(QPixmap.fromImage(p))
        except:
            print(f'{traceback.format_exc()}')


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = HomeWindow()
    window.show()
    sys.exit(app.exec_())

你可能感兴趣的:(python,音视频,python,pyqt)