augmentations.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. # YOLOv5 🚀 by Ultralytics, AGPL-3.0 license
  2. """
  3. Image augmentation functions
  4. """
  5. import math
  6. import random
  7. import cv2
  8. import numpy as np
  9. import torch
  10. import torchvision.transforms as T
  11. import torchvision.transforms.functional as TF
  12. from utils.general import LOGGER, check_version, colorstr, resample_segments, segment2box, xywhn2xyxy
  13. from utils.metrics import bbox_ioa
  14. IMAGENET_MEAN = 0.485, 0.456, 0.406 # RGB mean
  15. IMAGENET_STD = 0.229, 0.224, 0.225 # RGB standard deviation
  16. class Albumentations:
  17. # YOLOv5 Albumentations class (optional, only used if package is installed)
  18. def __init__(self, size=640):
  19. self.transform = None
  20. prefix = colorstr('albumentations: ')
  21. try:
  22. import albumentations as A
  23. check_version(A.__version__, '1.0.3', hard=True) # version requirement
  24. T = [
  25. A.RandomResizedCrop(height=size, width=size, scale=(0.8, 1.0), ratio=(0.9, 1.11), p=0.0),
  26. A.Blur(p=0.01),
  27. A.MedianBlur(p=0.01),
  28. A.ToGray(p=0.01),
  29. A.CLAHE(p=0.01),
  30. A.RandomBrightnessContrast(p=0.0),
  31. A.RandomGamma(p=0.0),
  32. A.ImageCompression(quality_lower=75, p=0.0)] # transforms
  33. self.transform = A.Compose(T, bbox_params=A.BboxParams(format='yolo', label_fields=['class_labels']))
  34. LOGGER.info(prefix + ', '.join(f'{x}'.replace('always_apply=False, ', '') for x in T if x.p))
  35. except ImportError: # package not installed, skip
  36. pass
  37. except Exception as e:
  38. LOGGER.info(f'{prefix}{e}')
  39. def __call__(self, im, labels, p=1.0):
  40. if self.transform and random.random() < p:
  41. new = self.transform(image=im, bboxes=labels[:, 1:], class_labels=labels[:, 0]) # transformed
  42. im, labels = new['image'], np.array([[c, *b] for c, b in zip(new['class_labels'], new['bboxes'])])
  43. return im, labels
  44. def normalize(x, mean=IMAGENET_MEAN, std=IMAGENET_STD, inplace=False):
  45. # Denormalize RGB images x per ImageNet stats in BCHW format, i.e. = (x - mean) / std
  46. return TF.normalize(x, mean, std, inplace=inplace)
  47. def denormalize(x, mean=IMAGENET_MEAN, std=IMAGENET_STD):
  48. # Denormalize RGB images x per ImageNet stats in BCHW format, i.e. = x * std + mean
  49. for i in range(3):
  50. x[:, i] = x[:, i] * std[i] + mean[i]
  51. return x
  52. def augment_hsv(im, hgain=0.5, sgain=0.5, vgain=0.5):
  53. # HSV color-space augmentation
  54. if hgain or sgain or vgain:
  55. r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1 # random gains
  56. hue, sat, val = cv2.split(cv2.cvtColor(im, cv2.COLOR_BGR2HSV))
  57. dtype = im.dtype # uint8
  58. x = np.arange(0, 256, dtype=r.dtype)
  59. lut_hue = ((x * r[0]) % 180).astype(dtype)
  60. lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)
  61. lut_val = np.clip(x * r[2], 0, 255).astype(dtype)
  62. im_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val)))
  63. cv2.cvtColor(im_hsv, cv2.COLOR_HSV2BGR, dst=im) # no return needed
  64. def hist_equalize(im, clahe=True, bgr=False):
  65. # Equalize histogram on BGR image 'im' with im.shape(n,m,3) and range 0-255
  66. yuv = cv2.cvtColor(im, cv2.COLOR_BGR2YUV if bgr else cv2.COLOR_RGB2YUV)
  67. if clahe:
  68. c = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
  69. yuv[:, :, 0] = c.apply(yuv[:, :, 0])
  70. else:
  71. yuv[:, :, 0] = cv2.equalizeHist(yuv[:, :, 0]) # equalize Y channel histogram
  72. return cv2.cvtColor(yuv, cv2.COLOR_YUV2BGR if bgr else cv2.COLOR_YUV2RGB) # convert YUV image to RGB
  73. def replicate(im, labels):
  74. # Replicate labels
  75. h, w = im.shape[:2]
  76. boxes = labels[:, 1:].astype(int)
  77. x1, y1, x2, y2 = boxes.T
  78. s = ((x2 - x1) + (y2 - y1)) / 2 # side length (pixels)
  79. for i in s.argsort()[:round(s.size * 0.5)]: # smallest indices
  80. x1b, y1b, x2b, y2b = boxes[i]
  81. bh, bw = y2b - y1b, x2b - x1b
  82. yc, xc = int(random.uniform(0, h - bh)), int(random.uniform(0, w - bw)) # offset x, y
  83. x1a, y1a, x2a, y2a = [xc, yc, xc + bw, yc + bh]
  84. im[y1a:y2a, x1a:x2a] = im[y1b:y2b, x1b:x2b] # im4[ymin:ymax, xmin:xmax]
  85. labels = np.append(labels, [[labels[i, 0], x1a, y1a, x2a, y2a]], axis=0)
  86. return im, labels
  87. def letterbox(im, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32):
  88. # Resize and pad image while meeting stride-multiple constraints
  89. shape = im.shape[:2] # current shape [height, width]
  90. if isinstance(new_shape, int):
  91. new_shape = (new_shape, new_shape)
  92. # Scale ratio (new / old)
  93. r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
  94. if not scaleup: # only scale down, do not scale up (for better val mAP)
  95. r = min(r, 1.0)
  96. # Compute padding
  97. ratio = r, r # width, height ratios
  98. new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
  99. dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding
  100. if auto: # minimum rectangle
  101. dw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh padding
  102. elif scaleFill: # stretch
  103. dw, dh = 0.0, 0.0
  104. new_unpad = (new_shape[1], new_shape[0])
  105. ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios
  106. dw /= 2 # divide padding into 2 sides
  107. dh /= 2
  108. if shape[::-1] != new_unpad: # resize
  109. im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR)
  110. top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
  111. left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
  112. im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border
  113. return im, ratio, (dw, dh)
  114. def random_perspective(im,
  115. targets=(),
  116. segments=(),
  117. degrees=10,
  118. translate=.1,
  119. scale=.1,
  120. shear=10,
  121. perspective=0.0,
  122. border=(0, 0)):
  123. # torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(0.1, 0.1), scale=(0.9, 1.1), shear=(-10, 10))
  124. # targets = [cls, xyxy]
  125. height = im.shape[0] + border[0] * 2 # shape(h,w,c)
  126. width = im.shape[1] + border[1] * 2
  127. # Center
  128. C = np.eye(3)
  129. C[0, 2] = -im.shape[1] / 2 # x translation (pixels)
  130. C[1, 2] = -im.shape[0] / 2 # y translation (pixels)
  131. # Perspective
  132. P = np.eye(3)
  133. P[2, 0] = random.uniform(-perspective, perspective) # x perspective (about y)
  134. P[2, 1] = random.uniform(-perspective, perspective) # y perspective (about x)
  135. # Rotation and Scale
  136. R = np.eye(3)
  137. a = random.uniform(-degrees, degrees)
  138. # a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations
  139. s = random.uniform(1 - scale, 1 + scale)
  140. # s = 2 ** random.uniform(-scale, scale)
  141. R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)
  142. # Shear
  143. S = np.eye(3)
  144. S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # x shear (deg)
  145. S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # y shear (deg)
  146. # Translation
  147. T = np.eye(3)
  148. T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * width # x translation (pixels)
  149. T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * height # y translation (pixels)
  150. # Combined rotation matrix
  151. M = T @ S @ R @ P @ C # order of operations (right to left) is IMPORTANT
  152. if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any(): # image changed
  153. if perspective:
  154. im = cv2.warpPerspective(im, M, dsize=(width, height), borderValue=(114, 114, 114))
  155. else: # affine
  156. im = cv2.warpAffine(im, M[:2], dsize=(width, height), borderValue=(114, 114, 114))
  157. # Visualize
  158. # import matplotlib.pyplot as plt
  159. # ax = plt.subplots(1, 2, figsize=(12, 6))[1].ravel()
  160. # ax[0].imshow(im[:, :, ::-1]) # base
  161. # ax[1].imshow(im2[:, :, ::-1]) # warped
  162. # Transform label coordinates
  163. n = len(targets)
  164. if n:
  165. use_segments = any(x.any() for x in segments) and len(segments) == n
  166. new = np.zeros((n, 4))
  167. if use_segments: # warp segments
  168. segments = resample_segments(segments) # upsample
  169. for i, segment in enumerate(segments):
  170. xy = np.ones((len(segment), 3))
  171. xy[:, :2] = segment
  172. xy = xy @ M.T # transform
  173. xy = xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2] # perspective rescale or affine
  174. # clip
  175. new[i] = segment2box(xy, width, height)
  176. else: # warp boxes
  177. xy = np.ones((n * 4, 3))
  178. xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1
  179. xy = xy @ M.T # transform
  180. xy = (xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]).reshape(n, 8) # perspective rescale or affine
  181. # create new boxes
  182. x = xy[:, [0, 2, 4, 6]]
  183. y = xy[:, [1, 3, 5, 7]]
  184. new = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T
  185. # clip
  186. new[:, [0, 2]] = new[:, [0, 2]].clip(0, width)
  187. new[:, [1, 3]] = new[:, [1, 3]].clip(0, height)
  188. # filter candidates
  189. i = box_candidates(box1=targets[:, 1:5].T * s, box2=new.T, area_thr=0.01 if use_segments else 0.10)
  190. targets = targets[i]
  191. targets[:, 1:5] = new[i]
  192. return im, targets
  193. def copy_paste(im, labels, segments, p=0.5):
  194. # Implement Copy-Paste augmentation https://arxiv.org/abs/2012.07177, labels as nx5 np.array(cls, xyxy)
  195. n = len(segments)
  196. if p and n:
  197. h, w, c = im.shape # height, width, channels
  198. im_new = np.zeros(im.shape, np.uint8)
  199. for j in random.sample(range(n), k=round(p * n)):
  200. l, s = labels[j], segments[j]
  201. box = w - l[3], l[2], w - l[1], l[4]
  202. ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area
  203. if (ioa < 0.30).all(): # allow 30% obscuration of existing labels
  204. labels = np.concatenate((labels, [[l[0], *box]]), 0)
  205. segments.append(np.concatenate((w - s[:, 0:1], s[:, 1:2]), 1))
  206. cv2.drawContours(im_new, [segments[j].astype(np.int32)], -1, (1, 1, 1), cv2.FILLED)
  207. result = cv2.flip(im, 1) # augment segments (flip left-right)
  208. i = cv2.flip(im_new, 1).astype(bool)
  209. im[i] = result[i] # cv2.imwrite('debug.jpg', im) # debug
  210. return im, labels, segments
  211. def cutout(im, labels, p=0.5):
  212. # Applies image cutout augmentation https://arxiv.org/abs/1708.04552
  213. if random.random() < p:
  214. h, w = im.shape[:2]
  215. scales = [0.5] * 1 + [0.25] * 2 + [0.125] * 4 + [0.0625] * 8 + [0.03125] * 16 # image size fraction
  216. for s in scales:
  217. mask_h = random.randint(1, int(h * s)) # create random masks
  218. mask_w = random.randint(1, int(w * s))
  219. # box
  220. xmin = max(0, random.randint(0, w) - mask_w // 2)
  221. ymin = max(0, random.randint(0, h) - mask_h // 2)
  222. xmax = min(w, xmin + mask_w)
  223. ymax = min(h, ymin + mask_h)
  224. # apply random color mask
  225. im[ymin:ymax, xmin:xmax] = [random.randint(64, 191) for _ in range(3)]
  226. # return unobscured labels
  227. if len(labels) and s > 0.03:
  228. box = np.array([xmin, ymin, xmax, ymax], dtype=np.float32)
  229. ioa = bbox_ioa(box, xywhn2xyxy(labels[:, 1:5], w, h)) # intersection over area
  230. labels = labels[ioa < 0.60] # remove >60% obscured labels
  231. return labels
  232. def mixup(im, labels, im2, labels2):
  233. # Applies MixUp augmentation https://arxiv.org/pdf/1710.09412.pdf
  234. r = np.random.beta(32.0, 32.0) # mixup ratio, alpha=beta=32.0
  235. im = (im * r + im2 * (1 - r)).astype(np.uint8)
  236. labels = np.concatenate((labels, labels2), 0)
  237. return im, labels
  238. def box_candidates(box1, box2, wh_thr=2, ar_thr=100, area_thr=0.1, eps=1e-16): # box1(4,n), box2(4,n)
  239. # Compute candidate boxes: box1 before augment, box2 after augment, wh_thr (pixels), aspect_ratio_thr, area_ratio
  240. w1, h1 = box1[2] - box1[0], box1[3] - box1[1]
  241. w2, h2 = box2[2] - box2[0], box2[3] - box2[1]
  242. ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps)) # aspect ratio
  243. return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr) # candidates
  244. def classify_albumentations(
  245. augment=True,
  246. size=224,
  247. scale=(0.08, 1.0),
  248. ratio=(0.75, 1.0 / 0.75), # 0.75, 1.33
  249. hflip=0.5,
  250. vflip=0.0,
  251. jitter=0.4,
  252. mean=IMAGENET_MEAN,
  253. std=IMAGENET_STD,
  254. auto_aug=False):
  255. # YOLOv5 classification Albumentations (optional, only used if package is installed)
  256. prefix = colorstr('albumentations: ')
  257. try:
  258. import albumentations as A
  259. from albumentations.pytorch import ToTensorV2
  260. check_version(A.__version__, '1.0.3', hard=True) # version requirement
  261. if augment: # Resize and crop
  262. T = [A.RandomResizedCrop(height=size, width=size, scale=scale, ratio=ratio)]
  263. if auto_aug:
  264. # TODO: implement AugMix, AutoAug & RandAug in albumentation
  265. LOGGER.info(f'{prefix}auto augmentations are currently not supported')
  266. else:
  267. if hflip > 0:
  268. T += [A.HorizontalFlip(p=hflip)]
  269. if vflip > 0:
  270. T += [A.VerticalFlip(p=vflip)]
  271. if jitter > 0:
  272. color_jitter = (float(jitter), ) * 3 # repeat value for brightness, contrast, satuaration, 0 hue
  273. T += [A.ColorJitter(*color_jitter, 0)]
  274. else: # Use fixed crop for eval set (reproducibility)
  275. T = [A.SmallestMaxSize(max_size=size), A.CenterCrop(height=size, width=size)]
  276. T += [A.Normalize(mean=mean, std=std), ToTensorV2()] # Normalize and convert to Tensor
  277. LOGGER.info(prefix + ', '.join(f'{x}'.replace('always_apply=False, ', '') for x in T if x.p))
  278. return A.Compose(T)
  279. except ImportError: # package not installed, skip
  280. LOGGER.warning(f'{prefix}⚠️ not found, install with `pip install albumentations` (recommended)')
  281. except Exception as e:
  282. LOGGER.info(f'{prefix}{e}')
  283. def classify_transforms(size=224):
  284. # Transforms to apply if albumentations not installed
  285. assert isinstance(size, int), f'ERROR: classify_transforms size {size} must be integer, not (list, tuple)'
  286. # T.Compose([T.ToTensor(), T.Resize(size), T.CenterCrop(size), T.Normalize(IMAGENET_MEAN, IMAGENET_STD)])
  287. return T.Compose([CenterCrop(size), ToTensor(), T.Normalize(IMAGENET_MEAN, IMAGENET_STD)])
  288. class LetterBox:
  289. # YOLOv5 LetterBox class for image preprocessing, i.e. T.Compose([LetterBox(size), ToTensor()])
  290. def __init__(self, size=(640, 640), auto=False, stride=32):
  291. super().__init__()
  292. self.h, self.w = (size, size) if isinstance(size, int) else size
  293. self.auto = auto # pass max size integer, automatically solve for short side using stride
  294. self.stride = stride # used with auto
  295. def __call__(self, im): # im = np.array HWC
  296. imh, imw = im.shape[:2]
  297. r = min(self.h / imh, self.w / imw) # ratio of new/old
  298. h, w = round(imh * r), round(imw * r) # resized image
  299. hs, ws = (math.ceil(x / self.stride) * self.stride for x in (h, w)) if self.auto else self.h, self.w
  300. top, left = round((hs - h) / 2 - 0.1), round((ws - w) / 2 - 0.1)
  301. im_out = np.full((self.h, self.w, 3), 114, dtype=im.dtype)
  302. im_out[top:top + h, left:left + w] = cv2.resize(im, (w, h), interpolation=cv2.INTER_LINEAR)
  303. return im_out
  304. class CenterCrop:
  305. # YOLOv5 CenterCrop class for image preprocessing, i.e. T.Compose([CenterCrop(size), ToTensor()])
  306. def __init__(self, size=640):
  307. super().__init__()
  308. self.h, self.w = (size, size) if isinstance(size, int) else size
  309. def __call__(self, im): # im = np.array HWC
  310. imh, imw = im.shape[:2]
  311. m = min(imh, imw) # min dimension
  312. top, left = (imh - m) // 2, (imw - m) // 2
  313. return cv2.resize(im[top:top + m, left:left + m], (self.w, self.h), interpolation=cv2.INTER_LINEAR)
  314. class ToTensor:
  315. # YOLOv5 ToTensor class for image preprocessing, i.e. T.Compose([LetterBox(size), ToTensor()])
  316. def __init__(self, half=False):
  317. super().__init__()
  318. self.half = half
  319. def __call__(self, im): # im = np.array HWC in BGR order
  320. im = np.ascontiguousarray(im.transpose((2, 0, 1))[::-1]) # HWC to CHW -> BGR to RGB -> contiguous
  321. im = torch.from_numpy(im) # to torch
  322. im = im.half() if self.half else im.float() # uint8 to fp16/32
  323. im /= 255.0 # 0-255 to 0.0-1.0
  324. return im