使用 ffmpeg 和 matplotlib 保存动画

Saving animations using ffmpeg and matplotlib

我是这里的新人,也是 python 的新人,我用 matplotliib 的 animation.FuncAnimation 做一些动画。动画效果很好,但我在保存动画时遇到问题。这是动画代码的一部分。

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

fig, ax = plt.subplots()

line,  = ax.plot(range(N),sin(x[0,:]),'o-')
ax.axis([0,1,-1,1])

def animate(i):
    line.set_ydata(sin(x[i,:]))  # update the data
    return line,

def init():
    line.set_ydata(np.ma.array(x[0,:], mask=True))
    return line,

ani = animation.FuncAnimation(fig, animate, np.arange(1, 10000),
    interval=25, init_func=init, blit=True)
ani.save('2osc.mp4', writer="ffmpeg")
plt.show()

其中 x[:,:] 是之前设置的。 ani.save 正在将动画的每一帧保存为 .npg 图像而不是保存电影。我不知道这是否应该是这样工作的,我必须用另一个程序用 .npg 制作电影,或者如果我做错了什么。 Obs:我之前安装过 ffmpeg,它似乎工作得很好。

对我来说,这段代码似乎 运行 没问题:

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

fig, ax = plt.subplots(1,1)
x=np.linspace(np.pi,4*np.pi,100)
N=len(x)
ax.set_xlim(len(x))
ax.set_ylim(-1.5,1.5)
line,  = ax.plot([],[],'o-')

def init():
    line.set_ydata(np.ma.array(x[:], mask=True))
    return line,

def animate(i, *args, **kwargs):
    y=np.sin(x*i)
    line.set_data(np.arange(N),y)            # update the data
    return line,

ani = animation.FuncAnimation(fig, animate, init_func=init, 
     frames=100, interval=10, blit= False, repeat = False)
ani.save('2osc.mp4', writer="ffmpeg")
fig.show()

您可以使用以下方式安装 ffmpeg 库:

sudo apt-get install ffmpeg