目標檢測數據增強,旋轉方法


 

# 旋轉
  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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM