脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|shell|

服务器之家 - 脚本之家 - Python - Python播放GIF图片(ChatGPT代码参考)

Python播放GIF图片(ChatGPT代码参考)

2023-06-26 16:45瀚瀚 Python

在网上找了好几个方法, 最后还是出现各种问题,解决不了播放GIF的功能。 最后,通过ChatGPT给出了简单明了的方案(使用第三方库imageio和matplotlib.animation来实现),调试直接通过。 但有小瑕疵,就是显示gif时隐藏掉坐标轴的功能

在网上找了好几个方法, 最后还是出现各种问题,解决不了播放GIF的功能。

最后,通过ChatGPT给出了简单明了的方案(使用第三方库imageiomatplotlib.animation来实现),调试直接通过。

但有小瑕疵,就是显示gif时隐藏掉坐标轴的功能无效,于是再做了一下优化。

Python播放GIF图片(ChatGPT代码参考)

 

[最终代码]

显示GIF动画:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import imageio

import numpy as np
import os

# -------------display gif---------------
def display_gif_file(): 

    # 加载GIF文件
    gif_path = "mygif.gif"
    gif = imageio.mimread(gif_path)

    # 创建图形窗口
    fig = plt.figure()
    
    # 定义更新函数,用于更新图像
    def update(frame):
        plt.clf()  # 清空图形窗口
        plt.imshow(frame)  # 显示当前帧
        plt.axis('off') # 隐藏x轴和y轴

    """ #方法二#
    # 创建图形窗口和子图
    fig, ax = plt.subplots()
    
    # 定义更新函数,用于更新图像
    def update(frame):
        ax.clear()  # 清空子图
        ax.imshow(frame)  # 显示当前帧
        ax.set_axis_off() # 隐藏x轴和y轴
    """ 

    # 创建动画
    ani = animation.FuncAnimation(fig, update, frames=gif, interval=60)

    # 显示动画
    plt.show()

 

GIF图片生成方法:

# -------------generate gif-----------------
def generate_gif_file():

    y = np.random.randint(30,90, size=(20))

    filenames = []
    num = 0
    for i in y:
        num += 1
        # 绘制n张折线图
        plt.plot(y[:num])
        plt.ylim(10, 300)
        # 保存图片文件
        filename = f'{num}.png'
        filenames.append(filename)
        plt.savefig(filename)
        plt.close()
        print("save:"+filename)
    # 生成gif
    finalImgName =r'mygif.gif' 
    with imageio.get_writer(finalImgName, mode='I') as writer:
        for filename in filenames:
            image = imageio.imread(filename)
            writer.append_data(image)
            print(filename)
            
    # 删除n张折线图
    for filename in set(filenames):
        os.remove(filename)

    print("gif done.")

 

GIF效果演示:

Python播放GIF图片(ChatGPT代码参考)

 原文地址:https://www.cnblogs.com/gaoxihan/p/17499434.html

延伸 · 阅读

精彩推荐