如何在ipython笔记本中重新加载图像?

时间:2016-05-04 09:06:33

标签: python jupyter-notebook

在我的笔记本中,我可以在相同的文件夹中显示markdown中的图像,如下所示:

<img src="files/adaptive_filter.png" alt="Schema of adaptive filter" height="100"> 

如果我使用files/中没有src的代码,则无效。

现在我改变了图像,ipython笔记本仍然显示原始图像。我尝试将其从代码中删除并重新启动笔记本,但它没有帮助。

我该怎么办?图像是否存储在某个地方?

提前致谢。

4 个答案:

答案 0 :(得分:4)

我也遇到了这个问题,我使用自己的类来输出一些python图并将它们嵌入到IPython笔记本中。解决这个问题的一种方法是在图像URL的末尾添加一个随机参数。例如

<img src="files/adaptive_filter.png?1" alt="Schema of adaptive filter" height="100">

不会缓存在与

相同的位置
<img src="files/adaptive_filter.png?2" alt="Schema of adaptive filter" height="100">

这样做的一种编程方式是通过python而不是降价来包含图片,例如:

# pick a random integer with 1 in 2 billion chance of getting the same
# integer twice
import random
__counter__ = random.randint(0,2e9)

# now use IPython's rich display to display the html image with the
# new argument
from IPython.display import HTML, display
display(HTML('<img src="files/adaptive_filter.png?%d" ' +
             'alt="Schema of adaptive filter" ' +
             'height="100">' % __counter__))

每次运行代码单元时都应该更新图像

答案 1 :(得分:1)

我遇到了完全相同的问题。以下过程对我有用:

.ipynb文件所在的文件夹中,有一个名为.ipynb_checkpoints /的缓存目录。该高速缓存目录中应该有一个与您正在使用的文件具有相同文件名的文件。现在,删除/删除.ip​​ynb_checkpoint /目录中的缓存文件,然后重新加载浏览器。您应该能够看到更新的图像。

我的环境:通过anaconda安装了macOS 10.14.2,Chrome浏览器71.0和Jupyter 1.0.0。

希望这会有所帮助。

答案 2 :(得分:0)

  1. 在ipynb文件目录中,使用ls命令,它将显示隐藏的 目录 .ipynb_checkpoints

  2. 删除 .ipynb_checkpoints 目录,然后重新运行单元格 代码,您将看到最新的图像。

答案 3 :(得分:0)

我遇到了同样的问题,即在 jupyter 中缓存图像,并且在使用 matplotlib.pyplot 时修改文件时没有更新。我使用 IPython.display.Image

修复了它
from IPython.display import Image
def saveImage(path, show=True): 
    plt.savefig(path, facecolor="white", bbox_inches='tight') 
    if show: return Image(path)

然后在代码单元的末尾,类似 saveImage('./someImage.png') 的内容将保存并显示图像。

类似地,Image('./someImage.png') 将显示磁盘中的图像(不保存)。

这似乎避免了缓存问题,并且图像在 PDF 导出中正确显示(另请参阅 Jupyter notebook matplotlib figures missing in exported pdf 以获取基于此的答案)。

就我而言,它有助于减小 jupyter notebook 的大小,防止它在呈现和更新 matplotlib.pyplot 图表时崩溃。

相关问题