如何将动画保存为gif并同时显示?

2024-04-16 13:07:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了一段代码来生成并显示matplotlib动画。我还可以将动画保存为gif格式。在

但是,当我按顺序执行这两个操作时(首先保存gif,然后显示动画,因为plt.show()是一个阻塞调用,所显示的动画并不是从头开始的;它似乎是首先被gif保存例程使用的。在

我的想法是使用plt.show()在窗口中显示动画,并将相同的动画作为gif保存到磁盘(在动画之前,或者理想的是在期间)。我尝试过用线程或者创建新的图形来解决这个问题,但是我没能成功——显示的动画总是被保存例程修改的。另外,将plt.show放入线程中也不起作用(因为它处理屏幕上的绘图,所以它需要在主线程中)。在

下面是我使用的代码:

import matplotlib.pyplot as plt
from matplotlib import animation
from visualizer import visualize
import updater


def run(k, update_func=updater.uniform,
        steps=1000, vis_steps=50,
        alpha_init=0.3, alpha_const=100, alpha_speed=0.95,
        diameter_init=3, diameter_const=1, diameter_speed=1,
        xlim=(-1, 1), ylim=(-1, 1),
        points_style='ro', lines_style='b-',
        save_as_gif=False):

    fig = plt.figure()
    ax = fig.add_subplot(111, xlim=xlim, ylim=ylim)

    global curr_alpha, curr_diameter, points, lines

    points, = ax.plot([], [], points_style)
    lines, = ax.plot([], [], lines_style)

    curr_alpha = alpha_init
    curr_diameter = diameter_init

    def update_attributes(i):
        global curr_alpha, curr_diameter

        if i % alpha_const == 0:
            curr_alpha *= alpha_speed
        if i % diameter_const == 0:
            curr_diameter *= diameter_speed

    def init():
        lines.set_data([], [])
        points.set_data([], [])

    def loop(i):
        for j in range(vis_steps):
            update_func(k, curr_alpha=curr_alpha, curr_diameter=curr_diameter)
            update_attributes(i * vis_steps + j)
        visualize(k, points, lines)
        return points, lines

    anim = animation.FuncAnimation(fig, loop, init_func=init, frames=steps // vis_steps, interval=1, repeat=False)

    if save_as_gif:
        anim.save('gifs/%s.gif' % save_as_gif, writer='imagemagick')

    plt.show()

Tags: importalphainitdefasshowupdate动画