Jupyter AI

7 几何变换:平移、旋转与缩放

📅 发表日期: 2024年8月11日

分类: 🖼️计算机图形学入门

👁️阅读: --

在计算机图形学中,几何变换是操作对象空间中图形的重要工具,它们通过数学手段改变图形的位置、方向或大小。本篇文章将详细探讨三种基本的几何变换:平移旋转缩放,同时通过案例和代码示例来帮助理解这些概念。

平移

定义

平移是一种简单的几何变换,它通过在二维或三维空间中移动一个对象来改变其位置。平移变换不改变图形的形状或大小。

数学表示

在二维空间中,平移变换可以表示为:

[xy]=[xy]+[txty]\begin{bmatrix} x' \\ y' \end{bmatrix} = \begin{bmatrix} x \\ y \end{bmatrix} + \begin{bmatrix} t_x \\ t_y \end{bmatrix}

其中 (x,y)(x', y') 是平移后的坐标,(x,y)(x, y) 是原始坐标,(tx,ty)(t_x, t_y) 是平移向量。

示例

假设我们有一个点 P(2,3)P(2, 3),我们希望将它平移 tx=5t_x = 5ty=2t_y = -2

P=[23]+[52]=[71]P' = \begin{bmatrix} 2 \\ 3 \end{bmatrix} + \begin{bmatrix} 5 \\ -2 \end{bmatrix} = \begin{bmatrix} 7 \\ 1 \end{bmatrix}

代码示例

以下是一个简单的 Python 代码示例,展示如何实现平移变换:

import numpy as np

def translate(point, translation_vector):
    return point + translation_vector

point = np.array([2, 3])
translation_vector = np.array([5, -2])
new_point = translate(point, translation_vector)
print(new_point)  # Output: [7 1]

旋转

定义

旋转变换是围绕某个固定点(通常是坐标原点)将图形旋转一定角度的过程。这种变换改变了图形的方向,但不会改变其形状或大小。

数学表示

在二维空间中,旋转变换可通过以下矩阵实现:

[xy]=[cos(θ)sin(θ)sin(θ)cos(θ)][xy]\begin{bmatrix} x' \\ y' \end{bmatrix} = \begin{bmatrix} \cos(\theta) & -\sin(\theta) \\ \sin(\theta) & \cos(\theta) \end{bmatrix} \begin{bmatrix} x \\ y \end{bmatrix}

其中 θ\theta 是旋转角度,(x,y)(x', y') 是旋转后的坐标。

示例

如果我们要将点 P(1,0)P(1, 0) 绕原点旋转 9090^\circ,则:

θ=90=π2[xy]=[cos(π2)sin(π2)sin(π2)cos(π2)][10]=[01]\theta = 90^\circ = \frac{\pi}{2} \\ \begin{bmatrix} x' \\ y' \end{bmatrix} = \begin{bmatrix} \cos\left(\frac{\pi}{2}\right) & -\sin\left(\frac{\pi}{2}\right) \\ \sin\left(\frac{\pi}{2}\right) & \cos\left(\frac{\pi}{2}\right) \end{bmatrix} \begin{bmatrix} 1 \\ 0 \end{bmatrix} = \begin{bmatrix} 0 \\ 1 \end{bmatrix}

代码示例

以下是一个 Python 示例,展示如何实现旋转变换:

import numpy as np

def rotate(point, angle):
    angle_rad = np.radians(angle)
    rotation_matrix = np.array([
        [np.cos(angle_rad), -np.sin(angle_rad)],
        [np.sin(angle_rad), np.cos(angle_rad)]
    ])
    return np.dot(rotation_matrix, point)

point = np.array([1, 0])
rotated_point = rotate(point, 90)
print(rotated_point)  # Output: [0. 1.]

缩放

定义

缩放变换是按一定比例(在某个方向上)增大或缩小图形的过程。缩放可以是均匀的(在所有方向上相同)或不均匀的(在某些方向上不同)。

数学表示

在二维空间中,缩放变换的表示为:

[xy]=[sx00sy][xy]\begin{bmatrix} x' \\ y' \end{bmatrix} = \begin{bmatrix} s_x & 0 \\ 0 & s_y \end{bmatrix} \begin{bmatrix} x \\ y \end{bmatrix}

其中 sxs_xsys_y 是在 xx 轴和 yy 轴上的缩放因子。

示例

如果我们有一个点 P(2,3)P(2, 3),并选择 sx=2s_x = 2sy=3s_y = 3,则:

P=[2×23×3]=[49]P' = \begin{bmatrix} 2 \times 2 \\ 3 \times 3 \end{bmatrix} = \begin{bmatrix} 4 \\ 9 \end{bmatrix}

代码示例

以下 Python 示例展示了如何实施缩放变换:

import numpy as np

def scale(point, scaling_factors):
    return point * scaling_factors

point = np.array([2, 3])
scaling_factors = np.array([2, 3])
scaled_point = scale(point, scaling_factors)
print(scaled_point)  # Output: [4 9]

总结

本文详细探讨了平移、旋转和缩放三种基本的几何变换,每种变换都有其特定的数学表示和实际应用。理解这些基础概念对于后续学习仿射变换与投影变换是至关重要的,正如我们下一篇文章所将要讨论的内容。这些变换形成了图形学中的基本构建块,使我们能够在计算机图形中创建和操作各种形状。