yolov5_augment.py 17 KB

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