yolov5_augment.py 15 KB

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