写真を回転する 2 つの方法

これら 2 つの方法は、画像を回転するときにいくつかの異なる効果を生み出す可能性があります。

rotate_image_new() 回転された画像には回転前のコンテンツが完全に含まれており、パディング境界は可能な限り小さくなります。

rotate_image() は元の画像のサイズを維持し、パディング オプションに応じて境界線を白で埋めるかどうかを決定します。if_fill_white パラメータが True の場合、塗りつぶしの境界線は白になります。それ以外の場合、境界線は元の画像の値を保持します。この方法では画像をより速く回転できますが、回転された画像に余分な空白が含まれたり、画像情報の一部が失われる可能性があります。


def rotate_image_new(image, degree):
    '''
    旋转图片角度
    '''
    from math import *
    # dividing height and width by 2 to get the center of the image
    height, width = image.shape[:2]

    heightNew = int(width * fabs(sin(radians(degree))) + height * fabs(cos(radians(degree))))
    widthNew = int(height * fabs(sin(radians(degree))) + width * fabs(cos(radians(degree))))

    matRotation = cv2.getRotationMatrix2D((width / 2, height / 2), degree, 1)
    matRotation[0, 2] += (widthNew - width) / 2  # 重点在这步,目前不懂为什么加这步
    matRotation[1, 2] += (heightNew - height) / 2  # 重点在这步

    imgRotation = cv2.warpAffine(image, matRotation, (widthNew, heightNew), borderValue=(255, 255, 255))

    return imgRotation

def rotate_image( image, angle,if_fill_white = False):
    '''
    顺时针旋转
    '''
    # dividing height and width by 2 to get the center of the image
    height, width = image.shape[:2]
    # get the center coordinates of the image to create the 2D rotation matrix
    center = (width / 2, height / 2)

    # using cv2.getRotationMatrix2D() to get the rotation matrix
    rotate_matrix = cv2.getRotationMatrix2D(center=center, angle=angle, scale=1)

    # rotate the image using cv2.warpAffine
    if not if_fill_white:
        rotated_image = cv2.warpAffine(src=image, M=rotate_matrix, dsize=(width, height) )
    else:
        color = (255, 255) if len(image.shape)==2 else (255, 255,255)
        rotated_image = cv2.warpAffine(src=image, M=rotate_matrix, dsize=(width, height), borderValue=color)
    return rotated_image


おすすめ

転載: blog.csdn.net/weixin_38235865/article/details/132560980