GIF 动图的分解与合成
- 2019 年 10 月 10 日
- 笔记
GIF 动图的分解可以利用 PIL模块的Image类来实现。下面的自定义函数可以将一张GIF动图分解到指定文件夹:

from PIL import Image import os def gifSplit(gif_path, save_path, suffix="png"): img = Image.open(gif_path) for i in range(img.n_frames): img.seek(i) new = Image.new("RGBA", img.size) new.paste(img) new.save(os.path.join(save_path, "%d.%s" %(i, suffix)))

将上述函数改成下面的生成器,可以将GIF动图迭代输出成numpy数组供OpenCV模块调用。
def gifSplit2Array(gif_path, save_path): import numpy as np img = Image.open(gif_path) for i in range(img.n_frames): img.seek(i) new = Image.new("RGBA", img.size) new.paste(img) arr = np.array(new).astype(np.uint8) # image: img (PIL Image): yield arr[:,:,2::-1] # 逆序(RGB 转BGR), 舍弃alpha通道, 输出数组供openCV使用
import cv2 for img in gifSplit2Array("drop.gif", r"./gif splited"): cv2.imshow("gif", img) cv2.waitKey(40) #加入延迟
撒水成冰:

利用imageio模块很容易就能实现GIF动图的合成:
def create_gif(imagesPath, gif_name, duration=0.3, reverse =False): import imageio fileNames = os.listdir(imagesPath) frames = [] #列表,用于存储各个帧 fileList = os.listdir(imagesPath) if reverse: fileList.sort(reverse=True) for file in fileList: fullpath = os.path.join(imagesPath, file) frames.append(imageio.imread(fullpath))#添加帧数据 imageio.mimsave(gif_name, frames, 'GIF', duration=duration)#合成
上述自定义函数中,将关键字参数reverse 设为True,还可以实现倒序播放:
create_gif(r"./gif splited","merged.gif", duration =0.3, reverse = True)
覆水可收:

上面提到的PIL和 imageio模块都可以用pip在线安装。