如何在 Jupyter notebook 中嵌入 gif?

How do I embed a gif in Jupyter notebook?

我一直在尝试在 Jupyter notebook 中显示 gif,但遇到了一些麻烦。我一直收到一个空白图像文件。

我试过使用 this GitHub repository 中的 html。

![wignerfunction][1](../gifs/wigner_rotation_animate.gif "wigner")

from IPython.display import Image
Image(url='example.gif')  
以上的

None 到目前为止都有效。

谢谢

I've been trying to display a gif in Jupyter notebook and have had some trouble.

要在笔记本中显示 gif,您可以像这样在 Markdown 单元格上使用内联标记:

  • ipynb notebook文件所在文件夹中的相对引用:

    ![SegmentLocal](191px-Seven_segment_display-animated.gif "segment")
    
  • ipynb 笔记本文件所在文件夹的子文件夹图像中的相对引用:

    ![SegmentLocal](images/191px-Seven_segment_display-animated.gif "segment")
    
  • 无论笔记本文件的位置如何,从根文件夹绝对引用:

    ![SegmentLocal](/Users/username/some-folder/191px-Seven_segment_display-animated.gif "segment")
    
  • URL 参考资料(应该在您的笔记本中开箱即用):

    ![ChessUrl](https://upload.wikimedia.org/wikipedia/commons/7/71/ChessPawnSpecialMoves.gif "chess")
    

例如,由于堆栈溢出也使用 markdown,因此最后一行带有 url 引用,如果正好给出最后提到的行:![ChessUrl](https://upload.wikimedia.org/wikipedia/commons/7/71/ChessPawnSpecialMoves.gif "chess"),但未作为代码引用计算为:

也应该显示在您的 jupyter notebook 中。现在,如果您可以看到最后一个,但无法从引用的本地文件中看到它,您很可能是 gif 损坏、权限问题或文件路径不正确。

任何想要在 python jupyter notebook 中显示的图像格式,无论是 png、jpg、jpeg 或 gif 等,然后只需使用 matplotlib 库即可。

import matplotlib.pyplot as plt

import matplotlib.image as mpimg

img = mpimg.imread("/home/gaurav/assignment/sofcomputing/river.gif")

plt.imshow(img)

当我需要在 jupyter notebook 中包含 gif 动画时,我会执行以下操作:

<img src="FileName.gif" width="750" align="center">

宽度和对齐参数由您定义。

谢谢

在某些情况下,您需要将gif文件嵌入到Jupyter notebook中,即即使您磁盘上的gif文件已被删除,该gif文件仍可在Jupyter notebook中使用。 @user13013261 的解决方案会失败,@Const 只能在 Markdown 单元格中工作。

你可以试试这些:

display(Image(data=open(gif_path,'rb').read(), format='png'))

import base64
b64 = base64.b64encode(open(gif_path,'rb').read()).decode('ascii')
display(HTML(f'<img src="data:image/gif;base64,{b64}" />'))

参考:
https://github.com/ipython/ipython/issues/10045#issuecomment-318202267 https://github.com/ipython/ipython/issues/10045#issuecomment-642640541

import ipywidgets as widgets
display(widgets.HTML(f'<img src="{gif_file}" width="750" align="center">'))