实现图像旋转

在这里插入图片描述

图像旋转原理

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

OpenCV中的图像旋转

OpenCV主要使用getRotationMatrix2D()来得到变换矩阵(getRotationMatrix2D的计算方式与上一节的推导一致,大家可以参看函数解释推导一下),再使用warpAffine()来实现图像旋转。代码如下

def rotate(image, angle, center=None, scale=1.0):
    # grab the dimensions of the image
    (h, w) = image.shape[:2]

    # if the center is None, initialize it as the center of
    # the image
    if center is None:
        center = (w // 2, h // 2)

    # perform the rotation
    M = cv2.getRotationMatrix2D(center, angle, scale)
    rotated = cv2.warpAffine(image, M, (w, h))

    # return the rotated image
    return rotated

现在我们来旋转一只小鸟。
在这里插入图片描述

使用OpenCV的方法旋转结果如下所示:
在这里插入图片描述
在这里插入图片描述
可以看到当旋转矩形涂向师,旋转后原图大量信息丢失了。在有些时候我们并不想要这种信息的丢失(比如在深度学习数据增强的时候)。

现在我改写一下上面的代码,来使矩形图片可以正确的旋转,不丢失信息。代码如下:

def rotate_bound(image, angle):
    # grab the dimensions of the image and then determine the
    # center
    (h, w) = image.shape[:2]
    (cX, cY) = (w / 2, h / 2)

    # grab the rotation matrix (applying the negative of the
    # angle to rotate clockwise), then grab the sine and cosine
    # (i.e., the rotation components of the matrix)
    M = cv2.getRotationMatrix2D((cX, cY), angle, 1.0)
    cos = np.abs(M[0, 0])
    sin = np.abs(M[0, 1])

    # compute the new bounding dimensions of the image
    nW = int((h * sin) + (w * cos))
    nH = int((h * cos) + (w * sin))

    # adjust the rotation matrix to take into account translation
    M[0, 2] += (nW / 2) - cX
    M[1, 2] += (nH / 2) - cY

    # perform the actual rotation and return the image
    return cv2.warpAffine(image, M, (nW, nH))

在计算出旋转变换矩阵M后,计算一下可以正常包含旋转后图像的外接矩形框的长和宽,然后计算外接矩形框的中心和原矩形框中心的距离,最后将旋转后的图像中心移到新的外接矩形框的中心。

结果如下:

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值