在 Python 中使用 OpenCV 旋转图像时调整大小问题

问题描述 投票:0回答:1

我目前正在从事一个图像处理项目,我需要旋转图像而不改变其原始大小。我使用 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 中的图像处理很陌生。如果您有替代解决方案,包括其他语言的方法,请分享。谢谢

numpy opencv image-processing rotation resize
1个回答
0
投票

该代码可以保持其原始图像大小。我用ImageJ验证了一下。 使用PIL等方法还可以旋转并保持原始尺寸的图像。

Original Image: 1280 x 1269

60-degree rotated image: 1738 x 1743 (include black background)

Actual rotated image size: 1280 x 1269

© www.soinside.com 2019 - 2024. All rights reserved.