如何使Matplotlib保存的gif动画循环播放

12

环境:

  • Matplotlib v2.2.2

代码:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.animation import PillowWriter

fig = plt.figure()

def f(x, y):
    return np.sin(x) + np.cos(y)

x = np.linspace(0, 2 * np.pi, 120)
y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1)
# ims is a list of lists, each row is a list of artists to draw in the
# current frame; here we are just animating one artist, the image, in
# each frame
ims = []
for i in range(20):
    x += np.pi / 15.
    y += np.pi / 20.
    im = plt.imshow(f(x, y))
    ims.append([im])

ani = animation.ArtistAnimation(fig, ims, interval=50, blit=True,
                                repeat_delay=500)

writer = PillowWriter(fps=20)
ani.save("demo2.gif", writer=writer)

plt.show()
输出: 它只会播放一次。

输入图像描述


这似乎取决于图像查看器。运行您的代码,我得到一个循环动画,但在网页上包含它会导致非循环图像。不确定原因,但可能与matplotlib无关。 - ImportanceOfBeingErnest
@ImportanceOfBeingErnest 你用哪个图片查看器?我用的是EyeOfGnome,但它不能播放循环。 - Honghe.Wu
2
另一种选择是使用外部编辑器修改gif并将其设置为循环播放。请参阅SU上的此问题https://superuser.com/questions/159212/how-do-i-make-an-existing-animated-gif-loop-repeatedly - Diziet Asahi
我正在使用IrfanView,其中这个循环是自动的。 - ImportanceOfBeingErnest
2个回答

11

使用 imagemagick 作为写入器可以生成循环 GIF,但我无法告诉你为什么在使用 PillowWriter 时这样做不起作用。

ani.save("demo2.gif", writer='imagemagick')

这里输入图像描述


1
我发现一个解决方法,在这里。你可以按照以下步骤操作:
from matplotlib.animation import PillowWriter    

class LoopingPillowWriter(PillowWriter):
    def finish(self):
        self._frames[0].save(
            self._outfile, save_all=True, append_images=self._frames[1:],
            duration=int(1000 / self.fps), loop=0)

ani = animation.ArtistAnimation(fig, ims, interval=50, blit=True,
                            repeat_delay=500)
ani.save('demo2.gif', writer=LoopingPillowWriter(fps=20)) 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接