python实现gif动画(matplotlib、imageio、pillow))
點擊上方“AI搞事情”關注我們
GIF(Graphics Interchange Format,圖形交換格式)是一種位圖圖像格式。
GIF格式的圖像文件具有如下特點:
GIF格式圖像文件的擴展名是“.gif”。
對于灰度圖像表現最佳。
具有GIF87a和GIF89a兩個版本。
采用改進的LZW壓縮算法處理圖像數據。
調色板數據有通用調色板和局部調色板之分,有不同的顏色取值。
不支持24bit彩色模式,最多存儲256色。
1. matplotlib
matplotlib 中的 animation 模塊繪制動態圖,繪制心形動態函數
安裝matplotlib
動態圖無法繪制透明背景。
2. imageio
pip install imageiohttps://blog.csdn.net/guduruyu/article/details/77540445
# -*- coding: UTF-8 -*- import imageio def create_gif(image_list, gif_name):frames = []for image_name in image_list:frames.append(imageio.imread(image_name))# Save them as frames into a gifimageio.mimsave(gif_name, frames, 'GIF', duration=0.01) # duration:秒returndef main():png_path = 'images'png_files = os.listdir(png_path)image_list =[png_path + "/%03d.png" % frame_id for frame_id in range(len(png_files))]gif_name = 'created_gif.gif'create_gif(image_list, gif_name)if __name__ == '__main__':main()imageio庫有個弊端是好像不能將透明背景的png圖像生成透明背景的gif圖像
3. pillow
pip install pillowGitHub:https://github.com/python-pillow/Pillow
官方文檔:
https://pillow.readthedocs.io/en/latest/handbook/image-file-formats.html#gif
參數說明pillow可以通過設置transparency參數,使GIF背景為透明的。
import os import random from PIL import Image, ImageDraw, ImageSequence def gif2pngs(gif_path, png_path):"""gif圖像拆成若干png幀圖"""img = Image.open(gif_path)for ind, frame in enumerate(ImageSequence.all_frames(img)):# 保存每一幀圖像frame.save(os.path.join(png_path, "%03d.png" % ind)) def pngs2gif(png_path, gif_name):"""png幀圖生成gif圖像"""frames = []png_files = os.listdir(png_path)for frame_id in range(len(png_files)):frame = Image.open(os.path.join(png_path, "%03d.png" % frame_id))frames.append(frame)# frames.reverse() # 將圖像序列逆轉frames[0].save(gif_name, save_all=True, append_images=frames[1:], loop=0, disposal=2) def draw_gif(gif_name):"""通過PIL繪制動態圖"""size = 50i = 0colors = ['red', 'blue', 'green', 'gray']# 繪制隨機閃現的球frames = []while i < 100:img = Image.new("RGBA", (800, 800), color=(0, 0, 0))draw = ImageDraw.Draw(img)x = random.randint(-800, 800)y = random.randint(-800, 800)if x-size < 0 or x-size > img.size[0]:continueif y-size < 0 or y-size > img.size[1]:continuedraw.ellipse((x, y, x + size, y + size), fill=colors[random.randint(0, 3)])frames.append(img)i += 1# transparency 透明背景設置,duration單位 毫秒, loop=0無限循環 loop=1循環一次,不設置,不循環frames[0].save(gif_name, save_all=True, append_images=frames[1:], transparency=0, duration=100, loop=0, disposal=2) if __name__ == '__main__':gif2pngs('下班了.gif', 'images')pngs2gif('images', 'tmp.gif')draw_gif('ball.gif') 圖片gif2pngs('下班了.gif', 'images')函數執行后會在images保存幀圖像
圖片圖片長按二維碼關注我們
有趣的靈魂在等你
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的python实现gif动画(matplotlib、imageio、pillow))的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【python自动化办公02】word操
- 下一篇: 【python自动化办公03】word操