Python批量读取视频文件的时间长度

要批量读取视频文件的时间长度,可以使用Python中的OpenCV库。以下是一个示例代码,可以读取指定文件夹中所有视频文件的时间长度:

import os
import cv2

video_dir = 'path/to/video/directory'

for filename in os.listdir(video_dir):
    if filename.endswith('.mp4') or filename.endswith('.avi'): # 可以根据需要更改视频格式
        filepath = os.path.join(video_dir, filename)
        cap = cv2.VideoCapture(filepath)
        length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
        fps = int(cap.get(cv2.CAP_PROP_FPS))
        duration = length / fps
        print(f"{
      
      filename}: {
      
      duration} seconds")
        cap.release()

这个代码循环遍历指定文件夹中的所有文件,对于每个视频文件,使用OpenCV的VideoCapture对象打开文件,并使用get方法获取视频的帧数和帧率。然后,通过将帧数除以帧率来计算视频的持续时间。最后,代码打印出每个视频文件的名称和持续时间。

猜你喜欢

转载自blog.csdn.net/qq_41563601/article/details/129229008