每次压缩视频文件时,都要在网上苦苦寻找“免费软件”,但结果往往不尽如人意:要么功能受限、隐藏收费,要么对电脑配置要求过高,使用起来非常不便。
最近我尝试结合 AI 工具,编写了一个轻量级的视频压缩脚本,完美满足我的日常需求。特此记录分享,方便自己也帮助他人。
为什么写这个脚本?
- 小巧实用 :不需要安装大型软件,依赖标准库 + OpenCV 就可运行。
- 自动适配比例 :支持按指定分辨率(如 960x1280)进行中心裁剪 + 缩放,保留主体画面。
- 批量处理多个视频 :自动读取指定目录下的所有视频文件并逐一处理。
- 跨平台兼容性好 :支持 Windows、Mac 和 Linux 系统。
实现思路
整个脚本分为三个主要部分:
- 获取输入目录中的视频文件列表
- 逐帧读取并处理每一帧图像
- 将处理后的帧重新封装为视频输出
技术亮点:
- 使用
cv2
进行视频读写操作; - 使用
os
模块进行路径管理和文件筛选; - 使用
tqdm
显示进度条,提升用户体验; - 支持多种主流格式(如
.mp4
,.avi
,.mov
,.mkv
)。
✅ 完整代码如下:
import os
import cv2
from tqdm import tqdm
def get_video_files(input_dir):
""" 获取指定目录中所有支持格式的视频文件 """
video_extensions = ['.mp4', '.avi', '.mov', '.mkv']
return [f for f in os.listdir(input_dir)
if os.path.splitext(f)[1].lower() in video_extensions]
def process_video(input_path, output_path):
""" 处理单个视频文件:中心裁剪并缩放到目标尺寸 """
cap = cv2.VideoCapture(input_path)
if not cap.isOpened():
print(f" 无法打开视频文件: {input_path}")
return False
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = cap.get(cv2.CAP_PROP_FPS)
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
# 目标尺寸:960x1280(3:4 比例,适合竖屏)target_width, target_height = 960, 1280
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter(output_path, fourcc, fps, (target_width, target_height))
for _ in tqdm(range(frame_count), desc=f" 处理 {os.path.basename(input_path)}"):
ret, frame = cap.read()
if not ret:
break
orig_ratio = width / height
target_ratio = target_width / target_height
# 根据原始比例计算裁剪区域
if orig_ratio > target_ratio:
crop_width = int(height * target_ratio)
crop_height = height
x = (width - crop_width) // 2
y = 0
else:
crop_width = width
crop_height = int(width / target_ratio)
x = 0
y = (height - crop_height) // 2
# 裁剪并缩放
cropped = frame[y:y+crop_height, x:x+crop_width]
resized = cv2.resize(cropped, (target_width, target_height))
out.write(resized)
cap.release()
out.release()
return True
def main():
input_dir = "video"
output_dir = "video_output"
os.makedirs(output_dir, exist_ok=True)
video_files = get_video_files(input_dir)
if not video_files:
print(f" 在目录 {input_dir} 中未找到支持的视频文件 ")
return
print(f" 共找到 {len(video_files)} 个视频文件 ")
for video_file in video_files:
input_path = os.path.join(input_dir, video_file)
filename, ext = os.path.splitext(video_file)
output_path = os.path.join(output_dir, f"{filename}_resized{ext}")
print(f"\n 开始处理: {video_file}")
success = process_video(input_path, output_path)
if success:
print(f" 处理完成,已保存至: {output_path}")
else:
print(f" 处理失败: {video_file}")
if __name__ == "__main__":
main()
📦 使用说明
1. 准备工作:
- 安装依赖库(如尚未安装):
pip install opencv-python tqdm
2. 文件结构:
project/
├── video/ ← 存放待压缩的视频文件
│ ├── example1.mp4
│ └── example2.mov
├── script.py ← 上面的脚本
└── video_output/ ← 处理完成后自动生成的输出目录
3. 自定义修改:
- 如果需要其他分辨率(如 720x1280 或 1080x1920),只需修改
target_width
和target_height
即可。 - 支持扩展更多视频格式,在
get_video_files()
中添加即可。
这个脚本虽然简单,但非常适合小规模视频压缩的需求。对于不想安装复杂软件或受限于网速的朋友来说,是一个非常不错的替代方案。
比起动辄几十 MB 的压缩软件,Python 脚本更灵活、透明、可控。
如你有进一步需求,比如增加 GUI 界面、可视化参数设置、多线程加速等,也可以基于此类脚本进行拓展。
感兴趣的朋友欢迎留言交流,或者一起优化改进这个小工具!
正文完