图像旋转矩阵
时间: 2025-03-31 22:07:02 浏览: 28
### 图像旋转的变换矩阵及其计算方式
在图像处理领域,图像旋转是一种常见的几何变换操作。为了实现这一功能,通常会利用 **二维旋转变换矩阵** 来完成。
#### 1. 基本理论
对于一个二维平面上的点 \((x, y)\),如果要将其绕着原点逆时针旋转角度\(\theta\),可以使用如下形式的旋转矩阵 \(R\) 进行描述:
\[ R =
\begin{bmatrix}
\cos{\theta} & -\sin{\theta}\\
\sin{\theta} & \cos{\theta}
\end{bmatrix} \]
经过该矩阵作用后的点的新位置可以通过下述公式得到[^3]:
\[
\begin{bmatrix}
x'\\y'
\end{bmatrix} =
\begin{bmatrix}
\cos{\theta} & -\sin{\theta}\\
\sin{\theta} & \cos{\theta}
\end{bmatrix}
\cdot
\begin{bmatrix}
x \\ y
\end{bmatrix}.
\]
其中,\( (x', y') \) 是原始点 \( (x, y) \) 经过旋转之后的位置。
#### 2. 实现方法
以下是基于 Python 和 OpenCV 的具体实现代码示例:
```python
import cv2
import numpy as np
def rotate_image(image, angle):
"""
对输入图片进行指定角度的旋转
参数:
image: 输入的numpy数组类型的图像.
angle: 顺时针方向的角度值(单位为度).
返回:
rotated: 旋转后的图像.
"""
height, width = image.shape[:2]
center = (width / 2, height / 2)
rotation_matrix = cv2.getRotationMatrix2D(center, angle, scale=1.0)
cos_val = np.cos(np.radians(angle))
sin_val = np.sin(np.radians(angle))
abs_cos = abs(rotation_matrix[0, 0])
abs_sin = abs(rotation_matrix[0, 1])
bound_w = int(height * abs_sin + width * abs_cos)
bound_h = int(height * abs_cos + width * abs_sin)
rotation_matrix[0, 2] += bound_w/2 - center[0]
rotation_matrix[1, 2] += bound_h/2 - center[1]
rotated = cv2.warpAffine(
src=image,
M=rotation_matrix,
dsize=(bound_w, bound_h),
flags=cv2.INTER_LINEAR,
borderMode=cv2.BORDER_CONSTANT,
borderValue=(255, 255, 255)
)
return rotated
# 测试函数
image_path = 'example.jpg'
img = cv2.imread(image_path)
rotated_img = rotate_image(img, 45) # 将图像顺时针旋转45°
cv2.imwrite('rotated_example.jpg', rotated_img)
```
上述代码片段展示了如何创建并应用一个旋转矩阵到给定的图像上[^1]。
#### 3. 关键注意事项
- 如果需要围绕某个特定中心而非默认的图像中心执行旋转,则需调整 `getRotationMatrix2D` 函数中的参数。
- 当涉及到更复杂的仿射变换或者透视变换时,可能还需要考虑额外的因素如缩放和平移等[^2]。
阅读全文
相关推荐

















