基于pyqt5与opencv读取播放本地视频
import sys
import cv2
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, \
QVBoxLayout, QWidget, QPushButton, QFileDialog
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtCore import Qt, QTimer
class VideoPlayer(QWidget):
def __init__(self):
super().__init__()
self.video_label = QLabel(self)
layout = QVBoxLayout()
layout.addWidget(self.video_label)
self.select_button = QPushButton('选择视频', self)
self.select_button.clicked.connect(self.select_video)
layout.addWidget(self.select_button)
self.setLayout(layout)
self.camera = None
self.timer = QTimer()
self.timer.timeout.connect(self.display_video_frame)
def select_video(self):
file_path, _ = QFileDialog.getOpenFileName(self, '选择视频文件', '', 'Video Files (*.mp4 *.avi)')
if file_path:
self.camera = cv2.VideoCapture(file_path)
self.timer.start(30)
def display_video_frame(self):
ret, frame = self.camera.read()
if ret:
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
image = QImage(frame_rgb.data, frame_rgb.shape[1], frame_rgb.shape[0], QImage.Format_RGB888)
pixmap = QPixmap.fromImage(image)
scaled_pixmap = pixmap.scaled(self.video_label.size(), Qt.KeepAspectRatio)
self.video_label.setPixmap(scaled_pixmap)
def closeEvent(self, event):
if self.camera and self.camera.isOpened():
self.camera.release()
event.accept()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = QMainWindow()
video_player = VideoPlayer()
window.setCentralWidget(video_player)
window.resize(800, 600) # 设置窗口大小
window.setWindowTitle("视频播放")
window.show()
sys.exit(app.exec_())
这段代码是一个简单的视频播放器应用程序,使用了Python的OpenCV库和PyQt5库。它提供了一个GUI界面,可以选择本地视频文件并播放。
首先,我们导入所需的模块和类,包括sys
、cv2
、QApplication
、QMainWindow
、QLabel
、QVBoxLayout
、QWidget
、QPushButton
、QFileDialog
、QImage
、QPixmap
和QTimer
。
然后,定义了一个名为VideoPlayer
的自定义QWidget类。在类的构造函数__init__
中,首先调用父类的构造函数super().__init__()
。然后创建一个QLabel
对象video_label
,用于显示视频帧。接着创建一个垂直布局layout
,并将video_label
添加到布局中。再创建一个QPushButton
对象select_button
,文本设置为"选择视频",并连接到select_video
槽函数。最后,将布局设置为当前QWidget的布局,并初始化camera
和timer
变量。
select_video
是一个槽函数,用于处理点击"选择视频"按钮时的操作。在该函数中,使用QFileDialog.getOpenFileName
方法打开一个文件对话框,让用户选择本地视频文件。如果用户选择了一个文件,使用OpenCV的cv2.VideoCapture()
函数打开该文件,并开始定时器以读取和显示视频帧。
display_video_frame
是另一个槽函数,用于定时显示视频帧。在该函数中,使用camera.read()
方法读取视频的下一帧。如果读取成功(ret
为True),将帧从BGR颜色空间转换为RGB颜色空间,然后创建一个QImage
对象,并将其设置为video_label
的像素图。最后,按比例缩放图像到video_label
的大小,并设置为video_label
的当前像素图。
closeEvent
是一个事件处理函数,用于在窗口关闭时释放摄像头资源。在该函数中,检查摄像头是否已经打开,如果是,则释放资源。
在主程序中,创建一个QApplication
对象和一个QMainWindow
对象。然后,创建一个VideoPlayer
对象,并将其设置为窗口的中央部件。设置窗口的初始大小为800x600像素,并设置窗口标题为"视频播放"。最后,启动应用程序的事件循环,并确保程序正常退出。