python - 如何使用 google colab 在 jupyter notebook 中显示 GIF?

标签 python matplotlib jupyter-notebook gif google-colaboratory

我正在使用 google colab 并想嵌入一个 gif。有谁知道如何做到这一点?我正在使用下面的代码,它没有为笔记本中的 gif 设置动画。我希望笔记本具有交互性,以便人们无需运行即可看到代码的动画效果。

我找到了很多在 Google colab 中不起作用的方法。感兴趣的代码和 GIF 如下。

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

img = mpimg.imread("/content/animationBrownianMotion2d.gif")
plt.imshow(img)

enter image description here

我尝试了一些提供的解决方案。
import IPython
from IPython.display import Image
Image(filename='/content/animationBrownianMotion2d.gif')

同样
import IPython
from IPython.display import Image
Image(filename='/content/animationBrownianMotion2d.gif',embed=True)

但得到了错误,
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-27-56bf6cd2b134> in <module>()
      1 import IPython
      2 from IPython.display import Image
----> 3 Image(filename='/content/animationBrownianMotion2d.gif',embed=True)
      4 

/usr/local/lib/python3.6/dist-packages/IPython/core/display.py in __init__(self, data, url, filename, format, embed, width, height, retina, unconfined, metadata)
   1013 
   1014         if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS:
-> 1015             raise ValueError("Cannot embed the '%s' image format" % (self.format))
   1016         self.width = width
   1017         self.height = height

ValueError: Cannot embed the 'gif' image format

两次。

最佳答案

对于外部 gif,您可以使用 Jupyter 的显示作为 @knoop 的答案。

from IPython.display import Image
Image(url='https://upload.wikimedia.org/wikipedia/commons/e/e3/Animhorse.gif')

但是对于本地文件,您需要读取字节并显示它。
!wget https://upload.wikimedia.org/wikipedia/commons/e/e3/Animhorse.gif
Image(open('Animhorse.gif','rb').read())

关于python - 如何使用 google colab 在 jupyter notebook 中显示 GIF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61110188/

相关文章:

python - matplotlib 存储和删除艺术家

python - 带有百分比标签的python中的圆形条形图

jupyter-notebook - 在 Google Colab 中显示带有换行符的所有输出

python - 我忘记关闭 tf.InteractiveSession,如何终止任何剩余进程?

python - pandas groupby 计数、总和和平均值

python - 使用 python 打印设置 header 访问控制允许来源

python - web2py 无法识别模块目录中的模块

python - 修改python中的matplotlib图例

python - 如何在 python 中获取用于 SQL 查询的表列名/表头

python - 将隐含乘法 (*) 添加到 Python 字符串的最佳方法?