简体   繁体   English

如何让用 ImageMagick 制作的 animation 在我的 python Jupyter Notebook 上播放?

[英]How do I make animation made with ImageMagick play on my python Jupyter Notebook?

How do I make an animation made with ImageMagick play on my python Jupyter Notebook?如何在我的 python Jupyter Notebook 上播放由 ImageMagick 制作的 animation?

I'm new to animations on Python, so I'm studying how to make one.我是Python上的动画新手,所以我正在研究如何制作一个。 So far, I copied the code from DevelopPaper but when I run the cells, it only shows a static image of it.到目前为止,我从 DevelopPaper 复制了代码,但是当我运行单元格时,它只显示它的 static 图像。 I also tried it for other animation examples there but it's the same for all of them -- animations from Imagemagick won't play on Jupyter Notebook but when I open the saved file manually it works just fine.我也在那里尝试了其他 animation 示例,但它们都是一样的——来自 Imagemagick 的动画不会在 Jupyter Notebook 上播放,但是当我手动打开保存的文件时,它工作得很好。 How do I get the animations to play on Jupyter Notebook itself?如何让动画在 Jupyter Notebook 上播放? Thanks!谢谢! enter image description here在此处输入图像描述

import numpy as np
from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation
plt.style.use('seaborn-pastel')


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

def init():
    line.set_data([], [])
    return line,
def animate(i):
    x = np.linspace(0, 4, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

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

anim.save('sine_wave.gif', writer='imagemagick')

There's lots of options.有很多选择。 (And you probably aren't finding the solutions easily because you aren't using the proper terms as your post title reflects. It seems you want to play a .gif in Jupyter or an animated plot made of frames.) (而且您可能不容易找到解决方案,因为您没有使用帖子标题所反映的正确术语。您似乎想在 Jupyter 中播放.gif或由帧组成的动画 plot。)

First, addressing showing the gif inside Jupyter:首先,解决在 Jupyter 中显示 gif 的问题:

The easiest is to use JupyterLab to open a new notebook run your code after clicking here .最简单的是使用 JupyterLab 打开一个新的笔记本,然后点击这里运行你的代码。 ( For using your code there , change that last line to anim.save('sine_wave.gif') because I didn't bother installing imagemagick there, yet. Pillow is able to make the gif, and matplotlib will handle selecting Pillow for the task if you just don't specify writer .) 要在那里使用您的代码,请将最后一行更改为anim.save('sine_wave.gif')因为我还没有费心在那里安装 imagemagick。Pillow 能够制作 gif,而 matplotlib 将处理选择 Pillow task 如果你只是不指定writer 。)

When the gif file gets made, you can just double click on it in the file browser on the left side and it will play.生成gif文件后,您只需在左侧的文件浏览器中双击它即可播放。 You can arrange the window it plays in as you want relative the notebook by clicking on the tab above it and dragging and then releasing it as you want.您可以通过单击其上方的选项卡并拖动然后根据需要释放它来根据需要相对于笔记本安排它播放的 window。

If you prefer the more traditional notebook for playing the gif in, you can simply put the following code in a cell after the gif file is generated:如果您更喜欢在更传统的笔记本中播放 gif,则可以在生成 gif 文件后将以下代码简单地放在一个单元格中:

from IPython.display import Image
Image("sine_wave.gif")

Executing that notebook cell will play the gif as output for the cell if the gif image file is in the same folder with the notebook file.如果 gif 图像文件与笔记本文件位于同一文件夹中,则执行该笔记本单元将为该单元播放 gif 作为 output。

Second, display alternatives instead of making a gif:其次,显示备选方案而不是制作 gif:

For how to properly get the plotting animation to play, not necessarily as a gif, I'd suggest adding controls following examples and links towards the bottom of the notebook that you can open in active form by clicking 'launch binder' here .对于如何正确地播放绘图 animation,不一定是 gif,我建议在示例和链接之后添加控件到笔记本底部,您可以通过单击此处的“启动活页夹”以活动形式打开 You are looking for examples and links that use or involve FuncAnimation() towards the bottom there.您正在寻找在底部使用或涉及FuncAnimation()的示例和链接。 The ones I suggest involving frames allow you to control and play them using a widget or make HTML that can play and be controlled.我建议涉及框架的那些允许您使用小部件控制和播放它们,或者制作可以播放和控制的 HTML。 Importantly, that widget approach will work even when the notebook is 'static' as you can see here .重要的是,即使笔记本处于“静态”状态,该小部件方法也能正常工作,如您在此处所见。 I put static in quotes because some active features will work in nbviewer, though usually note in Github preview, which trips up a lot of novices now that Github attempts a preview rendering for notebooks even of substantial length.我将static放在引号中,因为一些活动功能将在 nbviewer 中工作,但通常会在 Github 预览中注明,现在 Github 尝试对笔记本进行预览渲染,即使是相当长的笔记本,这也会让很多新手感到困惑。 (And if you need a portable HTML5-compatible video file to be generated, that is covered in that same section.) Here's a couple of variations on your code using related approaches to add the widget/frame generation that will work in active sessions here : (如果您需要生成可移植的 HTML5 兼容视频文件,请参阅同一部分。)这是您的代码的几个变体,使用相关方法添加将在此处的活动会话中工作的小部件/框架生成:

one option一个选项

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
from IPython.display import HTML, display
plt.style.use('seaborn-pastel')

def generate_animation():
    fig = plt.figure()
    ax = plt.axes(xlim=(0, 4), ylim=(-2, 2))
    lineplot, = ax.plot([], [], lw=3)
    
    def init():
        lineplot.set_data([], [])
        return lineplot, #return [lineplot] also works like in https://nbviewer.org/github/raphaelquast/jupyter_notebook_intro/blob/master/jupyter_nb_introduction.ipynb#pre-render-animations-and-export-to-HTML

    def animate(i):
        x = np.linspace(0, 4, 1000)
        y = np.sin(2 * np.pi * (x - 0.01 * i))
        lineplot.set_data([x], [y])
        return [lineplot]

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

    display(HTML(anim.to_jshtml()))
    plt.close(fig)

generate_animation()

another variant另一种变体

# RUN THIS TWICE. SECOND TIME WILL BE NICE SINGLE PLOT DISPLAYED.
# January 2023 I was finding first time I ran this or code like at https://nbviewer.org/gist/fomightez/d862333d8eefb94a74a79022840680b1 that it output a non-interactive frame of plot, too. Just re-ran and then it is just the interactive one with widget.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
from IPython.display import HTML, display
plt.rcParams["animation.html"] = "jshtml"
plt.ioff() #needed so the second time you run it you get only single plot
plt.style.use('seaborn-pastel')

fig = plt.figure()
ax = plt.axes(xlim=(0, 4), ylim=(-2, 2))
lineplot, = ax.plot([], [], lw=3)
    
def init():
    lineplot.set_data([], [])
    return lineplot, #return [lineplot] also works like in https://nbviewer.org/github/raphaelquast/jupyter_notebook_intro/blob/master/jupyter_nb_introduction.ipynb#pre-render-animations-and-export-to-HTML

def animate(i):
    x = np.linspace(0, 4, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    lineplot.set_data([x], [y])
    return [lineplot]

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

A Jupyter notebook with those to options run and more fully explained is here ;一个 Jupyter notebook,其中包含运行选项和更全面的解释 you'll note the widgets work there.您会注意到小部件在那里工作。
Click here to launch that notebook in an active, temporary Jupyter session served via MyBinder.org with the environment already having Python and everything needed to make the animation with a widget work in the notebook installed and working. 单击此处在通过 MyBinder.org 提供的活动的临时 Jupyter session 中启动该笔记本,环境中已经有 Python 以及使带有小部件的 animation 在笔记本中安装和运行所需的一切。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在我的jupyter笔记本中添加python3内核? - How do I add a python3 kernel to my jupyter notebook? 如何使 matplotlib 在 AWS EMR Jupyter 笔记本中工作? - How do I make matplotlib work in AWS EMR Jupyter notebook? 如何在jupyter笔记本中指定使用哪个python和哪个模块? - How do I specify which python and which modules are being used in my jupyter notebook? 如何在 jupyter notebook 中制作带有可点击单元格的表格? - How do I make a table with clickable cells in jupyter notebook? 我如何使用 jupyter 笔记本的 python 代码从网站下载 csv 文件 - how do i download the csv file from a website using python code for my jupyter notebook 我如何使用谷歌云自动化我的 jupyter notebook? - How do i automate my jupyter notebook using google cloud? 如何帮助 Python 找到 Jupyter 命令“jupyter-nbconvert”,将 Jupyter Notebook 导出为 HTML? - How do I help Python find Jupyter command 'jupyter-nbconvert', to export Jupyter Notebook to HTML? 如何将输出集中在 Python Jupyter 笔记本上? - How do I center the outputs on a Python Jupyter notebook? 如何解决 python 中的此错误(Jupyter 笔记本中的代码) - how do I solve this error in python (code in Jupyter notebook) 如何在 Jupyter 笔记本中运行 Python 异步代码? - How do I run Python asyncio code in a Jupyter notebook?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM