使用python 调用MoviePy制作GIF动图
快过节了,开始准备各种动图做贺卡咯
MoviePy
MoviePy (full documentation) is a Python library for video editing: cutting, concatenations, title insertions, video compositing (a.k.a. non-linear editing), video processing, and creation of custom effects. See the gallery for some examples of use.
Step1: 安装MoviePy
MoviePy depends on the Python modules
Numpy
,imageio
,Decorator
, andtqdm,
which will be automatically installed during MoviePy’s installation
MoviePy基于 Numpy
, imageio
, Decorator
, 和 tqdm,
在安装MoviePy时会同时安装以上库。
使用pip在终端安装
$ pip3 install MoviePy
该方法需提前预装setuptools 或ez_setup,或需根据报错信息更新相关库至需求版本。
$ pip3 install ez_setup
可能遇到的错误及解决
参考另一文章:
ERROR: Cannot uninstall ‘imageio‘. It is a distutils installed project and thus we cannot accurately
Step2: 提取及转换
实现步骤:
- 使用subclip截取视频片段
- 使用resize重新定义剪辑后片段的大小(直接转换出的GIF一般比较大,如CSDN可接受的最大图片仅为5M)
- 写入GIF格式文件
代码:
from c.editor import *
#使用subclip截取视频片段
#使用resize缩放为原来的20%
clip=(VideoFileClip("视频对绝对路径").subclip(0,5).resize(0.2))
#如不需要压缩则:
#clip=(VideoFileClip("视频对绝对路径").subclip(0,5))
#预览截取片段
clip.preview()
#转为gif
clip.write_gif("待保存的gif的绝对路径.gif")
补充-命令说明
1. subclip
subclip(self, t_start=0, t_end=None)
subclip为截取原视频中的自t_start至t_end间的视频片段
t_start and t_end, can be expressed in seconds (15.35), in (min, sec), in (hour, min, sec), or as a string: ‘01:03:05.35’.
参数
t_end
- 未给出,剪辑至视频终止
- 负值,自视频终止向前剪辑t_end片段,eg:
#cut the last two seconds of the clip:
$ newclip = clip.subclip(0,-2)
2.resize
moviepy.video.fx.all.resize(clip, newsize=None, height=None, width=None, apply_to_mask=True)[source]
参数
2.1 newsize
可接受的实参为:
- 以像素或浮点表示的(width,height)
- 缩放百分比,如 0.5
- 可以返回以上两者的函数
示例:
$ myClip.resize( (460,720) )
#以像素或浮点表示的(width,height)
$ myClip.resize(0.6) # 比例缩放 0.6
$ myClip.resize(lambda t : 1+0.02*t) # lambda函数定义剪辑时常
2.2 width
width of the new clip in pixel. The height is then computed so that the width/height ratio is conserved.
给出新剪辑的宽度(以像素为单位)。 自动计算高度,从而持宽高比。示例:
$ myClip.resize(width=800)
2.3 height
height of the new clip in pixel. The width is then computed so that the width/height ratio is conserved.
给出新剪辑的高度(以像素为单位)。 自动计算宽度,从而持宽高比。示例:
$ myClip.resize(width=800) # height computed automatically.
END
参考资料
official doc
user guid
making-animated-gifs-from-video-files-with-python
moviepy-VideoClip-VideoClip.html
上一篇: 删除Mac自带App