在图像处理中,围绕中心点旋转图像是一个常见的需求。无论是为了数据增强、视觉效果,还是图像对齐,旋转图像都是一项基础且重要的操作。本文将详细介绍如何使用 OpenCV 实现围绕图像中心旋转的功能,并深入探讨其背后的数学原理。
一、旋转图像的基本概念
图像旋转是指将图像围绕一个指定的点(通常是图像中心)旋转一定角度。旋转后的图像尺寸可能会发生变化,以确保所有原始像素都能在旋转后的图像中显示。旋转过程中,需要考虑以下几点:
- 旋转中心:图像旋转的轴心点,通常为图像中心。
- 旋转角度:旋转的角度,通常以度为单位,正角度表示逆时针旋转。
- 新图像尺寸:旋转后图像的新宽度和高度,确保不丢失任何像素。
- 插值方法:用于填充旋转后图像中空白区域的像素值。
二、代码实现
import cv2
import numpy as np
import math
def rotate_about_center(src, angle_degrees, scale=1.0):
"""
Rotate an image around its center by a specified angle.
Parameters:
- src: numpy.ndarray
The input image to be rotated.
- angle_degrees: float
The rotation angle in degrees. Positive values indicate counter-clockwise rotation.
- scale: float, optional
The scaling factor. Default is 1.0 (no scaling).
Returns:
- numpy.ndarray
The rotated image.
"""
# 确保输入图像是有效的
if src is None:
raise ValueError("Input image is None")
# 获取图像的宽度和高度
image_height, image_width = src.shape[:2]
# 将角度转换为弧度
angle_radians = np.deg2rad(angle_degrees)
# 计算旋转后的新图像尺寸
new_width = (abs(np.sin(angle_radians) * image_height) + abs(np.cos(angle_radians) * image_width)) * scale
new_height = (abs(np.cos(angle_radians) * image_height) + abs(np.sin(angle_radians) * image_width)) * scale
# 计算旋转矩阵
# center 是旋转的中心点,位于新图像的中心
rotation_center = (new_width * 0.5, new_height * 0.5)
rotation_matrix = cv2.getRotationMatrix2D(rotation_center, angle_degrees, scale)
# 计算从旧中心到新中心的移动
translation = np.dot(rotation_matrix, np.array([(new_width - image_width) * 0.5, (new_height - image_height) * 0.5, 0]))
# 更新旋转矩阵的平移部分
rotation_matrix[0, 2] += translation[0]
rotation_matrix[1, 2] += translation[1]
# 应用旋转
rotated_img = cv2.warpAffine(src, rotation_matrix, (int(math.ceil(new_width)), int(math.ceil(new_height))),
borderValue=(255, 255, 255), flags=cv2.INTER_LANCZOS4)
return rotated_img
三、代码说明
1. 输入检查
- 检查输入图像是否为空,确保后续操作的有效性。
2. 获取图像尺寸
- 从输入图像中提取高度和宽度,用于后续计算。
3. 计算新图像尺寸
- 使用三角函数计算旋转后图像的新宽度和高度。旋转后的图像尺寸需要足够大,以容纳旋转后的所有像素。
4. 生成旋转矩阵
- 使用
cv2.getRotationMatrix2D
计算旋转矩阵。旋转中心是新图像的中心,旋转角度为输入的角度,缩放因子为scale
。
5. 计算平移量
- 计算从旧图像中心到新图像中心的偏移量。
- 使用
np.dot
将旋转矩阵应用到偏移量上,计算由于旋转引起的额外平移。 - 更新旋转矩阵的平移部分,以确保旋转后的图像正确放置在新图像的中心。
6. 应用旋转
- 使用
cv2.warpAffine
应用旋转矩阵,生成旋转后的图像。 - 设置边界填充颜色为白色,并使用高质量的插值方法(
cv2.INTER_LANCZOS4
)。
7. 示例用法
- 读取输入图像,调用
rotate_about_center
函数旋转图像,并显示和保存结果。
五、旋转结果 ,旋转45°,正数表示逆时针旋转,负数表示顺时针旋转