我目前正在从事一个图像处理项目,我需要旋转图像而不改变其原始大小。我使用 Python 和 OpenCV 库来完成此任务。但是,我遇到了一个问题,旋转的图像正在调整大小或变小,这不是我想要的行为。
import cv2
import numpy as np
def rotate_and_flip_image(image_path, angle):
image = cv2.imread(image_path)
if image is not None:
# Get the height and width of the image
height, width = image.shape[:2]
# Calculate the rotation matrix
rotation_matrix = cv2.getRotationMatrix2D((width / 2, height / 2), -angle, 1)
# Calculate the new dimensions of the rotated image to ensure it fits entirely
cos = np.abs(rotation_matrix[0, 0])
sin = np.abs(rotation_matrix[0, 1])
new_width = int(height * sin + width * cos)
new_height = int(height * cos + width * sin)
# Create a canvas with the new dimensions
canvas = np.zeros((new_height, new_width, 3), dtype=np.uint8)
# Rotate the image onto the canvas
rotated_image = cv2.warpAffine(image, rotation_matrix, (new_width, new_height))
# Flip the rotated image horizontally
flipped_image = cv2.flip(rotated_image, 0) # Use 0 for horizontal flip
# Save the rotated and flipped images
base_filename = os.path.splitext(os.path.basename(image_path))[0]
rotated_output_path = os.path.join(output_directory, f"{base_filename}_rotated_{angle}deg.jpg")
flipped_output_path = os.path.join(output_directory, f"{base_filename}_flipped_{angle}deg.jpg")
cv2.imwrite(rotated_output_path, rotated_image)
cv2.imwrite(flipped_output_path, flipped_image)
上面的代码旋转图像,同时不会导致图像的某些部分被裁剪。但是,在旋转过程中,图像似乎会调整大小或变小,这不是所需的行为。
注意:我对 Python 和 OpenCV 中的图像处理很陌生。如果您有替代解决方案,包括其他语言的方法,请分享。谢谢