繁体   English   中英

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

[英]How to display a GIF in jupyter notebook using google colab?

我正在使用 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)

在此处输入图像描述

我尝试了一些提供的解决方案。

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())

我不知道为什么上述方法对我不起作用。

如何将 gif 文件从谷歌驱动器插入到谷歌 colab

第 1 步:将 gif 保存到您的 Google 驱动器中

第2步:要求谷歌驱动器在谷歌驱动器中打开您的文件(此步骤与原始问题没有直接关系。)

  • 如何将数据从 google drive 导入到 google colab。 关联

    1. 在您的 Google 云端硬盘(“我的云端硬盘”)中,在您选择的位置创建一个名为 data 的文件夹。 这是您上传数据的地方。

    2. 在 Colab 笔记本中,键入以下内容:

from google.colab import drive         # tell colab to look at google drive
drive.mount('/content/drive')
  1. 这些命令将带您进入 Google 身份验证步骤。 您应该会看到一个带有 Google Drive File Stream 想要访问您的 Google 帐户的屏幕。

  2. 获得许可后,复制给定的验证码并将其粘贴到 Colab 的框中。

  3. 在笔记本中,单击笔记本左上角的木炭>,然后单击文件。

  4. 找到您之前创建的数据文件夹并找到您的数据。 右键单击您的数据和 select 复制路径。 将此复制的路径存储到变量中,您就可以准备好 go。

  5. 数据集现在存储在 Pandas Dataframe

第 3 步:

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
from IPython import display

第4步:

gifPath = Path("/content/drive/My Drive/xxxx/xxx.gif") # please paste the whole path from Step 2-6
# Display GIF in Jupyter, CoLab, IPython
with open(gifPath,'rb') as f:
    display.Image(data=f.read(), format='png')

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM