1. 程式人生 > >python製作gif 以及從gif中獲得圖片

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中獲取圖片:

程式碼:

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)

生成的圖片:

實際生成的圖片質量不高