augment.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  1. # Ultralytics YOLO 🚀, AGPL-3.0 license
  2. import math
  3. import random
  4. from copy import deepcopy
  5. import cv2
  6. import numpy as np
  7. import torch
  8. import torchvision.transforms as T
  9. from ultralytics.utils import LOGGER, colorstr
  10. from ultralytics.utils.checks import check_version
  11. from ultralytics.utils.instance import Instances
  12. from ultralytics.utils.metrics import bbox_ioa
  13. from ultralytics.utils.ops import segment2box
  14. from .utils import polygons2masks, polygons2masks_overlap
  15. # TODO: we might need a BaseTransform to make all these augments be compatible with both classification and semantic
  16. class BaseTransform:
  17. def __init__(self) -> None:
  18. pass
  19. def apply_image(self, labels):
  20. """Applies image transformation to labels."""
  21. pass
  22. def apply_instances(self, labels):
  23. """Applies transformations to input 'labels' and returns object instances."""
  24. pass
  25. def apply_semantic(self, labels):
  26. """Applies semantic segmentation to an image."""
  27. pass
  28. def __call__(self, labels):
  29. """Applies label transformations to an image, instances and semantic masks."""
  30. self.apply_image(labels)
  31. self.apply_instances(labels)
  32. self.apply_semantic(labels)
  33. class Compose:
  34. def __init__(self, transforms):
  35. """Initializes the Compose object with a list of transforms."""
  36. self.transforms = transforms
  37. def __call__(self, data):
  38. """Applies a series of transformations to input data."""
  39. for t in self.transforms:
  40. data = t(data)
  41. return data
  42. def append(self, transform):
  43. """Appends a new transform to the existing list of transforms."""
  44. self.transforms.append(transform)
  45. def tolist(self):
  46. """Converts list of transforms to a standard Python list."""
  47. return self.transforms
  48. def __repr__(self):
  49. """Return string representation of object."""
  50. format_string = f'{self.__class__.__name__}('
  51. for t in self.transforms:
  52. format_string += '\n'
  53. format_string += f' {t}'
  54. format_string += '\n)'
  55. return format_string
  56. class BaseMixTransform:
  57. """This implementation is from mmyolo."""
  58. def __init__(self, dataset, pre_transform=None, p=0.0) -> None:
  59. self.dataset = dataset
  60. self.pre_transform = pre_transform
  61. self.p = p
  62. def __call__(self, labels):
  63. """Applies pre-processing transforms and mixup/mosaic transforms to labels data."""
  64. if random.uniform(0, 1) > self.p:
  65. return labels
  66. # Get index of one or three other images
  67. indexes = self.get_indexes()
  68. if isinstance(indexes, int):
  69. indexes = [indexes]
  70. # Get images information will be used for Mosaic or MixUp
  71. mix_labels = [self.dataset.get_image_and_label(i) for i in indexes]
  72. if self.pre_transform is not None:
  73. for i, data in enumerate(mix_labels):
  74. mix_labels[i] = self.pre_transform(data)
  75. labels['mix_labels'] = mix_labels
  76. # Mosaic or MixUp
  77. labels = self._mix_transform(labels)
  78. labels.pop('mix_labels', None)
  79. return labels
  80. def _mix_transform(self, labels):
  81. """Applies MixUp or Mosaic augmentation to the label dictionary."""
  82. raise NotImplementedError
  83. def get_indexes(self):
  84. """Gets a list of shuffled indexes for mosaic augmentation."""
  85. raise NotImplementedError
  86. class Mosaic(BaseMixTransform):
  87. """
  88. Mosaic augmentation.
  89. This class performs mosaic augmentation by combining multiple (4 or 9) images into a single mosaic image.
  90. The augmentation is applied to a dataset with a given probability.
  91. Attributes:
  92. dataset: The dataset on which the mosaic augmentation is applied.
  93. imgsz (int, optional): Image size (height and width) after mosaic pipeline of a single image. Default to 640.
  94. p (float, optional): Probability of applying the mosaic augmentation. Must be in the range 0-1. Default to 1.0.
  95. n (int, optional): The grid size, either 4 (for 2x2) or 9 (for 3x3).
  96. """
  97. def __init__(self, dataset, imgsz=640, p=1.0, n=4):
  98. """Initializes the object with a dataset, image size, probability, and border."""
  99. assert 0 <= p <= 1.0, f'The probability should be in range [0, 1], but got {p}.'
  100. assert n in (4, 9), 'grid must be equal to 4 or 9.'
  101. super().__init__(dataset=dataset, p=p)
  102. self.dataset = dataset
  103. self.imgsz = imgsz
  104. self.border = (-imgsz // 2, -imgsz // 2) # width, height
  105. self.n = n
  106. def get_indexes(self, buffer=True):
  107. """Return a list of random indexes from the dataset."""
  108. if buffer: # select images from buffer
  109. return random.choices(list(self.dataset.buffer), k=self.n - 1)
  110. else: # select any images
  111. return [random.randint(0, len(self.dataset) - 1) for _ in range(self.n - 1)]
  112. def _mix_transform(self, labels):
  113. """Apply mixup transformation to the input image and labels."""
  114. assert labels.get('rect_shape', None) is None, 'rect and mosaic are mutually exclusive.'
  115. assert len(labels.get('mix_labels', [])), 'There are no other images for mosaic augment.'
  116. return self._mosaic4(labels) if self.n == 4 else self._mosaic9(labels)
  117. def _mosaic4(self, labels):
  118. """Create a 2x2 image mosaic."""
  119. mosaic_labels = []
  120. s = self.imgsz
  121. yc, xc = (int(random.uniform(-x, 2 * s + x)) for x in self.border) # mosaic center x, y
  122. for i in range(4):
  123. labels_patch = labels if i == 0 else labels['mix_labels'][i - 1]
  124. # Load image
  125. img = labels_patch['img']
  126. h, w = labels_patch.pop('resized_shape')
  127. # Place img in img4
  128. if i == 0: # top left
  129. img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
  130. x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image)
  131. x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image)
  132. elif i == 1: # top right
  133. x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc
  134. x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h
  135. elif i == 2: # bottom left
  136. x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h)
  137. x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h)
  138. elif i == 3: # bottom right
  139. x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h)
  140. x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)
  141. img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax]
  142. padw = x1a - x1b
  143. padh = y1a - y1b
  144. labels_patch = self._update_labels(labels_patch, padw, padh)
  145. mosaic_labels.append(labels_patch)
  146. final_labels = self._cat_labels(mosaic_labels)
  147. final_labels['img'] = img4
  148. return final_labels
  149. def _mosaic9(self, labels):
  150. """Create a 3x3 image mosaic."""
  151. mosaic_labels = []
  152. s = self.imgsz
  153. hp, wp = -1, -1 # height, width previous
  154. for i in range(9):
  155. labels_patch = labels if i == 0 else labels['mix_labels'][i - 1]
  156. # Load image
  157. img = labels_patch['img']
  158. h, w = labels_patch.pop('resized_shape')
  159. # Place img in img9
  160. if i == 0: # center
  161. img9 = np.full((s * 3, s * 3, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
  162. h0, w0 = h, w
  163. c = s, s, s + w, s + h # xmin, ymin, xmax, ymax (base) coordinates
  164. elif i == 1: # top
  165. c = s, s - h, s + w, s
  166. elif i == 2: # top right
  167. c = s + wp, s - h, s + wp + w, s
  168. elif i == 3: # right
  169. c = s + w0, s, s + w0 + w, s + h
  170. elif i == 4: # bottom right
  171. c = s + w0, s + hp, s + w0 + w, s + hp + h
  172. elif i == 5: # bottom
  173. c = s + w0 - w, s + h0, s + w0, s + h0 + h
  174. elif i == 6: # bottom left
  175. c = s + w0 - wp - w, s + h0, s + w0 - wp, s + h0 + h
  176. elif i == 7: # left
  177. c = s - w, s + h0 - h, s, s + h0
  178. elif i == 8: # top left
  179. c = s - w, s + h0 - hp - h, s, s + h0 - hp
  180. padw, padh = c[:2]
  181. x1, y1, x2, y2 = (max(x, 0) for x in c) # allocate coords
  182. # Image
  183. img9[y1:y2, x1:x2] = img[y1 - padh:, x1 - padw:] # img9[ymin:ymax, xmin:xmax]
  184. hp, wp = h, w # height, width previous for next iteration
  185. # Labels assuming imgsz*2 mosaic size
  186. labels_patch = self._update_labels(labels_patch, padw + self.border[0], padh + self.border[1])
  187. mosaic_labels.append(labels_patch)
  188. final_labels = self._cat_labels(mosaic_labels)
  189. final_labels['img'] = img9[-self.border[0]:self.border[0], -self.border[1]:self.border[1]]
  190. return final_labels
  191. @staticmethod
  192. def _update_labels(labels, padw, padh):
  193. """Update labels."""
  194. nh, nw = labels['img'].shape[:2]
  195. labels['instances'].convert_bbox(format='xyxy')
  196. labels['instances'].denormalize(nw, nh)
  197. labels['instances'].add_padding(padw, padh)
  198. return labels
  199. def _cat_labels(self, mosaic_labels):
  200. """Return labels with mosaic border instances clipped."""
  201. if len(mosaic_labels) == 0:
  202. return {}
  203. cls = []
  204. instances = []
  205. imgsz = self.imgsz * 2 # mosaic imgsz
  206. for labels in mosaic_labels:
  207. cls.append(labels['cls'])
  208. instances.append(labels['instances'])
  209. final_labels = {
  210. 'im_file': mosaic_labels[0]['im_file'],
  211. 'ori_shape': mosaic_labels[0]['ori_shape'],
  212. 'resized_shape': (imgsz, imgsz),
  213. 'cls': np.concatenate(cls, 0),
  214. 'instances': Instances.concatenate(instances, axis=0),
  215. 'mosaic_border': self.border} # final_labels
  216. final_labels['instances'].clip(imgsz, imgsz)
  217. good = final_labels['instances'].remove_zero_area_boxes()
  218. final_labels['cls'] = final_labels['cls'][good]
  219. return final_labels
  220. class MixUp(BaseMixTransform):
  221. def __init__(self, dataset, pre_transform=None, p=0.0) -> None:
  222. super().__init__(dataset=dataset, pre_transform=pre_transform, p=p)
  223. def get_indexes(self):
  224. """Get a random index from the dataset."""
  225. return random.randint(0, len(self.dataset) - 1)
  226. def _mix_transform(self, labels):
  227. """Applies MixUp augmentation https://arxiv.org/pdf/1710.09412.pdf."""
  228. r = np.random.beta(32.0, 32.0) # mixup ratio, alpha=beta=32.0
  229. labels2 = labels['mix_labels'][0]
  230. labels['img'] = (labels['img'] * r + labels2['img'] * (1 - r)).astype(np.uint8)
  231. labels['instances'] = Instances.concatenate([labels['instances'], labels2['instances']], axis=0)
  232. labels['cls'] = np.concatenate([labels['cls'], labels2['cls']], 0)
  233. return labels
  234. class RandomPerspective:
  235. def __init__(self,
  236. degrees=0.0,
  237. translate=0.1,
  238. scale=0.5,
  239. shear=0.0,
  240. perspective=0.0,
  241. border=(0, 0),
  242. pre_transform=None):
  243. self.degrees = degrees
  244. self.translate = translate
  245. self.scale = scale
  246. self.shear = shear
  247. self.perspective = perspective
  248. # Mosaic border
  249. self.border = border
  250. self.pre_transform = pre_transform
  251. def affine_transform(self, img, border):
  252. """Center."""
  253. C = np.eye(3, dtype=np.float32)
  254. C[0, 2] = -img.shape[1] / 2 # x translation (pixels)
  255. C[1, 2] = -img.shape[0] / 2 # y translation (pixels)
  256. # Perspective
  257. P = np.eye(3, dtype=np.float32)
  258. P[2, 0] = random.uniform(-self.perspective, self.perspective) # x perspective (about y)
  259. P[2, 1] = random.uniform(-self.perspective, self.perspective) # y perspective (about x)
  260. # Rotation and Scale
  261. R = np.eye(3, dtype=np.float32)
  262. a = random.uniform(-self.degrees, self.degrees)
  263. # a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations
  264. s = random.uniform(1 - self.scale, 1 + self.scale)
  265. # s = 2 ** random.uniform(-scale, scale)
  266. R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)
  267. # Shear
  268. S = np.eye(3, dtype=np.float32)
  269. S[0, 1] = math.tan(random.uniform(-self.shear, self.shear) * math.pi / 180) # x shear (deg)
  270. S[1, 0] = math.tan(random.uniform(-self.shear, self.shear) * math.pi / 180) # y shear (deg)
  271. # Translation
  272. T = np.eye(3, dtype=np.float32)
  273. T[0, 2] = random.uniform(0.5 - self.translate, 0.5 + self.translate) * self.size[0] # x translation (pixels)
  274. T[1, 2] = random.uniform(0.5 - self.translate, 0.5 + self.translate) * self.size[1] # y translation (pixels)
  275. # Combined rotation matrix
  276. M = T @ S @ R @ P @ C # order of operations (right to left) is IMPORTANT
  277. # Affine image
  278. if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any(): # image changed
  279. if self.perspective:
  280. img = cv2.warpPerspective(img, M, dsize=self.size, borderValue=(114, 114, 114))
  281. else: # affine
  282. img = cv2.warpAffine(img, M[:2], dsize=self.size, borderValue=(114, 114, 114))
  283. return img, M, s
  284. def apply_bboxes(self, bboxes, M):
  285. """
  286. Apply affine to bboxes only.
  287. Args:
  288. bboxes (ndarray): list of bboxes, xyxy format, with shape (num_bboxes, 4).
  289. M (ndarray): affine matrix.
  290. Returns:
  291. new_bboxes (ndarray): bboxes after affine, [num_bboxes, 4].
  292. """
  293. n = len(bboxes)
  294. if n == 0:
  295. return bboxes
  296. xy = np.ones((n * 4, 3), dtype=bboxes.dtype)
  297. xy[:, :2] = bboxes[:, [0, 1, 2, 3, 0, 3, 2, 1]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1
  298. xy = xy @ M.T # transform
  299. xy = (xy[:, :2] / xy[:, 2:3] if self.perspective else xy[:, :2]).reshape(n, 8) # perspective rescale or affine
  300. # Create new boxes
  301. x = xy[:, [0, 2, 4, 6]]
  302. y = xy[:, [1, 3, 5, 7]]
  303. return np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1)), dtype=bboxes.dtype).reshape(4, n).T
  304. def apply_segments(self, segments, M):
  305. """
  306. Apply affine to segments and generate new bboxes from segments.
  307. Args:
  308. segments (ndarray): list of segments, [num_samples, 500, 2].
  309. M (ndarray): affine matrix.
  310. Returns:
  311. new_segments (ndarray): list of segments after affine, [num_samples, 500, 2].
  312. new_bboxes (ndarray): bboxes after affine, [N, 4].
  313. """
  314. n, num = segments.shape[:2]
  315. if n == 0:
  316. return [], segments
  317. xy = np.ones((n * num, 3), dtype=segments.dtype)
  318. segments = segments.reshape(-1, 2)
  319. xy[:, :2] = segments
  320. xy = xy @ M.T # transform
  321. xy = xy[:, :2] / xy[:, 2:3]
  322. segments = xy.reshape(n, -1, 2)
  323. bboxes = np.stack([segment2box(xy, self.size[0], self.size[1]) for xy in segments], 0)
  324. return bboxes, segments
  325. def apply_keypoints(self, keypoints, M):
  326. """
  327. Apply affine to keypoints.
  328. Args:
  329. keypoints (ndarray): keypoints, [N, 17, 3].
  330. M (ndarray): affine matrix.
  331. Returns:
  332. new_keypoints (ndarray): keypoints after affine, [N, 17, 3].
  333. """
  334. n, nkpt = keypoints.shape[:2]
  335. if n == 0:
  336. return keypoints
  337. xy = np.ones((n * nkpt, 3), dtype=keypoints.dtype)
  338. visible = keypoints[..., 2].reshape(n * nkpt, 1)
  339. xy[:, :2] = keypoints[..., :2].reshape(n * nkpt, 2)
  340. xy = xy @ M.T # transform
  341. xy = xy[:, :2] / xy[:, 2:3] # perspective rescale or affine
  342. out_mask = (xy[:, 0] < 0) | (xy[:, 1] < 0) | (xy[:, 0] > self.size[0]) | (xy[:, 1] > self.size[1])
  343. visible[out_mask] = 0
  344. return np.concatenate([xy, visible], axis=-1).reshape(n, nkpt, 3)
  345. def __call__(self, labels):
  346. """
  347. Affine images and targets.
  348. Args:
  349. labels (dict): a dict of `bboxes`, `segments`, `keypoints`.
  350. """
  351. if self.pre_transform and 'mosaic_border' not in labels:
  352. labels = self.pre_transform(labels)
  353. labels.pop('ratio_pad', None) # do not need ratio pad
  354. img = labels['img']
  355. cls = labels['cls']
  356. instances = labels.pop('instances')
  357. # Make sure the coord formats are right
  358. instances.convert_bbox(format='xyxy')
  359. instances.denormalize(*img.shape[:2][::-1])
  360. border = labels.pop('mosaic_border', self.border)
  361. self.size = img.shape[1] + border[1] * 2, img.shape[0] + border[0] * 2 # w, h
  362. # M is affine matrix
  363. # scale for func:`box_candidates`
  364. img, M, scale = self.affine_transform(img, border)
  365. bboxes = self.apply_bboxes(instances.bboxes, M)
  366. segments = instances.segments
  367. keypoints = instances.keypoints
  368. # Update bboxes if there are segments.
  369. if len(segments):
  370. bboxes, segments = self.apply_segments(segments, M)
  371. if keypoints is not None:
  372. keypoints = self.apply_keypoints(keypoints, M)
  373. new_instances = Instances(bboxes, segments, keypoints, bbox_format='xyxy', normalized=False)
  374. # Clip
  375. new_instances.clip(*self.size)
  376. # Filter instances
  377. instances.scale(scale_w=scale, scale_h=scale, bbox_only=True)
  378. # Make the bboxes have the same scale with new_bboxes
  379. i = self.box_candidates(box1=instances.bboxes.T,
  380. box2=new_instances.bboxes.T,
  381. area_thr=0.01 if len(segments) else 0.10)
  382. labels['instances'] = new_instances[i]
  383. labels['cls'] = cls[i]
  384. labels['img'] = img
  385. labels['resized_shape'] = img.shape[:2]
  386. return labels
  387. def box_candidates(self, box1, box2, wh_thr=2, ar_thr=100, area_thr=0.1, eps=1e-16): # box1(4,n), box2(4,n)
  388. # Compute box candidates: box1 before augment, box2 after augment, wh_thr (pixels), aspect_ratio_thr, area_ratio
  389. w1, h1 = box1[2] - box1[0], box1[3] - box1[1]
  390. w2, h2 = box2[2] - box2[0], box2[3] - box2[1]
  391. ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps)) # aspect ratio
  392. return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr) # candidates
  393. class RandomHSV:
  394. def __init__(self, hgain=0.5, sgain=0.5, vgain=0.5) -> None:
  395. self.hgain = hgain
  396. self.sgain = sgain
  397. self.vgain = vgain
  398. def __call__(self, labels):
  399. """Applies random horizontal or vertical flip to an image with a given probability."""
  400. img = labels['img']
  401. if self.hgain or self.sgain or self.vgain:
  402. r = np.random.uniform(-1, 1, 3) * [self.hgain, self.sgain, self.vgain] + 1 # random gains
  403. hue, sat, val = cv2.split(cv2.cvtColor(img, cv2.COLOR_BGR2HSV))
  404. dtype = img.dtype # uint8
  405. x = np.arange(0, 256, dtype=r.dtype)
  406. lut_hue = ((x * r[0]) % 180).astype(dtype)
  407. lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)
  408. lut_val = np.clip(x * r[2], 0, 255).astype(dtype)
  409. im_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val)))
  410. cv2.cvtColor(im_hsv, cv2.COLOR_HSV2BGR, dst=img) # no return needed
  411. return labels
  412. class RandomFlip:
  413. def __init__(self, p=0.5, direction='horizontal', flip_idx=None) -> None:
  414. assert direction in ['horizontal', 'vertical'], f'Support direction `horizontal` or `vertical`, got {direction}'
  415. assert 0 <= p <= 1.0
  416. self.p = p
  417. self.direction = direction
  418. self.flip_idx = flip_idx
  419. def __call__(self, labels):
  420. """Resize image and padding for detection, instance segmentation, pose."""
  421. img = labels['img']
  422. instances = labels.pop('instances')
  423. instances.convert_bbox(format='xywh')
  424. h, w = img.shape[:2]
  425. h = 1 if instances.normalized else h
  426. w = 1 if instances.normalized else w
  427. # Flip up-down
  428. if self.direction == 'vertical' and random.random() < self.p:
  429. img = np.flipud(img)
  430. instances.flipud(h)
  431. if self.direction == 'horizontal' and random.random() < self.p:
  432. img = np.fliplr(img)
  433. instances.fliplr(w)
  434. # For keypoints
  435. if self.flip_idx is not None and instances.keypoints is not None:
  436. instances.keypoints = np.ascontiguousarray(instances.keypoints[:, self.flip_idx, :])
  437. labels['img'] = np.ascontiguousarray(img)
  438. labels['instances'] = instances
  439. return labels
  440. class LetterBox:
  441. """Resize image and padding for detection, instance segmentation, pose."""
  442. def __init__(self, new_shape=(640, 640), auto=False, scaleFill=False, scaleup=True, center=True, stride=32):
  443. """Initialize LetterBox object with specific parameters."""
  444. self.new_shape = new_shape
  445. self.auto = auto
  446. self.scaleFill = scaleFill
  447. self.scaleup = scaleup
  448. self.stride = stride
  449. self.center = center # Put the image in the middle or top-left
  450. def __call__(self, labels=None, image=None):
  451. """Return updated labels and image with added border."""
  452. if labels is None:
  453. labels = {}
  454. img = labels.get('img') if image is None else image
  455. shape = img.shape[:2] # current shape [height, width]
  456. new_shape = labels.pop('rect_shape', self.new_shape)
  457. if isinstance(new_shape, int):
  458. new_shape = (new_shape, new_shape)
  459. # Scale ratio (new / old)
  460. r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
  461. if not self.scaleup: # only scale down, do not scale up (for better val mAP)
  462. r = min(r, 1.0)
  463. # Compute padding
  464. ratio = r, r # width, height ratios
  465. new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
  466. dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding
  467. if self.auto: # minimum rectangle
  468. dw, dh = np.mod(dw, self.stride), np.mod(dh, self.stride) # wh padding
  469. elif self.scaleFill: # stretch
  470. dw, dh = 0.0, 0.0
  471. new_unpad = (new_shape[1], new_shape[0])
  472. ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios
  473. if self.center:
  474. dw /= 2 # divide padding into 2 sides
  475. dh /= 2
  476. if labels.get('ratio_pad'):
  477. labels['ratio_pad'] = (labels['ratio_pad'], (dw, dh)) # for evaluation
  478. if shape[::-1] != new_unpad: # resize
  479. img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR)
  480. top, bottom = int(round(dh - 0.1)) if self.center else 0, int(round(dh + 0.1))
  481. left, right = int(round(dw - 0.1)) if self.center else 0, int(round(dw + 0.1))
  482. img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT,
  483. value=(114, 114, 114)) # add border
  484. if len(labels):
  485. labels = self._update_labels(labels, ratio, dw, dh)
  486. labels['img'] = img
  487. labels['resized_shape'] = new_shape
  488. return labels
  489. else:
  490. return img
  491. def _update_labels(self, labels, ratio, padw, padh):
  492. """Update labels."""
  493. labels['instances'].convert_bbox(format='xyxy')
  494. labels['instances'].denormalize(*labels['img'].shape[:2][::-1])
  495. labels['instances'].scale(*ratio)
  496. labels['instances'].add_padding(padw, padh)
  497. return labels
  498. class CopyPaste:
  499. def __init__(self, p=0.5) -> None:
  500. self.p = p
  501. def __call__(self, labels):
  502. """Implement Copy-Paste augmentation https://arxiv.org/abs/2012.07177, labels as nx5 np.array(cls, xyxy)."""
  503. im = labels['img']
  504. cls = labels['cls']
  505. h, w = im.shape[:2]
  506. instances = labels.pop('instances')
  507. instances.convert_bbox(format='xyxy')
  508. instances.denormalize(w, h)
  509. if self.p and len(instances.segments):
  510. n = len(instances)
  511. _, w, _ = im.shape # height, width, channels
  512. im_new = np.zeros(im.shape, np.uint8)
  513. # Calculate ioa first then select indexes randomly
  514. ins_flip = deepcopy(instances)
  515. ins_flip.fliplr(w)
  516. ioa = bbox_ioa(ins_flip.bboxes, instances.bboxes) # intersection over area, (N, M)
  517. indexes = np.nonzero((ioa < 0.30).all(1))[0] # (N, )
  518. n = len(indexes)
  519. for j in random.sample(list(indexes), k=round(self.p * n)):
  520. cls = np.concatenate((cls, cls[[j]]), axis=0)
  521. instances = Instances.concatenate((instances, ins_flip[[j]]), axis=0)
  522. cv2.drawContours(im_new, instances.segments[[j]].astype(np.int32), -1, (1, 1, 1), cv2.FILLED)
  523. result = cv2.flip(im, 1) # augment segments (flip left-right)
  524. i = cv2.flip(im_new, 1).astype(bool)
  525. im[i] = result[i]
  526. labels['img'] = im
  527. labels['cls'] = cls
  528. labels['instances'] = instances
  529. return labels
  530. class Albumentations:
  531. """YOLOv8 Albumentations class (optional, only used if package is installed)"""
  532. def __init__(self, p=1.0):
  533. """Initialize the transform object for YOLO bbox formatted params."""
  534. self.p = p
  535. self.transform = None
  536. prefix = colorstr('albumentations: ')
  537. try:
  538. import albumentations as A
  539. check_version(A.__version__, '1.0.3', hard=True) # version requirement
  540. T = [
  541. A.Blur(p=0.01),
  542. A.MedianBlur(p=0.01),
  543. A.ToGray(p=0.01),
  544. A.CLAHE(p=0.01),
  545. A.RandomBrightnessContrast(p=0.0),
  546. A.RandomGamma(p=0.0),
  547. A.ImageCompression(quality_lower=75, p=0.0)] # transforms
  548. self.transform = A.Compose(T, bbox_params=A.BboxParams(format='yolo', label_fields=['class_labels']))
  549. LOGGER.info(prefix + ', '.join(f'{x}'.replace('always_apply=False, ', '') for x in T if x.p))
  550. except ImportError: # package not installed, skip
  551. pass
  552. except Exception as e:
  553. LOGGER.info(f'{prefix}{e}')
  554. def __call__(self, labels):
  555. """Generates object detections and returns a dictionary with detection results."""
  556. im = labels['img']
  557. cls = labels['cls']
  558. if len(cls):
  559. labels['instances'].convert_bbox('xywh')
  560. labels['instances'].normalize(*im.shape[:2][::-1])
  561. bboxes = labels['instances'].bboxes
  562. # TODO: add supports of segments and keypoints
  563. if self.transform and random.random() < self.p:
  564. new = self.transform(image=im, bboxes=bboxes, class_labels=cls) # transformed
  565. if len(new['class_labels']) > 0: # skip update if no bbox in new im
  566. labels['img'] = new['image']
  567. labels['cls'] = np.array(new['class_labels'])
  568. bboxes = np.array(new['bboxes'], dtype=np.float32)
  569. labels['instances'].update(bboxes=bboxes)
  570. return labels
  571. # TODO: technically this is not an augmentation, maybe we should put this to another files
  572. class Format:
  573. def __init__(self,
  574. bbox_format='xywh',
  575. normalize=True,
  576. return_mask=False,
  577. return_keypoint=False,
  578. mask_ratio=4,
  579. mask_overlap=True,
  580. batch_idx=True):
  581. self.bbox_format = bbox_format
  582. self.normalize = normalize
  583. self.return_mask = return_mask # set False when training detection only
  584. self.return_keypoint = return_keypoint
  585. self.mask_ratio = mask_ratio
  586. self.mask_overlap = mask_overlap
  587. self.batch_idx = batch_idx # keep the batch indexes
  588. def __call__(self, labels):
  589. """Return formatted image, classes, bounding boxes & keypoints to be used by 'collate_fn'."""
  590. img = labels.pop('img')
  591. h, w = img.shape[:2]
  592. cls = labels.pop('cls')
  593. instances = labels.pop('instances')
  594. instances.convert_bbox(format=self.bbox_format)
  595. instances.denormalize(w, h)
  596. nl = len(instances)
  597. if self.return_mask:
  598. if nl:
  599. masks, instances, cls = self._format_segments(instances, cls, w, h)
  600. masks = torch.from_numpy(masks)
  601. else:
  602. masks = torch.zeros(1 if self.mask_overlap else nl, img.shape[0] // self.mask_ratio,
  603. img.shape[1] // self.mask_ratio)
  604. labels['masks'] = masks
  605. if self.normalize:
  606. instances.normalize(w, h)
  607. labels['img'] = self._format_img(img)
  608. labels['cls'] = torch.from_numpy(cls) if nl else torch.zeros(nl)
  609. labels['bboxes'] = torch.from_numpy(instances.bboxes) if nl else torch.zeros((nl, 4))
  610. if self.return_keypoint:
  611. labels['keypoints'] = torch.from_numpy(instances.keypoints)
  612. # Then we can use collate_fn
  613. if self.batch_idx:
  614. labels['batch_idx'] = torch.zeros(nl)
  615. return labels
  616. def _format_img(self, img):
  617. """Format the image for YOLOv5 from Numpy array to PyTorch tensor."""
  618. if len(img.shape) < 3:
  619. img = np.expand_dims(img, -1)
  620. img = np.ascontiguousarray(img.transpose(2, 0, 1)[::-1])
  621. img = torch.from_numpy(img)
  622. return img
  623. def _format_segments(self, instances, cls, w, h):
  624. """convert polygon points to bitmap."""
  625. segments = instances.segments
  626. if self.mask_overlap:
  627. masks, sorted_idx = polygons2masks_overlap((h, w), segments, downsample_ratio=self.mask_ratio)
  628. masks = masks[None] # (640, 640) -> (1, 640, 640)
  629. instances = instances[sorted_idx]
  630. cls = cls[sorted_idx]
  631. else:
  632. masks = polygons2masks((h, w), segments, color=1, downsample_ratio=self.mask_ratio)
  633. return masks, instances, cls
  634. def v8_transforms(dataset, imgsz, hyp, stretch=False):
  635. """Convert images to a size suitable for YOLOv8 training."""
  636. pre_transform = Compose([
  637. Mosaic(dataset, imgsz=imgsz, p=hyp.mosaic),
  638. CopyPaste(p=hyp.copy_paste),
  639. RandomPerspective(
  640. degrees=hyp.degrees,
  641. translate=hyp.translate,
  642. scale=hyp.scale,
  643. shear=hyp.shear,
  644. perspective=hyp.perspective,
  645. pre_transform=None if stretch else LetterBox(new_shape=(imgsz, imgsz)),
  646. )])
  647. flip_idx = dataset.data.get('flip_idx', []) # for keypoints augmentation
  648. if dataset.use_keypoints:
  649. kpt_shape = dataset.data.get('kpt_shape', None)
  650. if len(flip_idx) == 0 and hyp.fliplr > 0.0:
  651. hyp.fliplr = 0.0
  652. LOGGER.warning("WARNING ⚠️ No 'flip_idx' array defined in data.yaml, setting augmentation 'fliplr=0.0'")
  653. elif flip_idx and (len(flip_idx) != kpt_shape[0]):
  654. raise ValueError(f'data.yaml flip_idx={flip_idx} length must be equal to kpt_shape[0]={kpt_shape[0]}')
  655. return Compose([
  656. pre_transform,
  657. MixUp(dataset, pre_transform=pre_transform, p=hyp.mixup),
  658. Albumentations(p=1.0),
  659. RandomHSV(hgain=hyp.hsv_h, sgain=hyp.hsv_s, vgain=hyp.hsv_v),
  660. RandomFlip(direction='vertical', p=hyp.flipud),
  661. RandomFlip(direction='horizontal', p=hyp.fliplr, flip_idx=flip_idx)]) # transforms
  662. # Classification augmentations -----------------------------------------------------------------------------------------
  663. def classify_transforms(size=224, mean=(0.0, 0.0, 0.0), std=(1.0, 1.0, 1.0)): # IMAGENET_MEAN, IMAGENET_STD
  664. # Transforms to apply if albumentations not installed
  665. if not isinstance(size, int):
  666. raise TypeError(f'classify_transforms() size {size} must be integer, not (list, tuple)')
  667. if any(mean) or any(std):
  668. return T.Compose([CenterCrop(size), ToTensor(), T.Normalize(mean, std, inplace=True)])
  669. else:
  670. return T.Compose([CenterCrop(size), ToTensor()])
  671. def hsv2colorjitter(h, s, v):
  672. """Map HSV (hue, saturation, value) jitter into ColorJitter values (brightness, contrast, saturation, hue)"""
  673. return v, v, s, h
  674. def classify_albumentations(
  675. augment=True,
  676. size=224,
  677. scale=(0.08, 1.0),
  678. hflip=0.5,
  679. vflip=0.0,
  680. hsv_h=0.015, # image HSV-Hue augmentation (fraction)
  681. hsv_s=0.7, # image HSV-Saturation augmentation (fraction)
  682. hsv_v=0.4, # image HSV-Value augmentation (fraction)
  683. mean=(0.0, 0.0, 0.0), # IMAGENET_MEAN
  684. std=(1.0, 1.0, 1.0), # IMAGENET_STD
  685. auto_aug=False,
  686. ):
  687. """YOLOv8 classification Albumentations (optional, only used if package is installed)."""
  688. prefix = colorstr('albumentations: ')
  689. try:
  690. import albumentations as A
  691. from albumentations.pytorch import ToTensorV2
  692. check_version(A.__version__, '1.0.3', hard=True) # version requirement
  693. if augment: # Resize and crop
  694. T = [A.RandomResizedCrop(height=size, width=size, scale=scale)]
  695. if auto_aug:
  696. # TODO: implement AugMix, AutoAug & RandAug in albumentations
  697. LOGGER.info(f'{prefix}auto augmentations are currently not supported')
  698. else:
  699. if hflip > 0:
  700. T += [A.HorizontalFlip(p=hflip)]
  701. if vflip > 0:
  702. T += [A.VerticalFlip(p=vflip)]
  703. if any((hsv_h, hsv_s, hsv_v)):
  704. T += [A.ColorJitter(*hsv2colorjitter(hsv_h, hsv_s, hsv_v))] # brightness, contrast, saturation, hue
  705. else: # Use fixed crop for eval set (reproducibility)
  706. T = [A.SmallestMaxSize(max_size=size), A.CenterCrop(height=size, width=size)]
  707. T += [A.Normalize(mean=mean, std=std), ToTensorV2()] # Normalize and convert to Tensor
  708. LOGGER.info(prefix + ', '.join(f'{x}'.replace('always_apply=False, ', '') for x in T if x.p))
  709. return A.Compose(T)
  710. except ImportError: # package not installed, skip
  711. pass
  712. except Exception as e:
  713. LOGGER.info(f'{prefix}{e}')
  714. class ClassifyLetterBox:
  715. """YOLOv8 LetterBox class for image preprocessing, i.e. T.Compose([LetterBox(size), ToTensor()])"""
  716. def __init__(self, size=(640, 640), auto=False, stride=32):
  717. """Resizes image and crops it to center with max dimensions 'h' and 'w'."""
  718. super().__init__()
  719. self.h, self.w = (size, size) if isinstance(size, int) else size
  720. self.auto = auto # pass max size integer, automatically solve for short side using stride
  721. self.stride = stride # used with auto
  722. def __call__(self, im): # im = np.array HWC
  723. imh, imw = im.shape[:2]
  724. r = min(self.h / imh, self.w / imw) # ratio of new/old
  725. h, w = round(imh * r), round(imw * r) # resized image
  726. hs, ws = (math.ceil(x / self.stride) * self.stride for x in (h, w)) if self.auto else self.h, self.w
  727. top, left = round((hs - h) / 2 - 0.1), round((ws - w) / 2 - 0.1)
  728. im_out = np.full((self.h, self.w, 3), 114, dtype=im.dtype)
  729. im_out[top:top + h, left:left + w] = cv2.resize(im, (w, h), interpolation=cv2.INTER_LINEAR)
  730. return im_out
  731. class CenterCrop:
  732. """YOLOv8 CenterCrop class for image preprocessing, i.e. T.Compose([CenterCrop(size), ToTensor()])"""
  733. def __init__(self, size=640):
  734. """Converts an image from numpy array to PyTorch tensor."""
  735. super().__init__()
  736. self.h, self.w = (size, size) if isinstance(size, int) else size
  737. def __call__(self, im): # im = np.array HWC
  738. imh, imw = im.shape[:2]
  739. m = min(imh, imw) # min dimension
  740. top, left = (imh - m) // 2, (imw - m) // 2
  741. return cv2.resize(im[top:top + m, left:left + m], (self.w, self.h), interpolation=cv2.INTER_LINEAR)
  742. class ToTensor:
  743. """YOLOv8 ToTensor class for image preprocessing, i.e. T.Compose([LetterBox(size), ToTensor()])."""
  744. def __init__(self, half=False):
  745. """Initialize YOLOv8 ToTensor object with optional half-precision support."""
  746. super().__init__()
  747. self.half = half
  748. def __call__(self, im): # im = np.array HWC in BGR order
  749. im = np.ascontiguousarray(im.transpose((2, 0, 1))[::-1]) # HWC to CHW -> BGR to RGB -> contiguous
  750. im = torch.from_numpy(im) # to torch
  751. im = im.half() if self.half else im.float() # uint8 to fp16/32
  752. im /= 255.0 # 0-255 to 0.0-1.0
  753. return im