python制作gif 以及从gif中获得图片

先介绍python制作gif:

在用遗传算法的时候,想把种群进化过程中的接的分布动态的展示出来,所以就想到了制作gif,展示的时候直接贴到PPT里面就行,在网上找到一个gif在线制作的网站,不过那个网站体验极差,居然不能调整用于生成gif的图片顺序,之后突然想到之前看过一篇微信公众号文章介绍过python可以制作gif, 搜了一下果然找到多:

制作gif的图片是在matlab仿真程序中生成保存的:

gif转换代码:

import imageio, os
images = []
base_path = r'C:\Users\18811\Desktop\graph'
path = os.listdir(base_path)    # 读取文件夹下的图片
filenames = sorted(path, key=lambda x: int(x.split('.')[0]))   # 对文件按照文件名进行排序
print(filenames)
for filename in filenames:
    images.append(imageio.imread(os.path.join(base_path, filename)))
imageio.mimsave(os.path.join(base_path, 'res.gif'), images, duration=1)  # duration设置gif的间隔时间

生成的gif:

看起来效果还可以哦

-------------------------------------------------------分割线------------------------------------------------------

从gif中获取图片:

代码:

扫描二维码关注公众号,回复: 4903113 查看本文章
from PIL import Image
import sys
import os


def image_process(gif_path, save_path):
    try:
        im = Image.open(gif_path)
    except IOError:
        print("Load gif failed")
        sys.exit(1)
    cnt = 1
    mypalette = im.getpalette()   # 调色板

    try:
        while True:
            im.putpalette(mypalette)
            new_image = Image.new('RGBA', im.size)
            new_image.paste(im)
            new_image.save(os.path.join(save_path, str(cnt)+'.png'))
            cnt = cnt + 1
            im.seek(im.tell() + 1)
    except EOFError:
        pass


gif = r'C:\Users\18811\Desktop\graph\res.gif'
save = r'C:\Users\18811\Desktop\graph\12'
image_process(gif, save)

生成的图片:

实际生成的图片质量不高

猜你喜欢

转载自blog.csdn.net/zj1131190425/article/details/85231101