使用python 调用MoviePy制作GIF动图

本文介绍了如何使用Python的MoviePy库来编辑视频并创建GIF动图。首先,通过pip安装MoviePy及其依赖库。然后,详细阐述了如何截取视频片段(subclip)和调整大小(resize)。在截取片段时,可以指定开始和结束时间,而resize允许设置新尺寸或比例,保持原视频的宽高比。最后,提供了将处理后的视频保存为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, and tqdm, 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: 提取及转换

实现步骤:

  1. 使用subclip截取视频片段
  2. 使用resize重新定义剪辑后片段的大小(直接转换出的GIF一般比较大,如CSDN可接受的最大图片仅为5M)
  3. 写入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

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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值