目标检测数据增强——旋转

在图像识别任务中,图像旋转是一种比较常用的数据增强方法。结合cv2cv2.getRotationMatrix2D()cv2.warpAffine()就可以实现图像的旋转。

对于像目标检测这类带标注框的图像识别任务,不仅要对图像旋转,还要知道标注框被旋转到哪里了,所以还要计算坐标点的变化。下面的函数实现了:

  1. 给定角度,旋转图像。
  2. 自动调整图像尺寸,保证原图像的内容不会被旋转到图像外。
  3. 计算原图中坐标点points在旋转后的图像中的位置坐标。
import numpy as np
import cv2
from math import fabs, sin, radians, cos


def rotate_with_points(image, degree, points, fill=0):
    """逆时针旋转图像image角度degree,并计算原图中坐标点points在旋转后的图像中的位置坐标.
    Args:
        image: 图像数组
        degree: 旋转角度
        points (np.array): ([x, ...], [y, ...]), shape=(2, m),原图上的坐标点
        fill: 旋转图像后,空白处填充的颜色,默认填0(黑色)
    Return:
        new_img: 旋转后的图像
        new_pts: 原图中坐标点points在旋转后的图像中的位置坐标
    """
    h, w = image.shape

    new_h = int(w * fabs(sin(radians(degree))) + h * fabs(cos(radians(degree))))
    new_w = int(h * fabs(sin(radians(degree))) + w * fabs(cos(radians(degree))))

    rtt_mat = cv2.getRotationMatrix2D((w / 2, h / 2), degree, 1)

    rtt_mat[0, 2] += (new_w - w) / 2
    rtt_mat[1, 2] += (new_h - h) / 2

    new_img = cv2.warpAffine(image, rtt_mat, (new_w, new_h), borderValue=fill)

    a = np.array([rtt_mat[0][: 2], rtt_mat[1][: 2]])
    b = np.array([[rtt_mat[0][2]], [rtt_mat[1][2]]])

    new_pts = np.round(np.dot(a, points.astype(np.float32)) + b).astype(np.int64)
    return new_img, new_pts
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值