如何用 Matplotlib 显示图片
Suraj Joshi
2024年2月15日
Matplotlib
Matplotlib Images
本教程将讨论如何使用 matplotlib.pyplot.imshow() 方法来使用 Matplotlib 显示图片。
matplotlib.pyplot.imshow() 方法
matplotlib.pyplot.imshow() 在 Matplotlib 中显示数字。
matplotlib.pyplot.imshow() 语法
matplotlib.pyplot.imshow(X,
cmap=None,
norm=None,
aspect=None,
interpolation=None,
alpha=None,
vmin=None,
vmax=None,
origin=None,
extent=None, *,
filternorm=True,
filterrad=4.0,
resample=None,
url=None,
data=None,
**kwargs)
在这里,X 代表显示的图片或 PIL 图片的数组式结构。
示例:用 Matplotlib Python 使用 imshow() 显示图片
import matplotlib.pyplot as plt
import matplotlib.image as img
image = img.imread("lena.jpg")
plt.imshow(image)
plt.show()
输出:

它使用 matplotlib.image 模块中的 imread() 方法从当前工作目录中读取图片 lena.jpg,最后使用 imshow() 方法显示图片。如果不使用 IPython Notebooks,必须在 imshow() 之后调用 show() 方法才能查看图片,show() 方法会启动图片的单独窗口。
示例:用 Matplotlib Python 使用 imshow() 显示 PIL 图片
import matplotlib.pyplot as plt
from PIL import Image
image = Image.open("lena.jpg")
plt.imshow(image)
plt.show()
输出:

它显示 PIL 图片。我们使用 PIL 的 Image 模块中的 open() 方法读取它。我们也可以用 PIL 直接显示图片,方法简单得多。
from PIL import Image
img = Image.open("lena.jpg")
img.show()
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Suraj Joshi
Suraj Joshi is a backend software engineer at Matrice.ai.
LinkedIn