在图像旋转过程中保持图像尺寸不变,可以使用以下代码示例来实现:
import cv2
import numpy as np
def rotate_image(image, angle):
height, width = image.shape[:2]
image_center = (width / 2, height / 2)
rotation_matrix = cv2.getRotationMatrix2D(image_center, angle, 1)
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 - image_center[0]
rotation_matrix[1, 2] += bound_h / 2 - image_center[1]
rotated_image = cv2.warpAffine(image, rotation_matrix, (bound_w, bound_h), borderValue=(255, 255, 255))
return rotated_image
# 读取图像
image = cv2.imread('image.jpg')
# 指定旋转角度(正值为顺时针,负值为逆时针)
angle = 45
# 调用函数进行旋转
rotated_image = rotate_image(image, angle)
# 显示原始图像和旋转后的图像
cv2.imshow('Original Image', image)
cv2.imshow('Rotated Image', rotated_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
以上代码中,rotate_image函数接受一个图像和旋转角度作为输入,并返回旋转后的图像。它使用OpenCV的getRotationMatrix2D方法来获得旋转矩阵,并使用warpAffine方法对图像进行旋转。在旋转过程中,根据旋转后的图像尺寸来调整旋转矩阵和边界值,以保持图像尺寸不变。最后,使用imshow方法显示原始图像和旋转后的图像。
请注意,上述示例中的图像文件名为image.jpg,你可以将其替换为你想要旋转的图像文件名。