Python Jupyter 中的内联动画

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43445103/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:05:00  来源:igfitidea点击:

Inline animations in Jupyter

pythonanimationmatplotlibjupyter-notebookipython-notebook

提问by Ari Herman

I have a python animation script (using matplotlib's funcAnimation), which runs in Spyder but not in Jupyter. I have tried following various suggestions such as adding "%matplotlib inline" and changing the matplotlib backend to "Qt4agg", all without success. I have also tried running several example animations (from Jupyter tutorials), none of which have worked. Sometimes I get an error message and sometimes the plot appears, but does not animate. Incidentally, I havegotten pyplot.plot() to work using "%matplotlib inline".

我有一个 python 动画脚本(使用 matplotlib 的 funcAnimation),它在 Spyder 中运行但不在 Jupyter 中运行。我尝试遵循各种建议,例如添加“%matplotlib inline”并将matplotlib后端更改为“Qt4agg”,但都没有成功。我还尝试运行几个示例动画(来自 Jupyter 教程),但都没有奏效。有时我会收到一条错误消息,有时会出现情节,但没有动画。顺便说一句,我已经让pyplot.plot() 使用 "%matplotlib inline" 工作。

Does anyone know of a working Jupyter notebook with a SIMPLE inline animation example that uses funcAnimation. Thanks in advance for the help!

有谁知道有一个使用 funcAnimation 的简单内联动画示例的工作 Jupyter 笔记本。在此先感谢您的帮助!

[Note: I am on Windows 7]

[注意:我使用的是 Windows 7]

回答by ImportanceOfBeingErnest

notebook backend

笔记本后端

'Inline' means that the plots are shown as png graphics. Those png images cannot be animated. While in principle one could build an animation by successively replacing the png images, this is probably undesired.

“内联”意味着绘图显示为 png 图形。那些 png 图像不能被动画化。虽然原则上可以通过连续替换 png 图像来构建动画,但这可能是不受欢迎的。

A solution is to use the notebook backend, which is fully compatible with FuncAnimationas it renders the matplotlib figure itself:

一个解决方案是使用 notebook 后端,它与FuncAnimation渲染 matplotlib 图形本身完全兼容:

%matplotlib notebook

jsanimation

动画

From matplotlib 2.1 on, we can create an animation using JavaScript. This is similar to the ani.to_html5()solution, except that it does not require any video codecs.

从 matplotlib 2.1 开始,我们可以使用 JavaScript 创建动画。这与ani.to_html5()解决方案类似,不同之处在于它不需要任何视频编解码器。

from IPython.display import HTML
HTML(ani.to_jshtml())

Some complete example:

一些完整的例子:

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

t = np.linspace(0,2*np.pi)
x = np.sin(t)

fig, ax = plt.subplots()
ax.axis([0,2*np.pi,-1,1])
l, = ax.plot([],[])

def animate(i):
    l.set_data(t[:i], x[:i])

ani = matplotlib.animation.FuncAnimation(fig, animate, frames=len(t))

from IPython.display import HTML
HTML(ani.to_jshtml())

Alternatively, make the jsanimation the default for showing animations,

或者,将 jsanimation 设为显示动画的默认值,

plt.rcParams["animation.html"] = "jshtml"

Then at the end simply state anito obtain the animation.

然后在最后简单地声明ani获取动画。

Also see this answerfor a complete overview.

另请参阅此答案以获取完整概述。

回答by Biggsy

There is a simple example within this tutorial here: http://louistiao.me/posts/notebooks/embedding-matplotlib-animations-in-jupyter-notebooks/

本教程中有一个简单的例子:http: //louistiao.me/posts/notebooks/embedding-matplotlib-animations-in-jupyter-notebooks/

To summarise the tutorial above, you basically need something like this:

总结上面的教程,你基本上需要这样的东西:

from matplotlib import animation
from IPython.display import HTML

# <insert animation setup code here>

anim = animation.FuncAnimation()  # With arguments of course!
HTML(anim.to_html5_video())

However...

然而...

I had a lot of trouble getting that to work. Essentially, the problem was that the above uses (by default) ffmpegand the x264codec in the background but these were not configured correctly on my machine. The solution was to uninstall them and rebuild them from source with the correct configuration. For more details, see the question I asked about it with a working answer from Andrew Heusser: Animations in ipython (jupyter) notebook - ValueError: I/O operation on closed file

我在让它工作时遇到了很多麻烦。本质上,问题在于上述使用(默认情况下)ffmpegx264后台的编解码器,但这些在我的机器上没有正确配置。解决方案是卸载它们并使用正确的配置从源代码重建它们。有关更多详细信息,请参阅我通过 Andrew Heusser 的有效回答提出的问题:ipython (jupyter) notebook 中的动画 - ValueError: I/O operation on closed file

So, try the to_html5_videosolution above first, and if it doesn't work then also try the uninstall / rebuild of ffmpegand x264.

所以,首先尝试to_html5_video上面的解决方案,如果它不起作用,那么也尝试卸载/重建ffmpegx264

回答by MosGeo

Here is the answer that I put together from multiple sources including the official examples. I tested with the latest versions of Jupyter and Python.

这是我从多个来源(包括官方示例)汇总的答案。我使用最新版本的 Jupyter 和 Python 进行了测试。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from IPython.display import HTML

#=========================================
# Create Fake Images using Numpy 
# You don't need this in your code as you have your own imageList.
# This is used as an example.

imageList = []
x = np.linspace(0, 2 * np.pi, 120)
y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1)
for i in range(60):
    x += np.pi / 15.
    y += np.pi / 20.
    imageList.append(np.sin(x) + np.cos(y))

#=========================================
# Animate Fake Images (in Jupyter)

def getImageFromList(x):
    return imageList[x]

fig = plt.figure(figsize=(10, 10))
ims = []
for i in range(len(imageList)):
    im = plt.imshow(getImageFromList(i), animated=True)
    ims.append([im])

ani = animation.ArtistAnimation(fig, ims, interval=50, blit=True, repeat_delay=1000)
plt.close()

# Show the animation
HTML(ani.to_html5_video())

#=========================================
# Save animation as video (if required)
# ani.save('dynamic_images.mp4')

回答by duhaime

If you have a list of images and want to animate through them, you can use something like this:

如果您有一个图像列表并希望通过它们制作动画,您可以使用以下内容:

from keras.preprocessing.image import load_img, img_to_array
from matplotlib import animation
from IPython.display import HTML
import glob

%matplotlib inline

def plot_images(img_list):
  def init():
    img.set_data(img_list[0])
    return (img,)

  def animate(i):
    img.set_data(img_list[i])
    return (img,)

  fig = figure()
  ax = fig.gca()
  img = ax.imshow(img_list[0])
  anim = animation.FuncAnimation(fig, animate, init_func=init,
                                 frames=len(img_list), interval=20, blit=True)
  return anim

imgs = [img_to_array(load_img(i)) for i in glob.glob('*.jpg')]

HTML(plot_images(imgs).to_html5_video())