使用ffpmeg命令合成视频的介绍比较多,但是可调节性比较有限,ffmpeg-python本质上是在python中形成ffmpeg命令,然后执行命令来达到设计的效果,注意安装ffmpeg-python包不是python-ffmpeg,尽管python-ffmpeg比较新。
本篇介绍几种合成的方法,均合成为mp4,先定义几个合成时都用到的常量。
# coding=utf-8
import ffmpeg
VIDEO_FRAMERATE = 30
VIDEO_P = 'hd720'
VIDEO_FORMAT = 'mp4'
首先看看一张图片生成mp4,通过ffmpeg.input输入,ffmpeg.filter是滤镜,目前是缩放到720p,通过ffmpeg.output输出到mp4.mp4
def image2mp4():
v_in = ffmpeg.input('./image/a1.jpg', t=10, framerate=30, loop=1)
# 缩放到720p,force_original_aspect_ratio=increase图片扩大/decrease图片缩小
v_s = ffmpeg.filter(v_in,filter_name='scale', size=VIDEO_P, force_original_aspect_ratio='increase')
#v_s = ffmpeg.filter(v_in,filter_name='scale', size=VIDEO_P)
try:
out, err = (ffmpeg
.output(
v_s,
'mp4.mp4',
vcodec='libx264',
acodec='aac',
f='mp4')
.run(cmd=["ffmpeg"])
)
except ffmpeg.Error as error:
print("stderr:",error.stderr)
如果image文件夹中有多张图片,可以用如下方法得到每秒1帧切换一次的视频:
def images_2_mp4():
inv = ffmpeg.input('./image/*.jpg', pattern_type='glob', framerate=1, thread_queue_size=1)
v_s = ffmpeg.filter(inv,filter_name='scale', size=VIDEO_P)
try:
out, err = (ffmpeg
.output(
inv,
'mp4.mp4',
vcodec='libx264',
acodec='aac',
r=VIDEO_FRAMERATE,
f=VIDEO_FORMAT)
.run(cmd=["ffmpeg"])
)
except ffmpeg.Error as error:
print("stderr:",error.stderr)
如果有image的list,可以这样:
def image_list_2_mp4():
v_in_arr = []
for fn in img_files:
inv = ffmpeg.input(fn, t=2, framerate=VIDEO_FRAMERATE, loop=1)
v_s = ffmpeg.filter(inv,filter_name='scale', size=VIDEO_P)
v_in_arr.append(v_s)
video_in = ffmpeg.concat(*v_in_arr, v=1,a=0)
try:
out, err = (ffmpeg
.output(
video_in,
'mp4.mp4',
vcodec='libx264',
acodec='aac',
r=VIDEO_FRAMERATE,
f=VIDEO_FORMAT)
.run(cmd=["ffmpeg"])
)
except ffmpeg.Error as error:
print("stderr:",error.stderr)
下篇把音频加上