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

新手上路,请多包涵

想象一下我有这些图片:

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

我希望左边的图像像中间的图像一样旋转,而不是右边的图像。我如何使用 Python 和 OpenCV 执行此操作。我查看了 getRotationMatrix2DwarpAffine 但是有关它的示例将我的图像转换为正确的图像。

原文由 Fosheus Badabu 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
1 个回答

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

在 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

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

原文由 en_lorithai 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏