Python获取视频文件的各种属性信息

很多时候我们需要获取视频文件的属性信息,这里记录一下几种使用Python获取视频文件的属性信息的方法。

方法一:使用opencv库

需要安装opencv库

pip install opencv-python

具体代码如下:

 1 import cv2
 2 
 3 def get_video_info_opencv(video_path):
 4     """
 5     使用OpenCV获取视频信息
 6     """
 7     # 打开视频文件
 8     cap = cv2.VideoCapture(video_path)
 9     
10     if not cap.isOpened():
11         print("无法打开视频文件")
12         return None
13     
14     # 获取视频属性
15     fps = cap.get(cv2.CAP_PROP_FPS)           # 帧率
16     frame_count = cap.get(cv2.CAP_PROP_FRAME_COUNT)  # 总帧数
17     width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))   # 宽度
18     height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) # 高度
19     duration = frame_count / fps              # 时长(秒)
20     
21     # 关闭视频文件
22     cap.release()
23     
24     return {
25         'fps': fps,
26         'frame_count': frame_count,
27         'width': width,
28         'height': height,
29         'duration': duration,
30         'resolution': f"{width}x{height}"
31     }
32 
33 # 使用示例
34 video_path = "example.mp4"
35 info = get_video_info_opencv(video_path)
36 if info:
37     print(f"帧率: {info['fps']}")
38     print(f"总帧数: {info['frame_count']}")
39     print(f"分辨率: {info['resolution']}")
40     print(f"时长: {info['duration']:.2f} 秒")

 

方法二:使用 moviepy

需要安装moviepy库

pip install moviepy

具体代码如下:

 1 from moviepy.editor import VideoFileClip
 2 
 3 def get_video_info_moviepy(video_path):
 4     """
 5     使用moviepy获取视频信息
 6     """
 7     try:
 8         clip = VideoFileClip(video_path)
 9         
10         info = {
11             'fps': clip.fps,
12             'frame_count': int(clip.duration * clip.fps),
13             'width': clip.size[0],
14             'height': clip.size[1],
15             'duration': clip.duration,
16             'resolution': f"{clip.size[0]}x{clip.size[1]}"
17         }
18         
19         clip.close()
20         return info
21         
22     except Exception as e:
23         print(f"处理视频时出错: {e}")
24         return None
25 
26 # 使用示例
27 video_path = "example.mp4"
28 info = get_video_info_moviepy(video_path)
29 if info:
30     print(f"帧率: {info['fps']}")
31     print(f"总帧数: {info['frame_count']}")
32     print(f"分辨率: {info['resolution']}")
33     print(f"时长: {info['duration']:.2f} 秒")

 

方法三:使用 cv2 和其他库的综合方案

需要安装opencv库

 

pip install opencv-python

 

具体代码如下:

 1 import cv2
 2 import os
 3 
 4 class VideoInfoExtractor:
 5     def __init__(self, video_path):
 6         self.video_path = video_path
 7         self.cap = None
 8         
 9     def __enter__(self):
10         self.cap = cv2.VideoCapture(self.video_path)
11         return self
12         
13     def __exit__(self, exc_type, exc_val, exc_tb):
14         if self.cap:
15             self.cap.release()
16     
17     def get_basic_info(self):
18         """获取基础视频信息"""
19         if not self.cap or not self.cap.isOpened():
20             raise ValueError("无法打开视频文件")
21             
22         # 获取基本属性
23         fps = self.cap.get(cv2.CAP_PROP_FPS)
24         frame_count = self.cap.get(cv2.CAP_PROP_FRAME_COUNT)
25         width = int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH))
26         height = int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
27         duration = frame_count / fps if fps > 0 else 0
28         
29         return {
30             'fps': fps,
31             'frame_count': int(frame_count),
32             'width': width,
33             'height': height,
34             'duration': duration,
35             'resolution': f"{width}x{height}",
36             'file_size': os.path.getsize(self.video_path)
37         }
38     
39     def get_detailed_info(self):
40         """获取详细视频信息"""
41         basic_info = self.get_basic_info()
42         
43         # 获取编码信息
44         codec = self.cap.get(cv2.CAP_PROP_CODEC_PIXEL_FORMAT)
45         fourcc = self.cap.get(cv2.CAP_PROP_FOURCC)
46         
47         detailed_info = basic_info.copy()
48         detailed_info.update({
49             'codec': codec,
50             'fourcc': fourcc,
51             'aspect_ratio': f"{basic_info['width']}:{basic_info['height']}"
52         })
53         
54         return detailed_info
55 
56 # 使用示例
57 video_path = "example.mp4"
58 try:
59     with VideoInfoExtractor(video_path) as extractor:
60         info = extractor.get_detailed_info()
61         
62         print("=== 视频基本信息 ===")
63         print(f"文件路径: {video_path}")
64         print(f"分辨率: {info['resolution']}")
65         print(f"帧率: {info['fps']:.2f} FPS")
66         print(f"总帧数: {info['frame_count']}")
67         print(f"时长: {info['duration']:.2f} 秒")
68         print(f"文件大小: {info['file_size'] / (1024*1024):.2f} MB")
69         print(f"宽高比: {info['aspect_ratio']}")
70         
71 except ValueError as e:
72     print(f"错误: {e}")

 

posted on 2025-10-02 09:40  Arthurian  阅读(35)  评论(0)    收藏  举报