strong_augment.py 10 KB

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