yolov5_augment.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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. # ------------------------- Preprocessers -------------------------
  103. ## YOLOv5-style Transform for Train
  104. class YOLOv5Augmentation(object):
  105. def __init__(self, img_size=640, affine_params=None, use_ablu=False):
  106. # Basic parameters
  107. self.img_size = img_size
  108. self.pixel_mean = [0., 0., 0.]
  109. self.pixel_std = [255., 255., 255.]
  110. self.color_format = 'bgr'
  111. self.affine_params = affine_params
  112. # Albumentations
  113. self.ablu_trans = Albumentations(img_size) if use_ablu else None
  114. def __call__(self, image, target, mosaic=False):
  115. # --------------- Keep ratio Resize ---------------
  116. img_h0, img_w0 = image.shape[:2]
  117. ratio = self.img_size / max(img_h0, img_w0)
  118. if ratio != 1:
  119. interp = cv2.INTER_LINEAR
  120. new_shape = (int(round(img_w0 * ratio)), int(round(img_h0 * ratio)))
  121. img = cv2.resize(image, new_shape, interpolation=interp)
  122. else:
  123. img = image
  124. img_h, img_w = img.shape[:2]
  125. # rescale bbox
  126. boxes_ = target["boxes"].copy()
  127. boxes_[:, [0, 2]] = boxes_[:, [0, 2]] / img_w0 * img_w
  128. boxes_[:, [1, 3]] = boxes_[:, [1, 3]] / img_h0 * img_h
  129. target["boxes"] = boxes_
  130. # --------------- Filter bad targets ---------------
  131. tgt_boxes_wh = target["boxes"][..., 2:] - target["boxes"][..., :2]
  132. min_tgt_size = np.min(tgt_boxes_wh, axis=-1)
  133. keep = (min_tgt_size > 1)
  134. target["boxes"] = target["boxes"][keep]
  135. target["labels"] = target["labels"][keep]
  136. # --------------- Albumentations ---------------
  137. if self.ablu_trans is not None:
  138. img, target = self.ablu_trans(img, target)
  139. # --------------- HSV augmentations ---------------
  140. augment_hsv(img,
  141. hgain=self.affine_params['hsv_h'],
  142. sgain=self.affine_params['hsv_s'],
  143. vgain=self.affine_params['hsv_v'])
  144. # --------------- Spatial augmentations ---------------
  145. ## Random perspective
  146. if not mosaic:
  147. # spatial augment
  148. target_ = np.concatenate(
  149. (target['labels'][..., None], target['boxes']), axis=-1)
  150. img, target_ = random_perspective(
  151. img, target_,
  152. degrees = self.affine_params['degrees'],
  153. translate = self.affine_params['translate'],
  154. scale = self.affine_params['scale'],
  155. shear = self.affine_params['shear'],
  156. perspective = self.affine_params['perspective']
  157. )
  158. target['boxes'] = target_[..., 1:]
  159. target['labels'] = target_[..., 0]
  160. ## Random flip
  161. if random.random() < 0.5:
  162. w = img.shape[1]
  163. img = np.fliplr(img).copy()
  164. boxes = target['boxes'].copy()
  165. boxes[..., [0, 2]] = w - boxes[..., [2, 0]]
  166. target["boxes"] = boxes
  167. # --------------- To torch.Tensor ---------------
  168. img_tensor = torch.from_numpy(img).permute(2, 0, 1).contiguous().float()
  169. if target is not None:
  170. target["boxes"] = torch.as_tensor(target["boxes"]).float()
  171. target["labels"] = torch.as_tensor(target["labels"]).long()
  172. # --------------- Pad image ---------------
  173. img_h0, img_w0 = img_tensor.shape[1:]
  174. pad_image = torch.ones([img_tensor.size(0), self.img_size, self.img_size]).float() * 114.
  175. pad_image[:, :img_h0, :img_w0] = img_tensor
  176. dh = self.img_size - img_h0
  177. dw = self.img_size - img_w0
  178. # normalize image
  179. pad_image /= 255.
  180. return pad_image, target, ratio #[dw, dh]
  181. ## YOLOv5-style Transform for Eval
  182. class YOLOv5BaseTransform(object):
  183. def __init__(self, img_size=640, max_stride=32):
  184. self.img_size = img_size
  185. self.max_stride = max_stride
  186. self.pixel_mean = [0., 0., 0.]
  187. self.pixel_std = [255., 255., 255.]
  188. self.color_format = 'bgr'
  189. def __call__(self, image, target=None, mosaic=False):
  190. # --------------- Keep ratio Resize ---------------
  191. ## Resize image
  192. img_h0, img_w0 = image.shape[:2]
  193. ratio = self.img_size / max(img_h0, img_w0)
  194. if ratio != 1:
  195. new_shape = (int(round(img_w0 * ratio)), int(round(img_h0 * ratio)))
  196. img = cv2.resize(image, new_shape, interpolation=cv2.INTER_LINEAR)
  197. else:
  198. img = image
  199. img_h, img_w = img.shape[:2]
  200. ## Rescale bboxes
  201. if target is not None:
  202. # rescale bbox
  203. boxes_ = target["boxes"].copy()
  204. boxes_[:, [0, 2]] = boxes_[:, [0, 2]] / img_w0 * img_w
  205. boxes_[:, [1, 3]] = boxes_[:, [1, 3]] / img_h0 * img_h
  206. target["boxes"] = boxes_
  207. # --------------- To torch.Tensor ---------------
  208. img_tensor = torch.from_numpy(img).permute(2, 0, 1).contiguous().float()
  209. if target is not None:
  210. target["boxes"] = torch.as_tensor(target["boxes"]).float()
  211. target["labels"] = torch.as_tensor(target["labels"]).long()
  212. # --------------- Pad image ---------------
  213. img_h0, img_w0 = img_tensor.shape[1:]
  214. dh = img_h0 % self.max_stride
  215. dw = img_w0 % self.max_stride
  216. dh = dh if dh == 0 else self.max_stride - dh
  217. dw = dw if dw == 0 else self.max_stride - dw
  218. pad_img_h = img_h0 + dh
  219. pad_img_w = img_w0 + dw
  220. pad_image = torch.ones([img_tensor.size(0), pad_img_h, pad_img_w]).float() * 114.
  221. pad_image[:, :img_h0, :img_w0] = img_tensor
  222. # normalize image
  223. pad_image /= 255.
  224. return pad_image, target, ratio #[dw, dh]