第4章 图像几何变换

缩放 · 旋转 · 平移 · 仿射变换 · 透视变换 —— 原理与实现

几何变换是图像预处理中最基础也最核心的操作之一。它通过重新映射像素坐标来改变图像的形状、位置或视角,广泛应用于数据增强、图像配准、相机校正等场景。本章将系统讲解五种基本几何变换的数学原理与编程实现。

变换类型自由度矩阵形式典型应用
缩放 (Scale)2 (sx, sy)对角矩阵图像金字塔、缩略图
旋转 (Rotation)1 (θ)2×2 旋转矩阵图像校正、数据增强
平移 (Translation)2 (tx, ty)平移向量目标居中、滑动窗口
仿射变换 (Affine)62×3 矩阵通用线性变换 + 平移
透视变换 (Perspective)83×3 矩阵视角校正、文档扫描

1. 图像缩放

缩放通过乘以缩放因子改变图像尺寸。设原坐标 (x, y),缩放后坐标 (x', y') = (sx·x, sy·y)。
实现时需进行插值(最近邻、双线性、双三次等)以避免锯齿。

原图 100×100 缩放后 160×160 (sx=1.6, sy=1.6) 双线性插值

2. 图像旋转

绕原点逆时针旋转 θ 角度:
x' = x·cosθ - y·sinθ,   y' = x·sinθ + y·cosθ。
实际以图像中心为旋转点,需配合平移操作。

0° 30° 绕中心旋转

3. 图像平移

将图像沿 x 和 y 方向移动 (tx, ty):x' = x + tx, y' = y + ty。平移不改变像素值,仅改变位置。

原位置 平移后 tx=+100, ty=-20

4. 仿射变换

仿射变换是线性变换 + 平移,保持平行性和共线性。矩阵形式:

⎡ x' ⎤   ⎡ a  b  tx ⎤ ⎡ x ⎤
⎢ y' ⎥ = ⎢ c  d  ty ⎥ ⎢ y ⎥
⎣ 1  ⎦   ⎣ 0  0  1  ⎦ ⎣ 1 ⎦
        

OpenCV 中通过 cv2.getAffineTransform(src, dst) 计算矩阵,再用 cv2.warpAffine 执行。

原图 仿射变换 平行线保持平行

5. 透视变换

透视变换(投影变换)提供更大的自由度,可模拟相机视角变化。矩阵为 3×3,共 8 个自由度:

⎡ x' ⎤   ⎡ h11  h12  h13 ⎤ ⎡ x ⎤
⎢ y' ⎥ = ⎢ h21  h22  h23 ⎥ ⎢ y ⎥
⎣ w' ⎦   ⎣ h31  h32  1   ⎦ ⎣ 1 ⎦
        

最终像素坐标 (x'/w', y'/w')。OpenCV 使用 cv2.getPerspectiveTransform 和 cv2.warpPerspective。

原图 透视变换 平行线不再保持平行

6. Python 实现示例 (OpenCV)

核心函数速查
import cv2
import numpy as np

img = cv2.imread('input.jpg')
h, w = img.shape[:2]

# 缩放
resized = cv2.resize(img, (400, 300), interpolation=cv2.INTER_LINEAR)

# 旋转 (绕中心)
M_rot = cv2.getRotationMatrix2D((w//2, h//2), 45, 1.0)
rotated = cv2.warpAffine(img, M_rot, (w, h))

# 平移
M_trans = np.float32([[1, 0, 50], [0, 1, 30]])
translated = cv2.warpAffine(img, M_trans, (w, h))

# 仿射变换
src_pts = np.float32([[0,0], [w-1,0], [0,h-1]])
dst_pts = np.float32([[30,20], [w-50,10], [40,h-30]])
M_affine = cv2.getAffineTransform(src_pts, dst_pts)
affined = cv2.warpAffine(img, M_affine, (w, h))

# 透视变换
src_quad = np.float32([[0,0], [w-1,0], [w-1,h-1], [0,h-1]])
dst_quad = np.float32([[50,30], [w-40,20], [w-60,h-50], [40,h-40]])
M_persp = cv2.getPerspectiveTransform(src_quad, dst_quad)
perspected = cv2.warpPerspective(img, M_persp, (w, h))
        

7. 变换对比总结