strong_augment.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. import random
  2. import cv2
  3. import numpy as np
  4. from .yolo_augment import random_perspective
  5. # ------------------------- Strong augmentations -------------------------
  6. ## Mosaic Augmentation
  7. class MosaicAugment(object):
  8. def __init__(self,
  9. img_size,
  10. affine_params,
  11. is_train=False,
  12. ) -> None:
  13. self.img_size = img_size
  14. self.is_train = is_train
  15. self.affine_params = affine_params
  16. def __call__(self, image_list, target_list):
  17. assert len(image_list) == 4
  18. # mosaic center
  19. yc, xc = [int(random.uniform(-x, 2*self.img_size + x)) for x in [-self.img_size // 2, -self.img_size // 2]]
  20. mosaic_bboxes = []
  21. mosaic_labels = []
  22. mosaic_img = np.zeros([self.img_size*2, self.img_size*2, image_list[0].shape[2]], dtype=np.uint8)
  23. for i in range(4):
  24. img_i, target_i = image_list[i], target_list[i]
  25. bboxes_i = target_i["boxes"]
  26. labels_i = target_i["labels"]
  27. orig_h, orig_w, _ = img_i.shape
  28. # ------------------ Keep ratio Resize ------------------
  29. r = self.img_size / max(orig_h, orig_w)
  30. if r != 1:
  31. interp = cv2.INTER_LINEAR if (self.is_train or r > 1) else cv2.INTER_AREA
  32. img_i = cv2.resize(img_i, (int(orig_w * r), int(orig_h * r)), interpolation=interp)
  33. h, w, _ = img_i.shape
  34. # ------------------ Create mosaic image ------------------
  35. ## Place image in mosaic image
  36. if i == 0: # top left
  37. x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image)
  38. x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image)
  39. elif i == 1: # top right
  40. x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, self.img_size * 2), yc
  41. x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h
  42. elif i == 2: # bottom left
  43. x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(self.img_size * 2, yc + h)
  44. x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h)
  45. elif i == 3: # bottom right
  46. x1a, y1a, x2a, y2a = xc, yc, min(xc + w, self.img_size * 2), min(self.img_size * 2, yc + h)
  47. x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)
  48. mosaic_img[y1a:y2a, x1a:x2a] = img_i[y1b:y2b, x1b:x2b]
  49. padw = x1a - x1b
  50. padh = y1a - y1b
  51. ## Mosaic target
  52. bboxes_i_ = bboxes_i.copy()
  53. if len(bboxes_i) > 0:
  54. # a valid target, and modify it.
  55. bboxes_i_[:, 0] = (w * bboxes_i[:, 0] / orig_w + padw)
  56. bboxes_i_[:, 1] = (h * bboxes_i[:, 1] / orig_h + padh)
  57. bboxes_i_[:, 2] = (w * bboxes_i[:, 2] / orig_w + padw)
  58. bboxes_i_[:, 3] = (h * bboxes_i[:, 3] / orig_h + padh)
  59. mosaic_bboxes.append(bboxes_i_)
  60. mosaic_labels.append(labels_i)
  61. if len(mosaic_bboxes) == 0:
  62. mosaic_bboxes = np.array([]).reshape(-1, 4)
  63. mosaic_labels = np.array([]).reshape(-1)
  64. else:
  65. mosaic_bboxes = np.concatenate(mosaic_bboxes)
  66. mosaic_labels = np.concatenate(mosaic_labels)
  67. # clip
  68. mosaic_bboxes = mosaic_bboxes.clip(0, self.img_size * 2)
  69. # ----------------------- Random perspective -----------------------
  70. mosaic_targets = np.concatenate([mosaic_labels[..., None], mosaic_bboxes], axis=-1)
  71. mosaic_img, mosaic_targets = random_perspective(
  72. mosaic_img,
  73. mosaic_targets,
  74. self.affine_params['degrees'],
  75. translate = self.affine_params['translate'],
  76. scale = self.affine_params['scale'],
  77. shear = self.affine_params['shear'],
  78. perspective = self.affine_params['perspective'],
  79. border = [-self.img_size//2, -self.img_size//2]
  80. )
  81. # target
  82. mosaic_target = {
  83. "boxes": mosaic_targets[..., 1:],
  84. "labels": mosaic_targets[..., 0],
  85. }
  86. return mosaic_img, mosaic_target
  87. ## Mixup Augmentation
  88. class MixupAugment(object):
  89. def __init__(self, img_size) -> None:
  90. self.img_size = img_size
  91. def yolox_mixup_augment(self, origin_image, origin_target, new_image, new_target):
  92. jit_factor = random.uniform(0.5, 1.5)
  93. FLIP = random.uniform(0, 1) > 0.5
  94. # resize new image
  95. orig_h, orig_w = new_image.shape[:2]
  96. cp_scale_ratio = self.img_size / max(orig_h, orig_w)
  97. if cp_scale_ratio != 1:
  98. interp = cv2.INTER_LINEAR if cp_scale_ratio > 1 else cv2.INTER_AREA
  99. resized_new_img = cv2.resize(
  100. new_image, (int(orig_w * cp_scale_ratio), int(orig_h * cp_scale_ratio)), interpolation=interp)
  101. else:
  102. resized_new_img = new_image
  103. # pad new image
  104. cp_img = np.ones([self.img_size, self.img_size, new_image.shape[2]], dtype=np.uint8) * 114
  105. new_shape = (resized_new_img.shape[1], resized_new_img.shape[0])
  106. cp_img[:new_shape[1], :new_shape[0]] = resized_new_img
  107. # resize padded new image
  108. cp_img_h, cp_img_w = cp_img.shape[:2]
  109. cp_new_shape = (int(cp_img_w * jit_factor),
  110. int(cp_img_h * jit_factor))
  111. cp_img = cv2.resize(cp_img, (cp_new_shape[0], cp_new_shape[1]))
  112. cp_scale_ratio *= jit_factor
  113. # flip new image
  114. if FLIP:
  115. cp_img = cp_img[:, ::-1, :]
  116. # pad image
  117. origin_h, origin_w = cp_img.shape[:2]
  118. target_h, target_w = origin_image.shape[:2]
  119. padded_img = np.zeros(
  120. (max(origin_h, target_h), max(origin_w, target_w), 3), dtype=np.uint8
  121. )
  122. padded_img[:origin_h, :origin_w] = cp_img
  123. # crop padded image
  124. x_offset, y_offset = 0, 0
  125. if padded_img.shape[0] > target_h:
  126. y_offset = random.randint(0, padded_img.shape[0] - target_h - 1)
  127. if padded_img.shape[1] > target_w:
  128. x_offset = random.randint(0, padded_img.shape[1] - target_w - 1)
  129. padded_cropped_img = padded_img[
  130. y_offset: y_offset + target_h, x_offset: x_offset + target_w
  131. ]
  132. # process target
  133. new_boxes = new_target["boxes"]
  134. new_labels = new_target["labels"]
  135. new_boxes[:, 0::2] = np.clip(new_boxes[:, 0::2] * cp_scale_ratio, 0, origin_w)
  136. new_boxes[:, 1::2] = np.clip(new_boxes[:, 1::2] * cp_scale_ratio, 0, origin_h)
  137. if FLIP:
  138. new_boxes[:, 0::2] = (
  139. origin_w - new_boxes[:, 0::2][:, ::-1]
  140. )
  141. new_boxes[:, 0::2] = np.clip(
  142. new_boxes[:, 0::2] - x_offset, 0, target_w
  143. )
  144. new_boxes[:, 1::2] = np.clip(
  145. new_boxes[:, 1::2] - y_offset, 0, target_h
  146. )
  147. # mixup target
  148. mixup_boxes = np.concatenate([new_boxes, origin_target['boxes']], axis=0)
  149. mixup_labels = np.concatenate([new_labels, origin_target['labels']], axis=0)
  150. mixup_target = {
  151. 'boxes': mixup_boxes,
  152. 'labels': mixup_labels
  153. }
  154. # mixup images
  155. origin_image = origin_image.astype(np.float32)
  156. origin_image = 0.5 * origin_image + 0.5 * padded_cropped_img.astype(np.float32)
  157. return origin_image.astype(np.uint8), mixup_target
  158. def yolo_mixup_augment(self, origin_image, origin_target, new_image, new_target):
  159. if origin_image.shape[:2] != new_image.shape[:2]:
  160. img_size = max(new_image.shape[:2])
  161. # origin_image is not a mosaic image
  162. orig_h, orig_w = origin_image.shape[:2]
  163. scale_ratio = img_size / max(orig_h, orig_w)
  164. if scale_ratio != 1:
  165. interp = cv2.INTER_LINEAR if scale_ratio > 1 else cv2.INTER_AREA
  166. resize_size = (int(orig_w * scale_ratio), int(orig_h * scale_ratio))
  167. origin_image = cv2.resize(origin_image, resize_size, interpolation=interp)
  168. # pad new image
  169. pad_origin_image = np.zeros([img_size, img_size, origin_image.shape[2]], dtype=np.uint8)
  170. pad_origin_image[:resize_size[1], :resize_size[0]] = origin_image
  171. origin_image = pad_origin_image.copy()
  172. del pad_origin_image
  173. r = np.random.beta(32.0, 32.0)
  174. mixup_image = r * origin_image.astype(np.float32) + \
  175. (1.0 - r)* new_image.astype(np.float32)
  176. mixup_image = mixup_image.astype(np.uint8)
  177. cls_labels = new_target["labels"].copy()
  178. box_labels = new_target["boxes"].copy()
  179. mixup_bboxes = np.concatenate([origin_target["boxes"], box_labels], axis=0)
  180. mixup_labels = np.concatenate([origin_target["labels"], cls_labels], axis=0)
  181. mixup_target = {
  182. "boxes": mixup_bboxes,
  183. "labels": mixup_labels,
  184. }
  185. return mixup_image, mixup_target
  186. def __call__(self, origin_image, origin_target, new_image, new_target, yolox_style=False):
  187. if yolox_style:
  188. return self.yolox_mixup_augment(origin_image, origin_target, new_image, new_target)
  189. else:
  190. return self.yolo_mixup_augment(origin_image, origin_target, new_image, new_target)