pyQt5+cv2实现控制条对视频的播放,视频帧的处理
结果如图:
记录一下开发代码
import cv2
from PyQt5.QtWidgets import QApplication, QMainWindow, QSlider, QVBoxLayout, QWidget, QLabel, QHBoxLayout
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtCore import Qt, QTimer
class VideoPlayer(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Video Player")
# 创建 QWidget 并设置布局
self.central_widget = QWidget()
self.layout = QVBoxLayout()
self.central_widget.setLayout(self.layout)
self.setCentralWidget(self.central_widget)
# 创建进度条
self.slider = QSlider(Qt.Horizontal)
self.slider.setMinimum(0)
self.slider.setMaximum(100)
self.slider.valueChanged.connect(self.set_video_position)
# 创建显示时长的 QLabel
self.current_time_label = QLabel()
self.total_time_label = QLabel()
# 创建一个水平布局来放置进度条和时长标签
time_layout = QHBoxLayout()
time_layout.addWidget(self.slider)
time_layout.addWidget(self.current_time_label)
time_layout.addWidget(self.total_time_label)
self.layout.addLayout(time_layout)
# 创建 QLabel 显示视频
self.video_label = QLabel()
self.layout.addWidget(self.video_label)
# 加载视频文件
self.cap = cv2.VideoCapture(r"D:\atian\mldl\pljc\focus\1.mp4")
self.fps = self.cap.get(cv2.CAP_PROP_FPS)
self.total_frames = self.cap.get(cv2.CAP_PROP_FRAME_COUNT)
# 创建 QTimer 定时器更新进度条和视频帧
self.timer = QTimer()
self.timer.timeout.connect(self.update_video)
self.timer.start(1000 / self.fps)
def update_video(self):
ret, frame = self.cap.read()
if ret:
# 处理视频帧
# ...
# 更新进度条
current_position = self.cap.get(cv2.CAP_PROP_POS_FRAMES)
self.slider.setValue(int(current_position / self.total_frames * 100))
# 更新时长标签
current_seconds = int(current_position / self.fps)
total_seconds = int(self.total_frames / self.fps)
current_hours = current_seconds // 3600
current_minutes = (current_seconds % 3600) // 60
current_seconds = current_seconds % 60
total_hours = total_seconds // 3600
total_minutes = (total_seconds % 3600) // 60
total_seconds = total_seconds % 60
self.current_time_label.setText(f"{current_hours:02d}:{current_minutes:02d}:{current_seconds:02d}")
self.total_time_label.setText(f"{total_hours:02d}:{total_minutes:02d}:{total_seconds:02d}")
# 将 OpenCV 的 BGR 图像转换为 RGB 图像
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# 显示视频帧
height, width, channel = frame.shape
bytes_per_line = 3 * width
q_image = QImage(frame.data, width, height, bytes_per_line, QImage.Format_RGB888)
pixmap = QPixmap.fromImage(q_image)
self.video_label.setPixmap(pixmap)
def set_video_position(self, value):
# 根据进度条值设置视频进度
new_position = value / 100 * self.total_frames
self.cap.set(cv2.CAP_PROP_POS_FRAMES, new_position)
if __name__ == "__main__":
app = QApplication([])
player = VideoPlayer()
player.show()
app.exec_()