How to make Matplotlib saved gif looping

拜拜、爱过 提交于 2020-02-26 18:27:26

问题


Environment:

  • Matplotlib v2.2.2

Code:

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()

Output: It only play once.


回答1:


Using imagemagick as a writer produces a looping gif, but I can't tell you why that does not work with PillowWriter

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




回答2:


I found a workaround answer here. You can do the following:

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)) 


来源:https://stackoverflow.com/questions/51512141/how-to-make-matplotlib-saved-gif-looping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!