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在线安装。
本文分享自 Python可视化编程机器学习OpenCV 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有