augmentations.py 13 KB

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