FFmpeg
是操作视频的开源工具,本文记录Python
操作FFmpeg
进行视频压缩的方法。
简介
-
FFmpeg
是一个完整的,跨平台的解决方案,记录,转换和流音频和视频。 - 官网:https://ffmpeg.org/
下载安装
下载链接:https://ffmpeg.org/download.html#build-linux
Ubuntu 可以使用 apt 安装:
1 | sudo apt install ffmpeg |
---|
Windows 可以下载安装包,需要配置环境变量
视频压缩
下面是ffmpeg压缩视频的命令:
将视频压缩指定大小
1 | ffmpeg -i Desktop/input.mp4 -fs 10MB Desktop/output.mp4 |
---|
-fs 10
: 表示文件大小最大值为 10MB
设置视频的帧率为20fps
1 | ffmpeg -i Desktop/input.mp4 -r 20 Desktop/output.mp4 |
---|
-r 20
:表示帧率设置为 20fps
设置视频的码率
1 | ffmpeg -i Desktop/input.mp4 -b:v 1M Desktop/output.mp4 |
---|
-b:v
: 指定视频的码率
-b:a
: 指定音频的码率
1M
:码率的值 1M 表示 1Mb/s
设置视频的分辨率
1 | ffmpeg -i Desktop/input.mp4 -s 1920x1080 Desktop/output.mp4 |
---|
-s
: 1920x1080表示分辨率为1920x1080
可以结合上面的命令一起来使用
1 | ffmpeg -i Desktop/input.mp4 -s 1920x1080 -b:v 1M -r 20 Desktop/output.mp4 |
---|
Python 调用
- 在 Python 中可以用
os
命令调用ffmpeg
- 示例批量压缩的 Python 代码:
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 | import sysimport osimport mtutils as mtimport cv2 class Compress_Pic_or_Video(object): def __init__(self): pass def is_video(self, file_path): videoSuffixSet = {"WMV","ASF","ASX","RM","RMVB","MP4","3GP","MOV","M4V","AVI","DAT","MKV","FIV","VOB"} suffix = mt.get_suffix(file_path).upper() if suffix in videoSuffixSet: return True else: return False def infer_video_file(self, file_path, delete_origin_file=False): if not self.is_video(file_path): return else: width, height = self.get_target_size(file_path) self.SaveVideo(file_path, width, height, delete_origin_file) def get_target_size(self, file_path): cap = cv2.VideoCapture(file_path) cap.set(1, 1) # 取它的第一帧 rval, frame = cap.read() # 如果rval为False表示这个视频有问题,为True则正常 cap.release() height = frame.shape[0] # 高度 width = frame.shape[1] # 宽度 max_size = 960 factor = min(1, max_size / max(height, width)) width = int(width * factor) height = int(height * factor) return width, height def SaveVideo(self, file_path, width, height, delete_origin_file=False): fpsize = os.path.getsize(file_path) / 1024 dir_path= mt.OS_dirname(file_path) stem = mt.get_path_stem(file_path) output_path = mt.OS_join(dir_path, stem '_compress.mp4') if fpsize >= 150.0: # 大于150KB的视频需要压缩 compress = "ffmpeg -i {} -r 12 -s {}x{} -b:v 200k {}".format(file_path, width, height, output_path) isRun = os.system(compress) if isRun != 0: return (isRun,"没有安装ffmpeg") else: if delete_origin_file: mt.remove_file(file_path) return True else: return True if __name__ == "__main__": b = sys.argv try: dir_path = b[1] except: dir_path = '.' comp_obj = Compress_Pic_or_Video() dir_path_list, file_path_list = mt.get_dir_file_list(dir_path, True) for file_path in mt.tqdm(file_path_list): if '_compress.mp4' not in file_path: comp_obj.infer_video_file(file_path) |
---|
参考资料
- https://ffmpeg.org/
- https://zhuanlan.zhihu.com/p/383974036