Matplotlib 仿射变换

Beginner

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

简介

本实验演示如何使用 Matplotlib 对图像执行仿射变换。仿射变换会改变图像的形状和方向。本实验展示如何使用transforms.Affine2D函数来操作图像的形状和方向。

虚拟机使用提示

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

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

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

导入库并定义图像

第一步,我们导入必要的库并定义示例中要使用的图像。该图像是两个高斯函数的组合。

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.transforms as mtransforms

def get_image():
    delta = 0.25
    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)
    return Z

创建一个用于绘制图像的函数

在这一步中,我们定义一个函数,该函数将图像、绘图轴和变换作为输入。该函数在绘图轴上以指定的变换显示图像。该函数还会在图像周围显示一个黄色矩形,以展示图像的预期范围。

def do_plot(ax, Z, transform):
    im = ax.imshow(Z, interpolation='none',
                   origin='lower',
                   extent=[-2, 4, -3, 2], clip_on=True)

    trans_data = transform + ax.transData
    im.set_transform(trans_data)

    ## display intended extent of the image
    x1, x2, y1, y2 = im.get_extent()
    ax.plot([x1, x2, x2, x1, x1], [y1, y1, y2, y2, y1], "y--",
            transform=trans_data)
    ax.set_xlim(-5, 5)
    ax.set_ylim(-4, 4)

执行图像旋转

在这一步中,我们使用rotate_deg函数对图像进行旋转。我们将旋转角度作为输入传递给rotate_deg函数。我们使用do_plot函数来显示旋转后的图像。

## prepare image and figure
fig, ax1 = plt.subplots()
Z = get_image()

## image rotation
do_plot(ax1, Z, mtransforms.Affine2D().rotate_deg(30))

执行图像倾斜

在这一步中,我们使用skew_deg函数对图像进行倾斜。我们将倾斜角度作为输入传递给skew_deg函数。我们使用do_plot函数来显示倾斜后的图像。

## prepare image and figure
fig, ax2 = plt.subplots()
Z = get_image()

## image skew
do_plot(ax2, Z, mtransforms.Affine2D().skew_deg(30, 15))

执行图像缩放与反射

在这一步中,我们使用scale函数对图像进行缩放与反射操作。我们将缩放因子和反射因子作为输入传递给scale函数。我们使用do_plot函数来显示经过缩放和反射后的图像。

## prepare image and figure
fig, ax3 = plt.subplots()
Z = get_image()

## scale and reflection
do_plot(ax3, Z, mtransforms.Affine2D().scale(-1,.5))

执行多个变换

在这一步中,我们使用rotate_degskew_degscaletranslate函数对图像执行多个变换。我们将变换参数作为输入传递给相应的函数。我们使用do_plot函数来显示变换后的图像。

## prepare image and figure
fig, ax4 = plt.subplots()
Z = get_image()

## everything and a translation
do_plot(ax4, Z, mtransforms.Affine2D().
        rotate_deg(30).skew_deg(30, 15).scale(-1,.5).translate(.5, -1))

总结

本实验展示了如何使用 Matplotlib 对图像进行仿射变换。我们使用transforms.Affine2D函数来操作图像的形状和方向。我们对图像进行了旋转、倾斜、缩放、反射以及多种变换。我们还在具有图像预期范围的绘图轴上显示了变换后的图像。