简体   繁体   English

如何在 Jupyter Notebook 中显示文件中的图像?

[英]How can I display an image from a file in Jupyter Notebook?

I would like to use an IPython notebook as a way to interactively analyze some genome charts I am making with Biopython's GenomeDiagram module.我想使用IPython 笔记本作为交互式分析我使用 Biopython 的GenomeDiagram模块制作的一些基因组图表的一种方式。 While there is extensive documentation on how to use matplotlib to get graphs inline in IPython notebook, GenomeDiagram uses the ReportLab toolkit which I don't think is supported for inline graphing in IPython.虽然有大量关于如何使用matplotlib在 IPython 笔记本中获取内联图形的文档,但 GenomeDiagram 使用 ReportLab 工具包,我认为 IPython 中的内联图形不支持该工具包。

I was thinking, however, that a way around this would be to write out the plot/genome diagram to a file and then open the image inline which would have the same result with something like this:然而,我在想,解决这个问题的一种方法是将绘图/基因组图写到一个文件中,然后打开内联图像,这将具有相同的结果,如下所示:

gd_diagram.write("test.png", "PNG")
display(file="test.png")

However, I can't figure out how to do this - or know if it's possible.但是,我无法弄清楚如何做到这一点 - 或者知道它是否可能。 So does anyone know if images can be opened/displayed in IPython?那么有谁知道图像是否可以在 IPython 中打开/显示?

Courtesy of this post , you can do the following:感谢这篇文章,您可以执行以下操作:

from IPython.display import Image
Image(filename='test.png') 

( official docs ) 官方文档

If you are trying to display an Image in this way inside a loop, then you need to wrap the Image constructor in a display method.如果您尝试在循环中以这种方式显示 Image,则需要将 Image 构造函数包装在 display 方法中。

from IPython.display import Image, display

listOfImageNames = ['/path/to/images/1.png',
                    '/path/to/images/2.png']

for imageName in listOfImageNames:
    display(Image(filename=imageName))

Note, until now posted solutions only work for png and jpg!请注意,到目前为止发布的解决方案仅适用于 png 和 jpg!

If you want it even easier without importing further libraries or you want to display an animated or not animated GIF File in your Ipython Notebook.如果您希望在不导入更多库的情况下更轻松,或者您想在 Ipython Notebook 中显示动画或非动画 GIF 文件。 Transform the line where you want to display it to markdown and use this nice short hack!将要显示它的行转换为降价并使用这个漂亮的简短技巧!

![alt text](test.gif "Title")

This will import and display a .jpg image in Jupyter (tested with Python 2.7 in Anaconda environment)这将在 Jupyter 中导入并显示.jpg图像(在 Anaconda 环境中使用 Python 2.7 测试)

from IPython.display import display
from PIL import Image


path="/path/to/image.jpg"
display(Image.open(path))

You may need to install PIL您可能需要安装 PIL

in Anaconda this is done by typing在 Anaconda 中,这是通过键入来完成的

conda install pillow

您可以在降价部分的 html 代码中使用:示例:

 <img src="https://www.tensorflow.org/images/colab_logo_32px.png" />

If you want to efficiently display big number of images I recommend using IPyPlot package如果您想有效地显示大量图像,我建议使用IPyPlot 包

import ipyplot

ipyplot.plot_images(images_array, max_images=20, img_width=150)

在此处输入图像描述

There are some other useful functions in that package where you can display images in interactive tabs (separate tab for each label/class) which is very helpful for all the ML classification tasks.该包中还有一些其他有用的功能,您可以在交互式选项卡中显示图像(每个标签/类的单独选项卡),这对所有 ML 分类任务非常有帮助。

在此处输入图像描述

Courtesy of this page, I found this worked when the suggestions above didn't:感谢这个页面,当上面的建议没有时,我发现这很有效:

import PIL.Image
from cStringIO import StringIO
import IPython.display
import numpy as np
def showarray(a, fmt='png'):
    a = np.uint8(a)
    f = StringIO()
    PIL.Image.fromarray(a).save(f, fmt)
    IPython.display.display(IPython.display.Image(data=f.getvalue()))

A cleaner Python3 version that use standard numpy, matplotlib and PIL.使用标准 numpy、matplotlib 和 PIL 的更简洁的 Python3 版本。 Merging the answer for opening from URL.合并从 URL 打开的答案。

import matplotlib.pyplot as plt
from PIL import Image
import numpy as np

pil_im = Image.open('image.png') #Take jpg + png
## Uncomment to open from URL
#import requests
#r = requests.get('https://www.vegvesen.no/public/webkamera/kamera?id=131206')
#pil_im = Image.open(BytesIO(r.content))
im_array = np.asarray(pil_im)
plt.imshow(im_array)
plt.show()
from IPython.display import Image

Image(filename =r'C:\user\path')

I've seen some solutions and some wont work because of the raw directory, when adding codes like the one above, just remember to add 'r' before the directory.我已经看到了一些解决方案,有些由于原始目录而无法工作,在添加上述代码时,请记住在目录之前添加“r”。 this should avoid this kind of error: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape这应该避免这种错误:(unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

If you are looking to embed your image into ipython notebook from the local host, you can do the following:如果您希望将图像从本地主机嵌入到 ipython 笔记本中,您可以执行以下操作:

First : find the current local path:第一:找到当前本地路径:

# show current directory
import os
cwd = os.getcwd()
cwd

The result for example would be:例如,结果将是:

'C:\\Users\\lenovo\\Tutorials'

Next , embed your image as follows:接下来,按如下方式嵌入您的图像:

from IPython.display import display
from PIL import Image

path="C:\\Users\\lenovo\\Tutorials\\Data_Science\\DS images\\your_image.jpeg"
display(Image.open(path))

Make sure that you choose the right image type among jpg, jpeg or png.确保在 jpg、jpeg 或 png 中选择正确的图像类型。

You can also use PIL to display image files in Jupyter Notebook: 您还可以使用PIL在Jupyter Notebook中显示图像文件:

from PIL import Image
path = "cats/cat0.jpg"
display(Image.open(path))

This works in a loop as well. 这也可以循环工作。

Another option for plotting inline from an array of images could be:从图像数组内联绘制的另一个选项可能是:

import IPython
def showimg(a):
    IPython.display.display(PIL.Image.fromarray(a))

where a is an array其中 a 是一个数组

a.shape
(720, 1280, 3)

Another opt is:另一个选择是:

from matplotlib import pyplot as plt 
from io import BytesIO
from PIL import Image
import Ipython

f = BytesIO()
plt.savefig(f, format='png')
Ipython.display.display(Ipython.display.Image(data=f.getvalue()))
f.close()

When using GenomeDiagram with Jupyter (iPython), the easiest way to display images is by converting the GenomeDiagram to a PNG image.GenomeDiagram与 Jupyter (iPython) 一起使用时,显示图像的最简单方法是将 GenomeDiagram 转换为 PNG 图像。 This can be wrapped using an IPython.display.Image object to make it display in the notebook.这可以使用 IPython.display.Image 对象进行包装,使其显示在笔记本中。

from Bio.Graphics import GenomeDiagram
from Bio.SeqFeature import SeqFeature, FeatureLocation
from IPython.display import display, Image
gd_diagram = GenomeDiagram.Diagram("Test diagram")
gd_track_for_features = gd_diagram.new_track(1, name="Annotated Features")
gd_feature_set = gd_track_for_features.new_set()
gd_feature_set.add_feature(SeqFeature(FeatureLocation(25, 75), strand=+1))
gd_diagram.draw(format="linear", orientation="landscape", pagesize='A4',
                fragments=1, start=0, end=100)
Image(gd_diagram.write_to_string("PNG"))

[See Notebook] [见笔记本]

You can directly use this instead of importing PIL您可以直接使用它而不是导入 PIL

from IPython.display import Image, display
    
    display(Image(base_image_path))
    

This is the solution using opencv-python, but it opens new windows which is busy in waiting这是使用opencv-python的解决方案,但它会打开忙于等待的新窗口

import cv2 # pip install opencv-python
image = cv2.imread("foo.png")
cv2.imshow('test',image)
cv2.waitKey(duration) # in milliseconds; duration=0 means waiting forever
cv2.destroyAllWindows()

if you don't want to display image in another window, using matplotlib or whatever instead cv2.imshow()如果您不想在另一个窗口中显示图像,请使用matplotlib或其他任何东西cv2.imshow()

import cv2
import matplotlib.pyplot as plt
image = cv2.imread("foo.png")
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.show()

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

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