iPython Notebook没有嵌入动画

时间:2014-04-09 17:37:27

标签: ipython-notebook

我一直试图将动画嵌入到iPython笔记本中,但没有成功。我在运行10.8.5的Mac上使用最新版本的Enthought Canopy(python 2.7.3),使用Safari作为我的默认浏览器。

经过多次失败的实验,我尝试使用此代码

%pylab inline

from tempfile import NamedTemporaryFile

VIDEO_TAG = """<video controls>
 <source src="data:video/x-m4v;base64,{0}" type="video/mp4">
 Your browser does not support the video tag.
</video>"""

def anim_to_html(anim):
    if not hasattr(anim, '_encoded_video'):
            with NamedTemporaryFile(suffix='.mp4') as f:
            anim.save(f.name, fps=20, extra_args=['-vcodec', 'libx264'])
            video = open(f.name, "rb").read()
        anim._encoded_video = video.encode("base64")

    return VIDEO_TAG.format(anim._encoded_video)

from IPython.display import HTML

def display_animation(anim):
    plt.close(anim._fig)
    return HTML(anim_to_html(anim))  


from matplotlib import animation

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

# initialization function: plot the background of each frame
def init():
    line.set_data([], [])
    return line,

# animation function.  This is called sequentially
def animate(i):
    x = np.linspace(0, 2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=100, interval=20, blit=True)

# call our new function to display the animation
display_animation(anim)

来自网上的杰克范德普拉斯。我安装了ffmpeg。

在运行代码时,我获得视频进度条,但没有图表,只是视频进度条上方的空白区域。

经过几天的努力,我没有找到解决方案(以上是我最接近的解决方案)。任何人都可以看到出现问题或尝试的建议吗?

非常感谢。

1 个答案:

答案 0 :(得分:0)

这个问题在Jessica Hamrick对Jake Vanderplas博客https://jakevdp.github.io/blog/2013/05/12/embedding-matplotlib-animations/

的评论中得到了解决

她在extra_args参数中添加了两个额外的项目:

extra_args = [' - vcodec','libx264',' - pix_fmt','yuv420p']