📌  相关文章
📜  显示图像 jupyter notebook - Python (1)

📅  最后修改于: 2023-12-03 15:10:31.411000             🧑  作者: Mango

显示图像 jupyter notebook - Python

在jupyter notebook中,我们可以很方便地显示图像。本文将介绍在jupyter notebook中显示图像的几种方法。

方法一:使用IPython.display

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')
方法二:使用matplotlib

在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方法传递nrowsncols参数来实现。示例代码如下:

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中展示图片的功能。