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

Fos*_*abu 7 python opencv rotation

想象一下,我有这些图像:

载荷大小://i.stack.imgur.com/jjRfe.png

我希望左边的图像像中间的图像一样旋转,而不是正确的图像.我如何使用Python和OpenCV来做到这一点.我看了看getRotationMatrix2DwarpAffine,但关于它的例子变换我的形象是正确的.

en_*_*hai 16

这是迄今为止我发现的旋转图像同时避免裁剪图像的最佳解决方案.

在C++中的OpenCV中无需裁剪即可旋转图像

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
Run Code Online (Sandbox Code Playgroud)

当角度为90*n时,您可以添加检查以避免某些计算,但此功能将适用于任何角度.

  • 在 warpAffine 上使用“borderMode=”标志来控制边框的填充方式(如果结果中存在的话)。 (3认同)

Rya*_*Jay 10

如果您只关心numpy的90度旋转。这更容易,并且可以在opencv输入上使用:

import numpy as np
rotated_image = np.rot90(im)
Run Code Online (Sandbox Code Playgroud)

  • 您可以使用以下方法修复: np.ascontigiousarray(np.rot90(im)) 或: np.rot90(im).copy() (2认同)

mko*_*rbi 5

由于我不知道你的代码,我仍然会猜测使用该imutils.rotate_bound函数将解决问题.例如:rotate = imutils.rotate_bound(image, angle)