目标检测数据增强,旋转方法

 

# 旋转
 def _rotate_img_bbox(self, img, bboxes, angle=5, scale=1.):
 '''
  参考:https://blog.csdn.net/u014540717/article/details/53301195crop_rate
  输入:
  img:图像array,(h,w,c)
  bboxes:该图像包含的所有boundingboxs,一个list,每个元素为[x_min, y_min, x_max, y_max],要确保是数值
  angle:旋转角度
  scale:默认1
  输出:
  rot_img:旋转后的图像array
  rot_bboxes:旋转后的boundingbox坐标list
  '''
 #---------------------- 旋转图像 ----------------------
 w = img.shape[1]
 h = img.shape[0]
 # 角度变弧度
 rangle = np.deg2rad(angle) # angle in radians
 # now calculate new image width and height
 nw = (abs(np.sin(rangle)*h) + abs(np.cos(rangle)*w))*scale
 nh = (abs(np.cos(rangle)*h) + abs(np.sin(rangle)*w))*scale
 # ask OpenCV for the rotation matrix
 rot_mat = cv2.getRotationMatrix2D((nw*0.5, nh*0.5), angle, scale)
 # calculate the move from the old center to the new center combined
 # with the rotation
 rot_move = np.dot(rot_mat, np.array([(nw-w)*0.5, (nh-h)*0.5,0]))
 # the move only affects the translation, so update the translation
 # part of the transform
 rot_mat[0,2] += rot_move[0]
 rot_mat[1,2] += rot_move[1]
 # 仿射变换
 rot_img = cv2.warpAffine(img, rot_mat, (int(math.ceil(nw)), int(math.ceil(nh))), flags=cv2.INTER_LANCZOS4)
  
 #---------------------- 矫正bbox坐标 ----------------------
 # rot_mat是最终的旋转矩阵
 # 获取原始bbox的四个中点,然后将这四个点转换到旋转后的坐标系下
 rot_bboxes = list()
 for bbox in bboxes:
 xmin = bbox[0]
 ymin = bbox[1]
 xmax = bbox[2]
 ymax = bbox[3]
 point1 = np.dot(rot_mat, np.array([(xmin+xmax)/2, ymin, 1]))
 point2 = np.dot(rot_mat, np.array([xmax, (ymin+ymax)/2, 1]))
 point3 = np.dot(rot_mat, np.array([(xmin+xmax)/2, ymax, 1]))
 point4 = np.dot(rot_mat, np.array([xmin, (ymin+ymax)/2, 1]))
 # 合并np.array
 concat = np.vstack((point1, point2, point3, point4))
 # 改变array类型
 concat = concat.astype(np.int32)
 # 得到旋转后的坐标
 rx, ry, rw, rh = cv2.boundingRect(concat)
 rx_min = rx
 ry_min = ry
 rx_max = rx+rw
 ry_max = ry+rh
 # 加入list中
 rot_bboxes.append([rx_min, ry_min, rx_max, ry_max])
  
 return rot_img, rot_bboxes

 

参考链接:https://github.com/maozezhong/CV_ToolBox/blob/master/DataAugForObjectDetection/DataAugmentForObejctDetection.py

转载于:https://www.cnblogs.com/walktosee/p/10374820.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值