绘制图像的多种方式#

在 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()
image demo

也可以显示图片图像。

# 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()
MRI

图像插值#

也可以在显示图像之前对其进行插值。请注意,这可能会改变数据的显示方式,但有助于实现您想要的效果。下面我们将显示同一个(小)数组,使用三种不同的插值方法进行插值。

像素 A[i, j] 的中心绘制在 (i+0.5, j+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()
Nearest, Bilinear, Bicubic

您可以使用 origin 参数指定图像应以数组原点 x[0, 0] 在左上角还是右下角绘制。您还可以在 matplotlibrc 文件中控制默认设置 image.origin。有关此主题的更多信息,请参阅关于 origin 和 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()
blue should be up, blue should be down

最后,我们将显示一个使用剪裁路径的图像。

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()
image demo

参考

本示例展示了以下函数、方法、类和模块的使用

脚本总运行时间: (0 分钟 4.868 秒)

由 Sphinx-Gallery 生成的画廊