Matplotlib 图像可视化技术

Beginner

This tutorial is from open-source community. Access the source code

简介

Matplotlib 是一个用于 Python 编程语言及其数值数学扩展 NumPy 的绘图库。它提供了一个面向对象的 API,用于使用 Tkinter、wxPython、Qt 或 GTK 等通用 GUI 工具包将绘图嵌入到应用程序中。在本实验中,我们将学习如何使用 Matplotlib 绘制不同类型的图像。

虚拟机使用提示

虚拟机启动完成后,点击左上角切换到“笔记本”标签,以访问 Jupyter Notebook 进行练习。

有时,你可能需要等待几秒钟让 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。

如果你在学习过程中遇到问题,随时向 Labby 提问。课程结束后提供反馈,我们会及时为你解决问题。

导入必要的库

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

绘制二元正态分布

## 生成一个简单的二元正态分布
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()

绘制图片图像

## 加载一张示例图片
with cbook.get_sample_data('grace_hopper.jpg') as image_file:
    image = plt.imread(image_file)

## 使用 256x256 的 16 位整数加载另一张图片。
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')  ## 清除 x 轴和 y 轴

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 = 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()

控制图像原点

## 指定图像应以数组原点 x[0, 0] 位于左上角还是右下角的方式绘制
x = np.arange(120).reshape((10, 12))

interp = 'bilinear'
fig, axs = plt.subplots(nrows=2, sharex=True, figsize=(3, 5))
axs[0].set_title('蓝色应在上部')
axs[0].imshow(x, origin='upper', interpolation=interp)

axs[1].set_title('蓝色应在下部')
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 绘制不同类型的图像。我们绘制了二元正态分布、图片图像、插值图像以及使用剪辑路径的图像。我们还学习了如何控制图像原点。