赞
踩
这段代码用于查看视频帧率,帧数以及大小,并且是否需要按照设定参数压缩原始视频。主要定义了两个主要函数:analyze_video
和 compress_video
,以及一个主程序块来调用这些函数。下面是对这段代码功能的详细分析:
analyze_video
函数此函数用于分析给定视频的基本属性,并打印出这些信息。
frame_count
)。frame_rate
)。width
, height
)。video_size
),单位为兆字节(MB)。compress_video
函数此函数用于根据指定的参数压缩视频,并将压缩后的视频保存到一个新的文件中。
这部分代码负责:
analyze_video
函数来显示视频的信息。compress_video
函数执行压缩操作。这段代码实现了以下功能:
- import cv2
- import os
- from tqdm import tqdm
-
-
- def analyze_video(video_path):
- # 打开视频文件
- cap = cv2.VideoCapture(video_path)
-
- # 获取视频属性
- frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
- frame_rate = cap.get(cv2.CAP_PROP_FPS)
- width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
- height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
- video_size = os.path.getsize(video_path) / (1024 * 1024) # 文件大小,单位MB
-
- cap.release()
-
- print(f"视频信息:\n"
- f"帧数: {frame_count}\n"
- f"帧率: {frame_rate} FPS\n"
- f"分辨率: {width} x {height}\n"
- f"大小: {video_size:.2f} MB")
-
- return frame_count, frame_rate, (width, height), video_size
-
-
- def compress_video(input_video, output_video, frame_rate=None, resolution=None, codec='XVID'):
- # 打开视频文件
- cap = cv2.VideoCapture(input_video)
-
- # 获取原始视频信息
- original_frame_rate = cap.get(cv2.CAP_PROP_FPS)
- original_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
- original_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
-
- # 如果没有指定帧率或分辨率,则使用原始视频参数
- if frame_rate is None:
- frame_rate = original_frame_rate
- if resolution is None:
- resolution = (original_width, original_height)
-
- width, height = resolution
-
- # 初始化视频写入器
- fourcc = cv2.VideoWriter_fourcc(*codec)
- out = cv2.VideoWriter(output_video, fourcc, frame_rate, (width, height))
-
- # 压缩视频并保存
- total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
- for _ in tqdm(range(total_frames), desc="Compressing video"):
- ret, frame = cap.read()
- if not ret:
- break
-
- # 调整大小
- resized_frame = cv2.resize(frame, (width, height))
- out.write(resized_frame)
-
- cap.release()
- out.release()
-
- output_size = os.path.getsize(output_video) / (1024 * 1024) # 输出视频文件大小,单位MB
- print(f"压缩后的视频已保存到 {output_video},大小: {output_size:.2f} MB")
-
-
- if __name__ == "__main__":
- # 分析视频
- video_path = "demo.mp4"
- frame_count, frame_rate, resolution, video_size = analyze_video(video_path)
-
- # 询问用户是否需要压缩视频
- compress = input("是否要压缩视频?(y/n): ").strip().lower()
-
- if compress == 'y':
- # 设置压缩参数
- new_frame_rate = float(input(f"设置新帧率 (当前: {frame_rate} FPS, 按Enter跳过): ") or frame_rate)
- width = int(input(f"设置新宽度 (当前: {resolution[0]}, 按Enter跳过): ") or resolution[0])
- height = int(input(f"设置新高度 (当前: {resolution[1]}, 按Enter跳过): ") or resolution[1])
-
- output_video = "compressed_video.mp4"
- compress_video(video_path, output_video, frame_rate=new_frame_rate, resolution=(width, height))
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。