无法使用ffmpeg保存Matplotlib动画

时间:2017-12-23 13:21:01

标签: python animation matplotlib ffmpeg

我已经安装了ffmpeg并将其添加到路径,并检查它在命令提示符下工作,但我仍然无法保存动画。我尝试创建一个在我不尝试保存它时会产生动画的浪潮,但在我进行演示时会抛出错误;

from __future__ import division

import numpy as numpy
from matplotlib import pyplot as pyplot
from matplotlib import animation

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

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

def animate(i):
    x = numpy.linspace(0, 2, 1000)
    y = numpy.sin(2 * numpy.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

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

FFwriter = animation.FFMpegWriter()
anim.save('animation_testing.mp4', writer = FFwriter)

pyplot.show()

当我尝试运行它时,它反复抛出相同的错误,我假设它遍历每个帧;

Traceback (most recent call last):
  File "c:\users\james\appdata\local\enthought\canopy\user\lib\site-
packages\matplotlib\backends\backend_wx.py", line 212, in _on_timer
    TimerBase._on_timer(self)
  File "c:\users\james\appdata\local\enthought\canopy\user\lib\site-
packages\matplotlib\backend_bases.py", line 1273, in _on_timer
    ret = func(*args, **kwargs)
  File "c:\users\james\appdata\local\enthought\canopy\user\lib\site-
packages\matplotlib\animation.py", line 910, in _step
    still_going = Animation._step(self, *args)
  File "c:\users\james\appdata\local\enthought\canopy\user\lib\site-
packages\matplotlib\animation.py", line 769, in _step
    self._draw_next_frame(framedata, self._blit)
  File "c:\users\james\appdata\local\enthought\canopy\user\lib\site-
packages\matplotlib\animation.py", line 787, in _draw_next_frame
    self._pre_draw(framedata, blit)
  File "c:\users\james\appdata\local\enthought\canopy\user\lib\site-
packages\matplotlib\animation.py", line 800, in _pre_draw
    self._blit_clear(self._drawn_artists, self._blit_cache)
  File "c:\users\james\appdata\local\enthought\canopy\user\lib\site-
packages\matplotlib\animation.py", line 840, in _blit_clear
    a.figure.canvas.restore_region(bg_cache[a])
KeyError: <matplotlib.axes._subplots.AxesSubplot object at 0x0000000009C04DD8>

由于它在_blit_clear中提到错误,我尝试在FuncAnimation中将blit更改为False,但是当我没有尝试保存时,它不会在pyplot.show()中设置动画。

我不确定错误的位置,因此无法解决问题。

我使用的是Windows 10,python 2.7.6和matplotlib 1.4.2版

非常感谢!

1 个答案:

答案 0 :(得分:0)

添加;

pyplot.switch_backend('backend')

后端是TkAgg或Qt4Agg解决了我的问题。

感谢ImportanceOfBeingErnest为我解决这个问题!