yolov5_augment.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. import random
  2. import cv2
  3. import math
  4. import numpy as np
  5. import torch
  6. # ------------------------- Basic augmentations -------------------------
  7. ## Spatial transform
  8. def random_perspective(image,
  9. targets=(),
  10. degrees=10,
  11. translate=.1,
  12. scale=[0.1, 2.0],
  13. shear=10,
  14. perspective=0.0,
  15. border=(0, 0)):
  16. # torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(0.1, 0.1), scale=(0.9, 1.1), shear=(-10, 10))
  17. # targets = [cls, xyxy]
  18. height = image.shape[0] + border[0] * 2 # shape(h,w,c)
  19. width = image.shape[1] + border[1] * 2
  20. # Center
  21. C = np.eye(3)
  22. C[0, 2] = -image.shape[1] / 2 # x translation (pixels)
  23. C[1, 2] = -image.shape[0] / 2 # y translation (pixels)
  24. # Perspective
  25. P = np.eye(3)
  26. P[2, 0] = random.uniform(-perspective, perspective) # x perspective (about y)
  27. P[2, 1] = random.uniform(-perspective, perspective) # y perspective (about x)
  28. # Rotation and Scale
  29. R = np.eye(3)
  30. a = random.uniform(-degrees, degrees)
  31. # a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations
  32. s = random.uniform(scale[0], scale[1])
  33. # s = 2 ** random.uniform(-scale, scale)
  34. R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)
  35. # Shear
  36. S = np.eye(3)
  37. S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # x shear (deg)
  38. S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # y shear (deg)
  39. # Translation
  40. T = np.eye(3)
  41. T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * width # x translation (pixels)
  42. T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * height # y translation (pixels)
  43. # Combined rotation matrix
  44. M = T @ S @ R @ P @ C # order of operations (right to left) is IMPORTANT
  45. if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any(): # image changed
  46. if perspective:
  47. image = cv2.warpPerspective(image, M, dsize=(width, height), borderValue=(114, 114, 114))
  48. else: # affine
  49. image = cv2.warpAffine(image, M[:2], dsize=(width, height), borderValue=(114, 114, 114))
  50. # Transform label coordinates
  51. n = len(targets)
  52. if n:
  53. new = np.zeros((n, 4))
  54. # warp boxes
  55. xy = np.ones((n * 4, 3))
  56. xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1
  57. xy = xy @ M.T # transform
  58. xy = (xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]).reshape(n, 8) # perspective rescale or affine
  59. # create new boxes
  60. x = xy[:, [0, 2, 4, 6]]
  61. y = xy[:, [1, 3, 5, 7]]
  62. new = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T
  63. # clip
  64. new[:, [0, 2]] = new[:, [0, 2]].clip(0, width)
  65. new[:, [1, 3]] = new[:, [1, 3]].clip(0, height)
  66. targets[:, 1:5] = new
  67. return image, targets
  68. ## Color transform
  69. def augment_hsv(img, hgain=0.5, sgain=0.5, vgain=0.5):
  70. r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1 # random gains
  71. hue, sat, val = cv2.split(cv2.cvtColor(img, cv2.COLOR_BGR2HSV))
  72. dtype = img.dtype # uint8
  73. x = np.arange(0, 256, dtype=np.int16)
  74. lut_hue = ((x * r[0]) % 180).astype(dtype)
  75. lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)
  76. lut_val = np.clip(x * r[2], 0, 255).astype(dtype)
  77. img_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val))).astype(dtype)
  78. cv2.cvtColor(img_hsv, cv2.COLOR_HSV2BGR, dst=img) # no return needed
  79. # ------------------------- Strong augmentations -------------------------
  80. ## YOLOv5-Mosaic
  81. def yolov5_mosaic_augment(image_list, target_list, img_size, affine_params, is_train=False):
  82. assert len(image_list) == 4
  83. mosaic_img = np.ones([img_size*2, img_size*2, image_list[0].shape[2]], dtype=np.uint8) * 114
  84. # mosaic center
  85. yc, xc = [int(random.uniform(-x, 2*img_size + x)) for x in [-img_size // 2, -img_size // 2]]
  86. # yc = xc = self.img_size
  87. mosaic_bboxes = []
  88. mosaic_labels = []
  89. for i in range(4):
  90. img_i, target_i = image_list[i], target_list[i]
  91. bboxes_i = target_i["boxes"]
  92. labels_i = target_i["labels"]
  93. orig_h, orig_w, _ = img_i.shape
  94. # resize
  95. r = img_size / max(orig_h, orig_w)
  96. if r != 1:
  97. interp = cv2.INTER_LINEAR if (is_train or r > 1) else cv2.INTER_AREA
  98. img_i = cv2.resize(img_i, (int(orig_w * r), int(orig_h * r)), interpolation=interp)
  99. h, w, _ = img_i.shape
  100. # place img in img4
  101. if i == 0: # top left
  102. x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image)
  103. x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image)
  104. elif i == 1: # top right
  105. x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, img_size * 2), yc
  106. x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h
  107. elif i == 2: # bottom left
  108. x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(img_size * 2, yc + h)
  109. x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h)
  110. elif i == 3: # bottom right
  111. x1a, y1a, x2a, y2a = xc, yc, min(xc + w, img_size * 2), min(img_size * 2, yc + h)
  112. x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)
  113. mosaic_img[y1a:y2a, x1a:x2a] = img_i[y1b:y2b, x1b:x2b]
  114. padw = x1a - x1b
  115. padh = y1a - y1b
  116. # labels
  117. bboxes_i_ = bboxes_i.copy()
  118. if len(bboxes_i) > 0:
  119. # a valid target, and modify it.
  120. bboxes_i_[:, 0] = (w * bboxes_i[:, 0] / orig_w + padw)
  121. bboxes_i_[:, 1] = (h * bboxes_i[:, 1] / orig_h + padh)
  122. bboxes_i_[:, 2] = (w * bboxes_i[:, 2] / orig_w + padw)
  123. bboxes_i_[:, 3] = (h * bboxes_i[:, 3] / orig_h + padh)
  124. mosaic_bboxes.append(bboxes_i_)
  125. mosaic_labels.append(labels_i)
  126. if len(mosaic_bboxes) == 0:
  127. mosaic_bboxes = np.array([]).reshape(-1, 4)
  128. mosaic_labels = np.array([]).reshape(-1)
  129. else:
  130. mosaic_bboxes = np.concatenate(mosaic_bboxes)
  131. mosaic_labels = np.concatenate(mosaic_labels)
  132. # clip
  133. mosaic_bboxes = mosaic_bboxes.clip(0, img_size * 2)
  134. # random perspective
  135. mosaic_targets = np.concatenate([mosaic_labels[..., None], mosaic_bboxes], axis=-1)
  136. mosaic_img, mosaic_targets = random_perspective(
  137. mosaic_img,
  138. mosaic_targets,
  139. affine_params['degrees'],
  140. translate=affine_params['translate'],
  141. scale=affine_params['scale'],
  142. shear=affine_params['shear'],
  143. perspective=affine_params['perspective'],
  144. border=[-img_size//2, -img_size//2]
  145. )
  146. # target
  147. mosaic_target = {
  148. "boxes": mosaic_targets[..., 1:],
  149. "labels": mosaic_targets[..., 0],
  150. "orig_size": [img_size, img_size]
  151. }
  152. return mosaic_img, mosaic_target
  153. ## YOLOv5-Mixup
  154. def yolov5_mixup_augment(origin_image, origin_target, new_image, new_target):
  155. if origin_image.shape[:2] != new_image.shape[:2]:
  156. img_size = max(new_image.shape[:2])
  157. # origin_image is not a mosaic image
  158. orig_h, orig_w = origin_image.shape[:2]
  159. scale_ratio = img_size / max(orig_h, orig_w)
  160. if scale_ratio != 1:
  161. interp = cv2.INTER_LINEAR if scale_ratio > 1 else cv2.INTER_AREA
  162. resize_size = (int(orig_w * scale_ratio), int(orig_h * scale_ratio))
  163. origin_image = cv2.resize(origin_image, resize_size, interpolation=interp)
  164. # pad new image
  165. pad_origin_image = np.ones([img_size, img_size, origin_image.shape[2]], dtype=np.uint8) * 114
  166. pad_origin_image[:resize_size[1], :resize_size[0]] = origin_image
  167. origin_image = pad_origin_image.copy()
  168. del pad_origin_image
  169. r = np.random.beta(32.0, 32.0) # mixup ratio, alpha=beta=32.0
  170. mixup_image = r * origin_image.astype(np.float32) + \
  171. (1.0 - r)* new_image.astype(np.float32)
  172. mixup_image = mixup_image.astype(np.uint8)
  173. cls_labels = new_target["labels"].copy()
  174. box_labels = new_target["boxes"].copy()
  175. mixup_bboxes = np.concatenate([origin_target["boxes"], box_labels], axis=0)
  176. mixup_labels = np.concatenate([origin_target["labels"], cls_labels], axis=0)
  177. mixup_target = {
  178. "boxes": mixup_bboxes,
  179. "labels": mixup_labels,
  180. 'orig_size': mixup_image.shape[:2]
  181. }
  182. return mixup_image, mixup_target
  183. ## YOLOX-Mixup
  184. def yolox_mixup_augment(origin_img, origin_target, new_img, new_target, img_size, mixup_scale):
  185. jit_factor = random.uniform(*mixup_scale)
  186. FLIP = random.uniform(0, 1) > 0.5
  187. # resize new image
  188. orig_h, orig_w = new_img.shape[:2]
  189. cp_scale_ratio = img_size / max(orig_h, orig_w)
  190. if cp_scale_ratio != 1:
  191. interp = cv2.INTER_LINEAR if cp_scale_ratio > 1 else cv2.INTER_AREA
  192. resized_new_img = cv2.resize(
  193. new_img, (int(orig_w * cp_scale_ratio), int(orig_h * cp_scale_ratio)), interpolation=interp)
  194. else:
  195. resized_new_img = new_img
  196. # pad new image
  197. cp_img = np.ones([img_size, img_size, new_img.shape[2]], dtype=np.uint8) * 114
  198. new_shape = (resized_new_img.shape[1], resized_new_img.shape[0])
  199. cp_img[:new_shape[1], :new_shape[0]] = resized_new_img
  200. # resize padded new image
  201. cp_img_h, cp_img_w = cp_img.shape[:2]
  202. cp_new_shape = (int(cp_img_w * jit_factor),
  203. int(cp_img_h * jit_factor))
  204. cp_img = cv2.resize(cp_img, (cp_new_shape[0], cp_new_shape[1]))
  205. cp_scale_ratio *= jit_factor
  206. # flip new image
  207. if FLIP:
  208. cp_img = cp_img[:, ::-1, :]
  209. # pad image
  210. origin_h, origin_w = cp_img.shape[:2]
  211. target_h, target_w = origin_img.shape[:2]
  212. padded_img = np.zeros(
  213. (max(origin_h, target_h), max(origin_w, target_w), 3), dtype=np.uint8
  214. )
  215. padded_img[:origin_h, :origin_w] = cp_img
  216. # crop padded image
  217. x_offset, y_offset = 0, 0
  218. if padded_img.shape[0] > target_h:
  219. y_offset = random.randint(0, padded_img.shape[0] - target_h - 1)
  220. if padded_img.shape[1] > target_w:
  221. x_offset = random.randint(0, padded_img.shape[1] - target_w - 1)
  222. padded_cropped_img = padded_img[
  223. y_offset: y_offset + target_h, x_offset: x_offset + target_w
  224. ]
  225. # process target
  226. new_boxes = new_target["boxes"]
  227. new_labels = new_target["labels"]
  228. new_boxes[:, 0::2] = np.clip(new_boxes[:, 0::2] * cp_scale_ratio, 0, origin_w)
  229. new_boxes[:, 1::2] = np.clip(new_boxes[:, 1::2] * cp_scale_ratio, 0, origin_h)
  230. if FLIP:
  231. new_boxes[:, 0::2] = (
  232. origin_w - new_boxes[:, 0::2][:, ::-1]
  233. )
  234. new_boxes[:, 0::2] = np.clip(
  235. new_boxes[:, 0::2] - x_offset, 0, target_w
  236. )
  237. new_boxes[:, 1::2] = np.clip(
  238. new_boxes[:, 1::2] - y_offset, 0, target_h
  239. )
  240. # mixup target
  241. mixup_boxes = np.concatenate([new_boxes, origin_target['boxes']], axis=0)
  242. mixup_labels = np.concatenate([new_labels, origin_target['labels']], axis=0)
  243. mixup_target = {
  244. 'boxes': mixup_boxes,
  245. 'labels': mixup_labels
  246. }
  247. # mixup images
  248. origin_img = origin_img.astype(np.float32)
  249. origin_img = 0.5 * origin_img + 0.5 * padded_cropped_img.astype(np.float32)
  250. return origin_img.astype(np.uint8), mixup_target
  251. # ------------------------- Preprocessers -------------------------
  252. ## YOLOv5-style Transform for Train
  253. class YOLOv5Augmentation(object):
  254. def __init__(self,
  255. img_size=640,
  256. trans_config=None):
  257. self.trans_config = trans_config
  258. self.img_size = img_size
  259. def __call__(self, image, target, mosaic=False):
  260. # resize
  261. img_h0, img_w0 = image.shape[:2]
  262. r = self.img_size / max(img_h0, img_w0)
  263. if r != 1:
  264. interp = cv2.INTER_LINEAR
  265. new_shape = (int(round(img_w0 * r)), int(round(img_h0 * r)))
  266. img = cv2.resize(image, new_shape, interpolation=interp)
  267. else:
  268. img = image
  269. img_h, img_w = img.shape[:2]
  270. # hsv augment
  271. augment_hsv(img, hgain=self.trans_config['hsv_h'],
  272. sgain=self.trans_config['hsv_s'],
  273. vgain=self.trans_config['hsv_v'])
  274. if not mosaic:
  275. # rescale bbox
  276. boxes_ = target["boxes"].copy()
  277. boxes_[:, [0, 2]] = boxes_[:, [0, 2]] / img_w0 * img_w
  278. boxes_[:, [1, 3]] = boxes_[:, [1, 3]] / img_h0 * img_h
  279. target["boxes"] = boxes_
  280. # spatial augment
  281. target_ = np.concatenate(
  282. (target['labels'][..., None], target['boxes']), axis=-1)
  283. img, target_ = random_perspective(
  284. img, target_,
  285. degrees=self.trans_config['degrees'],
  286. translate=self.trans_config['translate'],
  287. scale=self.trans_config['scale'],
  288. shear=self.trans_config['shear'],
  289. perspective=self.trans_config['perspective']
  290. )
  291. target['boxes'] = target_[..., 1:]
  292. target['labels'] = target_[..., 0]
  293. # random flip
  294. if random.random() < 0.5:
  295. w = img.shape[1]
  296. img = np.fliplr(img).copy()
  297. boxes = target['boxes'].copy()
  298. boxes[..., [0, 2]] = w - boxes[..., [2, 0]]
  299. target["boxes"] = boxes
  300. # to tensor
  301. img_tensor = torch.from_numpy(img).permute(2, 0, 1).contiguous().float()
  302. if target is not None:
  303. target["boxes"] = torch.as_tensor(target["boxes"]).float()
  304. target["labels"] = torch.as_tensor(target["labels"]).long()
  305. # pad img
  306. img_h0, img_w0 = img_tensor.shape[1:]
  307. assert max(img_h0, img_w0) <= self.img_size
  308. pad_image = torch.ones([img_tensor.size(0), self.img_size, self.img_size]).float() * 114.
  309. pad_image[:, :img_h0, :img_w0] = img_tensor
  310. dh = self.img_size - img_h0
  311. dw = self.img_size - img_w0
  312. return pad_image, target, [dw, dh]
  313. ## YOLOv5-style Transform for Eval
  314. class YOLOv5BaseTransform(object):
  315. def __init__(self, img_size=640, max_stride=32):
  316. self.img_size = img_size
  317. self.max_stride = max_stride
  318. def __call__(self, image, target=None, mosaic=False):
  319. # resize
  320. img_h0, img_w0 = image.shape[:2]
  321. r = self.img_size / max(img_h0, img_w0)
  322. # r = min(r, 1.0) # only scale down, do not scale up (for better val mAP)
  323. if r != 1:
  324. new_shape = (int(round(img_w0 * r)), int(round(img_h0 * r)))
  325. img = cv2.resize(image, new_shape, interpolation=cv2.INTER_LINEAR)
  326. else:
  327. img = image
  328. img_h, img_w = img.shape[:2]
  329. # to tensor
  330. img_tensor = torch.from_numpy(img).permute(2, 0, 1).contiguous().float()
  331. # rescale bboxes
  332. if target is not None:
  333. # rescale bbox
  334. boxes_ = target["boxes"].copy()
  335. boxes_[:, [0, 2]] = boxes_[:, [0, 2]] / img_w0 * img_w
  336. boxes_[:, [1, 3]] = boxes_[:, [1, 3]] / img_h0 * img_h
  337. target["boxes"] = boxes_
  338. # to tensor
  339. target["boxes"] = torch.as_tensor(target["boxes"]).float()
  340. target["labels"] = torch.as_tensor(target["labels"]).long()
  341. # pad img
  342. img_h0, img_w0 = img_tensor.shape[1:]
  343. dh = img_h0 % self.max_stride
  344. dw = img_w0 % self.max_stride
  345. dh = dh if dh == 0 else self.max_stride - dh
  346. dw = dw if dw == 0 else self.max_stride - dw
  347. pad_img_h = img_h0 + dh
  348. pad_img_w = img_w0 + dw
  349. pad_image = torch.ones([img_tensor.size(0), pad_img_h, pad_img_w]).float() * 114.
  350. pad_image[:, :img_h0, :img_w0] = img_tensor
  351. return pad_image, target, [dw, dh]