You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

272 line
11KB

  1. # YOLOv5 image augmentation functions
  2. import logging
  3. import random
  4. import cv2
  5. import math
  6. import numpy as np
  7. from utils.general import colorstr, segment2box, resample_segments, check_version
  8. from utils.metrics import bbox_ioa
  9. class Albumentations:
  10. # YOLOv5 Albumentations class (optional, only used if package is installed)
  11. def __init__(self):
  12. self.transform = None
  13. try:
  14. import albumentations as A
  15. check_version(A.__version__, '1.0.3') # version requirement
  16. self.transform = A.Compose([
  17. A.Blur(p=0.1),
  18. A.MedianBlur(p=0.1),
  19. A.ToGray(p=0.01)],
  20. bbox_params=A.BboxParams(format='yolo', label_fields=['class_labels']))
  21. logging.info(colorstr('albumentations: ') + ', '.join(f'{x}' for x in self.transform.transforms if x.p))
  22. except ImportError: # package not installed, skip
  23. pass
  24. except Exception as e:
  25. logging.info(colorstr('albumentations: ') + f'{e}')
  26. def __call__(self, im, labels, p=1.0):
  27. if self.transform and random.random() < p:
  28. new = self.transform(image=im, bboxes=labels[:, 1:], class_labels=labels[:, 0]) # transformed
  29. im, labels = new['image'], np.array([[c, *b] for c, b in zip(new['class_labels'], new['bboxes'])])
  30. return im, labels
  31. def augment_hsv(im, hgain=0.5, sgain=0.5, vgain=0.5):
  32. # HSV color-space augmentation
  33. if hgain or sgain or vgain:
  34. r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1 # random gains
  35. hue, sat, val = cv2.split(cv2.cvtColor(im, cv2.COLOR_BGR2HSV))
  36. dtype = im.dtype # uint8
  37. x = np.arange(0, 256, dtype=r.dtype)
  38. lut_hue = ((x * r[0]) % 180).astype(dtype)
  39. lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)
  40. lut_val = np.clip(x * r[2], 0, 255).astype(dtype)
  41. im_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val)))
  42. cv2.cvtColor(im_hsv, cv2.COLOR_HSV2BGR, dst=im) # no return needed
  43. def hist_equalize(im, clahe=True, bgr=False):
  44. # Equalize histogram on BGR image 'im' with im.shape(n,m,3) and range 0-255
  45. yuv = cv2.cvtColor(im, cv2.COLOR_BGR2YUV if bgr else cv2.COLOR_RGB2YUV)
  46. if clahe:
  47. c = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
  48. yuv[:, :, 0] = c.apply(yuv[:, :, 0])
  49. else:
  50. yuv[:, :, 0] = cv2.equalizeHist(yuv[:, :, 0]) # equalize Y channel histogram
  51. return cv2.cvtColor(yuv, cv2.COLOR_YUV2BGR if bgr else cv2.COLOR_YUV2RGB) # convert YUV image to RGB
  52. def replicate(im, labels):
  53. # Replicate labels
  54. h, w = im.shape[:2]
  55. boxes = labels[:, 1:].astype(int)
  56. x1, y1, x2, y2 = boxes.T
  57. s = ((x2 - x1) + (y2 - y1)) / 2 # side length (pixels)
  58. for i in s.argsort()[:round(s.size * 0.5)]: # smallest indices
  59. x1b, y1b, x2b, y2b = boxes[i]
  60. bh, bw = y2b - y1b, x2b - x1b
  61. yc, xc = int(random.uniform(0, h - bh)), int(random.uniform(0, w - bw)) # offset x, y
  62. x1a, y1a, x2a, y2a = [xc, yc, xc + bw, yc + bh]
  63. im[y1a:y2a, x1a:x2a] = im[y1b:y2b, x1b:x2b] # im4[ymin:ymax, xmin:xmax]
  64. labels = np.append(labels, [[labels[i, 0], x1a, y1a, x2a, y2a]], axis=0)
  65. return im, labels
  66. def letterbox(im, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32):
  67. # Resize and pad image while meeting stride-multiple constraints
  68. shape = im.shape[:2] # current shape [height, width]
  69. if isinstance(new_shape, int):
  70. new_shape = (new_shape, new_shape)
  71. # Scale ratio (new / old)
  72. r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
  73. if not scaleup: # only scale down, do not scale up (for better val mAP)
  74. r = min(r, 1.0)
  75. # Compute padding
  76. ratio = r, r # width, height ratios
  77. new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
  78. dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding
  79. if auto: # minimum rectangle
  80. dw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh padding
  81. elif scaleFill: # stretch
  82. dw, dh = 0.0, 0.0
  83. new_unpad = (new_shape[1], new_shape[0])
  84. ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios
  85. dw /= 2 # divide padding into 2 sides
  86. dh /= 2
  87. if shape[::-1] != new_unpad: # resize
  88. im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR)
  89. top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
  90. left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
  91. im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border
  92. return im, ratio, (dw, dh)
  93. def random_perspective(im, targets=(), segments=(), degrees=10, translate=.1, scale=.1, shear=10, perspective=0.0,
  94. border=(0, 0)):
  95. # torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(.1, .1), scale=(.9, 1.1), shear=(-10, 10))
  96. # targets = [cls, xyxy]
  97. height = im.shape[0] + border[0] * 2 # shape(h,w,c)
  98. width = im.shape[1] + border[1] * 2
  99. # Center
  100. C = np.eye(3)
  101. C[0, 2] = -im.shape[1] / 2 # x translation (pixels)
  102. C[1, 2] = -im.shape[0] / 2 # y translation (pixels)
  103. # Perspective
  104. P = np.eye(3)
  105. P[2, 0] = random.uniform(-perspective, perspective) # x perspective (about y)
  106. P[2, 1] = random.uniform(-perspective, perspective) # y perspective (about x)
  107. # Rotation and Scale
  108. R = np.eye(3)
  109. a = random.uniform(-degrees, degrees)
  110. # a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations
  111. s = random.uniform(1 - scale, 1 + scale)
  112. # s = 2 ** random.uniform(-scale, scale)
  113. R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)
  114. # Shear
  115. S = np.eye(3)
  116. S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # x shear (deg)
  117. S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # y shear (deg)
  118. # Translation
  119. T = np.eye(3)
  120. T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * width # x translation (pixels)
  121. T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * height # y translation (pixels)
  122. # Combined rotation matrix
  123. M = T @ S @ R @ P @ C # order of operations (right to left) is IMPORTANT
  124. if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any(): # image changed
  125. if perspective:
  126. im = cv2.warpPerspective(im, M, dsize=(width, height), borderValue=(114, 114, 114))
  127. else: # affine
  128. im = cv2.warpAffine(im, M[:2], dsize=(width, height), borderValue=(114, 114, 114))
  129. # Visualize
  130. # import matplotlib.pyplot as plt
  131. # ax = plt.subplots(1, 2, figsize=(12, 6))[1].ravel()
  132. # ax[0].imshow(im[:, :, ::-1]) # base
  133. # ax[1].imshow(im2[:, :, ::-1]) # warped
  134. # Transform label coordinates
  135. n = len(targets)
  136. if n:
  137. use_segments = any(x.any() for x in segments)
  138. new = np.zeros((n, 4))
  139. if use_segments: # warp segments
  140. segments = resample_segments(segments) # upsample
  141. for i, segment in enumerate(segments):
  142. xy = np.ones((len(segment), 3))
  143. xy[:, :2] = segment
  144. xy = xy @ M.T # transform
  145. xy = xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2] # perspective rescale or affine
  146. # clip
  147. new[i] = segment2box(xy, width, height)
  148. else: # warp boxes
  149. xy = np.ones((n * 4, 3))
  150. xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1
  151. xy = xy @ M.T # transform
  152. xy = (xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]).reshape(n, 8) # perspective rescale or affine
  153. # create new boxes
  154. x = xy[:, [0, 2, 4, 6]]
  155. y = xy[:, [1, 3, 5, 7]]
  156. new = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T
  157. # clip
  158. new[:, [0, 2]] = new[:, [0, 2]].clip(0, width)
  159. new[:, [1, 3]] = new[:, [1, 3]].clip(0, height)
  160. # filter candidates
  161. i = box_candidates(box1=targets[:, 1:5].T * s, box2=new.T, area_thr=0.01 if use_segments else 0.10)
  162. targets = targets[i]
  163. targets[:, 1:5] = new[i]
  164. return im, targets
  165. def copy_paste(im, labels, segments, p=0.5):
  166. # Implement Copy-Paste augmentation https://arxiv.org/abs/2012.07177, labels as nx5 np.array(cls, xyxy)
  167. n = len(segments)
  168. if p and n:
  169. h, w, c = im.shape # height, width, channels
  170. im_new = np.zeros(im.shape, np.uint8)
  171. for j in random.sample(range(n), k=round(p * n)):
  172. l, s = labels[j], segments[j]
  173. box = w - l[3], l[2], w - l[1], l[4]
  174. ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area
  175. if (ioa < 0.30).all(): # allow 30% obscuration of existing labels
  176. labels = np.concatenate((labels, [[l[0], *box]]), 0)
  177. segments.append(np.concatenate((w - s[:, 0:1], s[:, 1:2]), 1))
  178. cv2.drawContours(im_new, [segments[j].astype(np.int32)], -1, (255, 255, 255), cv2.FILLED)
  179. result = cv2.bitwise_and(src1=im, src2=im_new)
  180. result = cv2.flip(result, 1) # augment segments (flip left-right)
  181. i = result > 0 # pixels to replace
  182. # i[:, :] = result.max(2).reshape(h, w, 1) # act over ch
  183. im[i] = result[i] # cv2.imwrite('debug.jpg', im) # debug
  184. return im, labels, segments
  185. def cutout(im, labels, p=0.5):
  186. # Applies image cutout augmentation https://arxiv.org/abs/1708.04552
  187. if random.random() < p:
  188. h, w = im.shape[:2]
  189. scales = [0.5] * 1 + [0.25] * 2 + [0.125] * 4 + [0.0625] * 8 + [0.03125] * 16 # image size fraction
  190. for s in scales:
  191. mask_h = random.randint(1, int(h * s)) # create random masks
  192. mask_w = random.randint(1, int(w * s))
  193. # box
  194. xmin = max(0, random.randint(0, w) - mask_w // 2)
  195. ymin = max(0, random.randint(0, h) - mask_h // 2)
  196. xmax = min(w, xmin + mask_w)
  197. ymax = min(h, ymin + mask_h)
  198. # apply random color mask
  199. im[ymin:ymax, xmin:xmax] = [random.randint(64, 191) for _ in range(3)]
  200. # return unobscured labels
  201. if len(labels) and s > 0.03:
  202. box = np.array([xmin, ymin, xmax, ymax], dtype=np.float32)
  203. ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area
  204. labels = labels[ioa < 0.60] # remove >60% obscured labels
  205. return labels
  206. def mixup(im, labels, im2, labels2):
  207. # Applies MixUp augmentation https://arxiv.org/pdf/1710.09412.pdf
  208. r = np.random.beta(32.0, 32.0) # mixup ratio, alpha=beta=32.0
  209. im = (im * r + im2 * (1 - r)).astype(np.uint8)
  210. labels = np.concatenate((labels, labels2), 0)
  211. return im, labels
  212. def box_candidates(box1, box2, wh_thr=2, ar_thr=20, area_thr=0.1, eps=1e-16): # box1(4,n), box2(4,n)
  213. # Compute candidate boxes: box1 before augment, box2 after augment, wh_thr (pixels), aspect_ratio_thr, area_ratio
  214. w1, h1 = box1[2] - box1[0], box1[3] - box1[1]
  215. w2, h2 = box2[2] - box2[0], box2[3] - box2[1]
  216. ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps)) # aspect ratio
  217. return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr) # candidates