OpenCV Python:旋转图像而不裁剪边

2024-06-02 07:12:36 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有这些图像:

ttps://i.stack.imgur.com/jjRfe.png

我希望从左开始的图像像中间的图像一样旋转,而不是右转。如何使用Python和OpenCV来实现这一点。我看了getRotationMatrix2DwarpAffine,但是关于它的例子将我的图像转换为正确的图像。


Tags: 图像opencv例子warpaffine右转getrotationmatrix2d
3条回答

这是目前为止我发现的最好的解决方案,可以在旋转图像的同时避免剪切图像。

Rotate an image without cropping in OpenCV in C++

import cv2

def rotate_image(mat, angle):
    """
    Rotates an image (angle in degrees) and expands image to avoid cropping
    """

    height, width = mat.shape[:2] # image shape has 3 dimensions
    image_center = (width/2, height/2) # getRotationMatrix2D needs coordinates in reverse order (width, height) compared to shape

    rotation_mat = cv2.getRotationMatrix2D(image_center, angle, 1.)

    # rotation calculates the cos and sin, taking absolutes of those.
    abs_cos = abs(rotation_mat[0,0]) 
    abs_sin = abs(rotation_mat[0,1])

    # find the new width and height bounds
    bound_w = int(height * abs_sin + width * abs_cos)
    bound_h = int(height * abs_cos + width * abs_sin)

    # subtract old image center (bringing image back to origo) and adding the new image center coordinates
    rotation_mat[0, 2] += bound_w/2 - image_center[0]
    rotation_mat[1, 2] += bound_h/2 - image_center[1]

    # rotate image with the new bounds and translated rotation matrix
    rotated_mat = cv2.warpAffine(mat, rotation_mat, (bound_w, bound_h))
    return rotated_mat

当角度为90*n时,可以添加检查以避免某些计算,但此函数将按原样适用于任何角度。

如果你只关心90度旋转。它更容易使用opencv输入:

import numpy as np
rotated_image = np.rot90(im)

由于我不知道您的代码,我仍然认为使用imutils.rotate_bound函数可以解决问题。E、 g.:rotate = imutils.rotate_bound(image, angle)

相关问题 更多 >