📅  最后修改于: 2023-12-03 15:10:31.411000             🧑  作者: Mango
在jupyter notebook中,我们可以很方便地显示图像。本文将介绍在jupyter notebook中显示图像的几种方法。
IPython.display模块提供了很多方法可以帮助我们在notebook中显示各种格式的数据。其中,Image
类可以用来显示图片。示例代码如下:
from IPython.display import Image
Image(filename='path/to/image.jpg')
其中,filename
参数指定图片的路径。如果图片与notebook在同一目录下,可以直接使用图片文件名。
该方法还支持传入URL作为参数,以显示在线图片。示例代码如下:
Image(url='https://example.com/image.jpg')
在python中,matplotlib
是最常用的绘图库之一。它也可以用来显示图片。示例代码如下:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img = mpimg.imread('path/to/image.jpg')
plt.imshow(img)
plt.axis('off')
plt.show()
如果要显示多张图片,可以通过给plt.subplots
方法传递nrows
和ncols
参数来实现。示例代码如下:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img1 = mpimg.imread('path/to/image1.jpg')
img2 = mpimg.imread('path/to/image2.jpg')
img3 = mpimg.imread('path/to/image3.jpg')
fig, axs = plt.subplots(nrows=1, ncols=3, figsize=(12, 4))
axs[0].imshow(img1)
axs[1].imshow(img2)
axs[2].imshow(img3)
for ax in axs:
ax.axis('off')
plt.show()
以上就是在jupyter notebook中显示图像的几种方法。无论是使用IPython.display还是matplotlib,都可以轻松地实现在notebook中展示图片的功能。