日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python实现gif动画(matplotlib、imageio、pillow))

發布時間:2025/1/21 python 89 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python实现gif动画(matplotlib、imageio、pillow)) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

點擊上方“AI搞事情”關注我們


GIF(Graphics Interchange Format,圖形交換格式)是一種位圖圖像格式。

GIF格式的圖像文件具有如下特點:

  • GIF格式圖像文件的擴展名是“.gif”。

  • 對于灰度圖像表現最佳。

  • 具有GIF87a和GIF89a兩個版本。

  • 采用改進的LZW壓縮算法處理圖像數據。

  • 調色板數據有通用調色板和局部調色板之分,有不同的顏色取值。

  • 不支持24bit彩色模式,最多存儲256色。

  • 1. matplotlib

    matplotlib 中的 animation 模塊繪制動態圖,繪制心形動態函數

    • 安裝matplotlib

    pip install matplotlib import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation fig, ax = plt.subplots() # fig.patch.set_alpha(0.) # 設置透明背景,但animation不起作用 plt.axis('off') # 關閉坐標軸 #初始化窗口和坐標軸 xdata, ydata = [], [] #初始化x,y列表 ln, = ax.plot([], [], 'r-', animated=False) #初始化繪制曲線的參數。 #init()函數初始化x,y軸范圍 def init():ax.set_xlim(-20,20)ax.set_ylim(-20,15)return ln, #迭代器,根據傳入的frame更新x,y值 def update(frame):# 心形函數x = 16 * np.sin(frame) ** 3y = 13 * np.cos(frame) - 5 * np.cos(2 * frame) - 2 * np.cos(3 * frame) - np.cos(4 * frame)xdata.append(x)ydata.append(y)ln.set_data(xdata, ydata)return ln, # interval:幀持續時間(milliseconds) anim = animation.FuncAnimation(fig, update, frames=np.linspace(0, 10, 100), init_func=init, interval=1, repeat=False, blit=True) anim.save('tmp.gif', writer='pillow') plt.show()

    動態圖無法繪制透明背景。

    2. imageio

    pip install imageio

    https://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 pillow

    GitHub: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))的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。