使用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