web-dev-qa-db-ja.com

Matplotlibに保存されたgifループを作成する方法

環境:

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

出力:1回だけ再生されます。

enter image description here

7
Honghe.Wu

回避策の回答 こちら を見つけました。次のことができます。

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)) 
1
Daniel Wyatt