备注
Go to the end 下载完整的示例代码.
绘制图像的多种方法#
在 Matplotlib 中绘制图像最常见的方法是使用 imshow .以下示例演示了 imshow 的许多功能以及您可以创建的许多图像.
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cbook as cbook
import matplotlib.cm as cm
from matplotlib.patches import PathPatch
from matplotlib.path import Path
# Fixing random state for reproducibility
np.random.seed(19680801)
首先,我们将生成一个简单的二元正态分布.
delta = 0.025
x = y = np.arange(-3.0, 3.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) * 2
fig, ax = plt.subplots()
im = ax.imshow(Z, interpolation='bilinear', cmap=cm.RdYlGn,
origin='lower', extent=[-3, 3, -3, 3],
vmax=abs(Z).max(), vmin=-abs(Z).max())
plt.show()

也可以显示图片的图像.
# A sample image
with cbook.get_sample_data('grace_hopper.jpg') as image_file:
image = plt.imread(image_file)
# And another image, using 256x256 16-bit integers.
w, h = 256, 256
with cbook.get_sample_data('s1045.ima.gz') as datafile:
s = datafile.read()
A = np.frombuffer(s, np.uint16).astype(float).reshape((w, h))
extent = (0, 25, 0, 25)
fig, ax = plt.subplot_mosaic([
['hopper', 'mri']
], figsize=(7, 3.5))
ax['hopper'].imshow(image)
ax['hopper'].axis('off') # clear x-axis and y-axis
im = ax['mri'].imshow(A, cmap=plt.cm.hot, origin='upper', extent=extent)
markers = [(15.9, 14.5), (16.8, 15)]
x, y = zip(*markers)
ax['mri'].plot(x, y, 'o')
ax['mri'].set_title('MRI')
plt.show()

插值图像#
也可以在显示图像之前对其进行插值.请注意,这可能会改变数据的外观,但对达到您想要的效果很有帮助.下面我们将显示相同的(小)数组,并使用三种不同的插值方法对其进行插值.
A[i, j] 处像素的中心点绘制在 (i+0.5, i+0.5) 处.如果您使用 interpolation='nearest',则以 (i, j) 和 (i+1, j+1) 为界的区域将具有相同的颜色.如果您使用插值,则像素中心将具有与使用 nearest 时相同的颜色,但其他像素将在相邻像素之间进行插值.
为了防止在进行插值时出现边缘效应,Matplotlib 会在输入数组的边缘填充相同的像素:如果您有一个 5x5 的数组,颜色如下:
a b c d e
f g h i j
k l m n o
p q r s t
u v w x y
Matplotlib 计算填充数组上的插值和大小调整:
a a b c d e e
a a b c d e e
f f g h i j j
k k l m n o o
p p q r s t t
o u v w x y y
o u v w x y y
然后提取结果的中心区域.(极旧版本的 Matplotlib (<0.63) 没有填充数组,而是调整了视图限制以隐藏受影响的边缘区域.)
这种方法允许绘制数组的整个范围而没有边缘效应,例如,可以使用不同的插值方法将多个不同大小的图像分层叠加在一起 -- 请参阅 使用 alpha 混合分层图像 .这也意味着性能损失,因为必须创建这个新的临时填充数组.复杂的插值也意味着性能损失;为了获得最大性能或处理非常大的图像,建议使用 interpolation='nearest'.
A = np.random.rand(5, 5)
fig, axs = plt.subplots(1, 3, figsize=(10, 3))
for ax, interp in zip(axs, ['nearest', 'bilinear', 'bicubic']):
ax.imshow(A, interpolation=interp)
ax.set_title(interp.capitalize())
ax.grid(True)
plt.show()

您可以使用 origin 参数指定是否应使用数组原点 x[0, 0] 在左上角或右下角绘制图像.您还可以在 matplotlibrc file 中控制默认设置 image.origin .有关此主题的更多信息,请参阅 complete guide on origin and extent .
x = np.arange(120).reshape((10, 12))
interp = 'bilinear'
fig, axs = plt.subplots(nrows=2, sharex=True, figsize=(3, 5))
axs[0].set_title('blue should be up')
axs[0].imshow(x, origin='upper', interpolation=interp)
axs[1].set_title('blue should be down')
axs[1].imshow(x, origin='lower', interpolation=interp)
plt.show()

最后,我们将使用剪切路径显示图像.
delta = 0.025
x = y = np.arange(-3.0, 3.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) * 2
path = Path([[0, 1], [1, 0], [0, -1], [-1, 0], [0, 1]])
patch = PathPatch(path, facecolor='none')
fig, ax = plt.subplots()
ax.add_patch(patch)
im = ax.imshow(Z, interpolation='bilinear', cmap=cm.gray,
origin='lower', extent=[-3, 3, -3, 3],
clip_path=patch, clip_on=True)
im.set_clip_path(patch)
plt.show()

参考
以下函数,方法,类和模块的用法在本例中显示:
matplotlib.axes.Axes.imshow/matplotlib.pyplot.imshowmatplotlib.artist.Artist.set_clip_pathmatplotlib.patches.PathPatch
脚本的总运行时间:(0 分 1.854 秒)