opencv旋转矩阵
时间: 2025-02-05 18:01:32 浏览: 34
### OpenCV 中使用旋转矩阵进行图像变换
在 OpenCV 中,通过 `cv2.getRotationMatrix2D` 获取旋转矩阵并应用此矩阵执行仿射变换是实现图像旋转的标准方法。具体来说:
- **获取旋转矩阵**:函数 `cv2.getRotationMatrix2D(center, angle, scale)` 接受三个参数——旋转中心坐标 `(centerX, centerY)`、旋转角度 `angle`(正值表示逆时针方向),以及缩放因子 `scale`[^2]。
- **应用旋转矩阵**:得到的旋转矩阵随后被传递给 `cv2.warpAffine()` 函数,后者负责基于所提供的变换矩阵对输入图像实施几何变换[^3]。
下面是一个完整的 Python 代码示例,展示了如何利用上述两个函数完成图像的旋转变换:
```python
import cv2
import numpy as np
def rotate_image(image_path, output_path, rotation_angle_degrees=45):
# 加载原始图片
image = cv2.imread(image_path)
# 定义旋转中心 (宽度的一半, 高度的一半),即图像中心点
height, width = image.shape[:2]
center_of_rotation = (width / 2, height / 2)
# 创建旋转矩阵 M
rotation_matrix = cv2.getRotationMatrix2D(
center=center_of_rotation,
angle=rotation_angle_degrees,
scale=1.0
)
# 应用旋转矩阵到原图上
rotated_image = cv2.warpAffine(
src=image,
M=rotation_matrix,
dsize=(width, height)
)
# 将结果保存至指定路径
cv2.imwrite(output_path, rotated_image)
if __name__ == "__main__":
input_img = "path/to/input/image.jpg"
result_img = "path/to/output/rotated_image.jpg"
rotate_image(input_img, result_img)
```
这段脚本定义了一个名为 `rotate_image` 的辅助函数,接受源文件位置、目标存储地址及期望的角度作为参数;内部逻辑遵循前述描述的过程完成了图像读取、构建旋转矩阵、调用 `warpAffine` 执行实际转换,并最终写出修改后的版本[^4]。
阅读全文
相关推荐


















