通过matplotlib制作动画并保存视频文件

时间:2016-01-18 16:54:19

标签: python animation matplotlib ffmpeg

我一直在研究一维波动方程并制作方程的动画。但使用anim.save animation保存视频文件时存在一些问题。我已经在我的计算机(Windows机器)上安装了ffmpeg并设置了环境变量。但它一直告诉我这个:

UserWarning: MovieWriter ffmpeg unavailable
...
RuntimeError: Error creating movie, return code: 4 Try running with --verbose-debug

enter image description here

这是我的代码:

from numpy import zeros,linspace,sin,pi
import matplotlib.pyplot as mpl
from matplotlib import animation
mpl.rcParams['animation.ffmpeg_path'] = 'C:\\ffmpeg\\bin\\ffmpeg.exe'

def I(x):
    return sin(2*x*pi/L)

def f(x,t):
    return sin(0.5*x*t)

def solver0(I,f,c,L,n,dt,t):
    # f is a function of x and t, I is a function of x
    x = linspace(0,L,n+1)
    dx = L/float(n)
    if dt <= 0:
        dt = dx/float(c)
    C2 = (c*dt/dx)**2
    dt2 = dt*dt
    up = zeros(n+1)
    u = up.copy()
    um = up.copy()
    for i in range(0,n):
        u[i] = I(x[i])
    for i in range(1,n-1):
        um[i] = u[i]+0.5*C2*(u[i-1] - 2*u[i] + u[i+1]) + dt2*f(x[i],t)
    um[0] = 0
    um[n] = 0    
    while t <= tstop:
        t_old = t
        t += dt
        #update all inner points:
        for i in range(1,n-1):
            up[i] = -um[i] + 2*u[i] + C2*(u[i-1] - 2*u[i] + u[i+1]) + dt2*f(x[i],t_old)    
        #insert boundary conditions:
        up[0] = 0
        up[n] = 0
        #update data structures for next step
        um = u.copy()
        u = up.copy()   
    return u

c = 1.0 
L = 10
n = 100
dt = 0
tstop = 40

fig = mpl.figure()
ax = mpl.axes(xlim=(0,10),ylim=(-1.0,1.0))
line, = ax.plot([],[],lw=2)

def init():
    line.set_data([],[])
    return line,

def animate(t):
    x = linspace(0,L,n+1)
    y = solver0(I, f, c, L, n, dt, t)
    line.set_data(x,y)
    return line,

anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=200, interval=20, blit=True)

anim.save('seawave_1d_ani.mp4',writer='ffmpeg',fps=30)
mpl.show()

我认为问题出在动画部分,而不是上面的三个功能。请帮我找出我犯的错误。

1 个答案:

答案 0 :(得分:1)

我终于解决了。似乎我错过了两条重要的路线。 RectangleAnnotation这一行是正确的。据我所知,'\\'和'/'在Windows中都有效。 我在底部添加mpl.rcParams['animation.ffmpeg_path'] = 'C:\\ffmpeg\\bin\\ffmpeg.exe'并按mywriter = animation.FFMpegWriter()修改anim.save('seawave_1d_ani.mp4',writer='ffmpeg',fps=30)。最后,感谢Using FFmpeg and IPython。 也感谢那些帮助我解决这个问题的朋友。