augment.py 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433
  1. # Ultralytics YOLO 🚀, AGPL-3.0 license
  2. import math
  3. import random
  4. from copy import deepcopy
  5. from typing import Tuple, Union
  6. import cv2
  7. import numpy as np
  8. import torch
  9. from PIL import Image
  10. from ultralytics.data.utils import polygons2masks, polygons2masks_overlap
  11. from ultralytics.utils import LOGGER, colorstr
  12. from ultralytics.utils.checks import check_version
  13. from ultralytics.utils.instance import Instances
  14. from ultralytics.utils.metrics import bbox_ioa
  15. from ultralytics.utils.ops import segment2box, xyxyxyxy2xywhr
  16. from ultralytics.utils.torch_utils import TORCHVISION_0_10, TORCHVISION_0_11, TORCHVISION_0_13
  17. DEFAULT_MEAN = (0.0, 0.0, 0.0)
  18. DEFAULT_STD = (1.0, 1.0, 1.0)
  19. DEFAULT_CROP_FRACTION = 1.0
  20. # TODO: we might need a BaseTransform to make all these augments be compatible with both classification and semantic
  21. class BaseTransform:
  22. """
  23. Base class for image transformations.
  24. This is a generic transformation class that can be extended for specific image processing needs.
  25. The class is designed to be compatible with both classification and semantic segmentation tasks.
  26. Methods:
  27. __init__: Initializes the BaseTransform object.
  28. apply_image: Applies image transformation to labels.
  29. apply_instances: Applies transformations to object instances in labels.
  30. apply_semantic: Applies semantic segmentation to an image.
  31. __call__: Applies all label transformations to an image, instances, and semantic masks.
  32. """
  33. def __init__(self) -> None:
  34. """Initializes the BaseTransform object."""
  35. pass
  36. def apply_image(self, labels):
  37. """Applies image transformations to labels."""
  38. pass
  39. def apply_instances(self, labels):
  40. """Applies transformations to object instances in labels."""
  41. pass
  42. def apply_semantic(self, labels):
  43. """Applies semantic segmentation to an image."""
  44. pass
  45. def __call__(self, labels):
  46. """Applies all label transformations to an image, instances, and semantic masks."""
  47. self.apply_image(labels)
  48. self.apply_instances(labels)
  49. self.apply_semantic(labels)
  50. class Compose:
  51. """Class for composing multiple image transformations."""
  52. def __init__(self, transforms):
  53. """Initializes the Compose object with a list of transforms."""
  54. self.transforms = transforms if isinstance(transforms, list) else [transforms]
  55. def __call__(self, data):
  56. """Applies a series of transformations to input data."""
  57. for t in self.transforms:
  58. data = t(data)
  59. return data
  60. def append(self, transform):
  61. """Appends a new transform to the existing list of transforms."""
  62. self.transforms.append(transform)
  63. def insert(self, index, transform):
  64. """Inserts a new transform to the existing list of transforms."""
  65. self.transforms.insert(index, transform)
  66. def __getitem__(self, index: Union[list, int]) -> "Compose":
  67. """Retrieve a specific transform or a set of transforms using indexing."""
  68. assert isinstance(index, (int, list)), f"The indices should be either list or int type but got {type(index)}"
  69. index = [index] if isinstance(index, int) else index
  70. return Compose([self.transforms[i] for i in index])
  71. def __setitem__(self, index: Union[list, int], value: Union[list, int]) -> None:
  72. """Retrieve a specific transform or a set of transforms using indexing."""
  73. assert isinstance(index, (int, list)), f"The indices should be either list or int type but got {type(index)}"
  74. if isinstance(index, list):
  75. assert isinstance(
  76. value, list
  77. ), f"The indices should be the same type as values, but got {type(index)} and {type(value)}"
  78. if isinstance(index, int):
  79. index, value = [index], [value]
  80. for i, v in zip(index, value):
  81. assert i < len(self.transforms), f"list index {i} out of range {len(self.transforms)}."
  82. self.transforms[i] = v
  83. def tolist(self):
  84. """Converts the list of transforms to a standard Python list."""
  85. return self.transforms
  86. def __repr__(self):
  87. """Returns a string representation of the object."""
  88. return f"{self.__class__.__name__}({', '.join([f'{t}' for t in self.transforms])})"
  89. class BaseMixTransform:
  90. """
  91. Class for base mix (MixUp/Mosaic) transformations.
  92. This implementation is from mmyolo.
  93. """
  94. def __init__(self, dataset, pre_transform=None, p=0.0) -> None:
  95. """Initializes the BaseMixTransform object with dataset, pre_transform, and probability."""
  96. self.dataset = dataset
  97. self.pre_transform = pre_transform
  98. self.p = p
  99. def __call__(self, labels):
  100. """Applies pre-processing transforms and mixup/mosaic transforms to labels data."""
  101. if random.uniform(0, 1) > self.p:
  102. return labels
  103. # Get index of one or three other images
  104. indexes = self.get_indexes()
  105. if isinstance(indexes, int):
  106. indexes = [indexes]
  107. # Get images information will be used for Mosaic or MixUp
  108. mix_labels = [self.dataset.get_image_and_label(i) for i in indexes]
  109. if self.pre_transform is not None:
  110. for i, data in enumerate(mix_labels):
  111. mix_labels[i] = self.pre_transform(data)
  112. labels["mix_labels"] = mix_labels
  113. # Update cls and texts
  114. labels = self._update_label_text(labels)
  115. # Mosaic or MixUp
  116. labels = self._mix_transform(labels)
  117. labels.pop("mix_labels", None)
  118. return labels
  119. def _mix_transform(self, labels):
  120. """Applies MixUp or Mosaic augmentation to the label dictionary."""
  121. raise NotImplementedError
  122. def get_indexes(self):
  123. """Gets a list of shuffled indexes for mosaic augmentation."""
  124. raise NotImplementedError
  125. def _update_label_text(self, labels):
  126. """Update label text."""
  127. if "texts" not in labels:
  128. return labels
  129. mix_texts = sum([labels["texts"]] + [x["texts"] for x in labels["mix_labels"]], [])
  130. mix_texts = list({tuple(x) for x in mix_texts})
  131. text2id = {text: i for i, text in enumerate(mix_texts)}
  132. for label in [labels] + labels["mix_labels"]:
  133. for i, cls in enumerate(label["cls"].squeeze(-1).tolist()):
  134. text = label["texts"][int(cls)]
  135. label["cls"][i] = text2id[tuple(text)]
  136. label["texts"] = mix_texts
  137. return labels
  138. class Mosaic(BaseMixTransform):
  139. """
  140. Mosaic augmentation.
  141. This class performs mosaic augmentation by combining multiple (4 or 9) images into a single mosaic image.
  142. The augmentation is applied to a dataset with a given probability.
  143. Attributes:
  144. dataset: The dataset on which the mosaic augmentation is applied.
  145. imgsz (int, optional): Image size (height and width) after mosaic pipeline of a single image. Default to 640.
  146. p (float, optional): Probability of applying the mosaic augmentation. Must be in the range 0-1. Default to 1.0.
  147. n (int, optional): The grid size, either 4 (for 2x2) or 9 (for 3x3).
  148. """
  149. def __init__(self, dataset, imgsz=640, p=1.0, n=4):
  150. """Initializes the object with a dataset, image size, probability, and border."""
  151. assert 0 <= p <= 1.0, f"The probability should be in range [0, 1], but got {p}."
  152. assert n in {4, 9}, "grid must be equal to 4 or 9."
  153. super().__init__(dataset=dataset, p=p)
  154. self.dataset = dataset
  155. self.imgsz = imgsz
  156. self.border = (-imgsz // 2, -imgsz // 2) # width, height
  157. self.n = n
  158. def get_indexes(self, buffer=True):
  159. """Return a list of random indexes from the dataset."""
  160. if buffer: # select images from buffer
  161. return random.choices(list(self.dataset.buffer), k=self.n - 1)
  162. else: # select any images
  163. return [random.randint(0, len(self.dataset) - 1) for _ in range(self.n - 1)]
  164. def _mix_transform(self, labels):
  165. """Apply mixup transformation to the input image and labels."""
  166. assert labels.get("rect_shape", None) is None, "rect and mosaic are mutually exclusive."
  167. assert len(labels.get("mix_labels", [])), "There are no other images for mosaic augment."
  168. return (
  169. self._mosaic3(labels) if self.n == 3 else self._mosaic4(labels) if self.n == 4 else self._mosaic9(labels)
  170. ) # This code is modified for mosaic3 method.
  171. def _mosaic3(self, labels):
  172. """Create a 1x3 image mosaic."""
  173. mosaic_labels = []
  174. s = self.imgsz
  175. for i in range(3):
  176. labels_patch = labels if i == 0 else labels["mix_labels"][i - 1]
  177. # Load image
  178. img = labels_patch["img"]
  179. h, w = labels_patch.pop("resized_shape")
  180. # Place img in img3
  181. if i == 0: # center
  182. img3 = np.full((s * 3, s * 3, img.shape[2]), 114, dtype=np.uint8) # base image with 3 tiles
  183. h0, w0 = h, w
  184. c = s, s, s + w, s + h # xmin, ymin, xmax, ymax (base) coordinates
  185. elif i == 1: # right
  186. c = s + w0, s, s + w0 + w, s + h
  187. elif i == 2: # left
  188. c = s - w, s + h0 - h, s, s + h0
  189. padw, padh = c[:2]
  190. x1, y1, x2, y2 = (max(x, 0) for x in c) # allocate coords
  191. img3[y1:y2, x1:x2] = img[y1 - padh :, x1 - padw :] # img3[ymin:ymax, xmin:xmax]
  192. # hp, wp = h, w # height, width previous for next iteration
  193. # Labels assuming imgsz*2 mosaic size
  194. labels_patch = self._update_labels(labels_patch, padw + self.border[0], padh + self.border[1])
  195. mosaic_labels.append(labels_patch)
  196. final_labels = self._cat_labels(mosaic_labels)
  197. final_labels["img"] = img3[-self.border[0] : self.border[0], -self.border[1] : self.border[1]]
  198. return final_labels
  199. def _mosaic4(self, labels):
  200. """Create a 2x2 image mosaic."""
  201. mosaic_labels = []
  202. s = self.imgsz
  203. yc, xc = (int(random.uniform(-x, 2 * s + x)) for x in self.border) # mosaic center x, y
  204. for i in range(4):
  205. labels_patch = labels if i == 0 else labels["mix_labels"][i - 1]
  206. # Load image
  207. img = labels_patch["img"]
  208. h, w = labels_patch.pop("resized_shape")
  209. # Place img in img4
  210. if i == 0: # top left
  211. img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
  212. x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image)
  213. x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image)
  214. elif i == 1: # top right
  215. x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc
  216. x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h
  217. elif i == 2: # bottom left
  218. x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h)
  219. x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h)
  220. elif i == 3: # bottom right
  221. x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h)
  222. x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)
  223. img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax]
  224. padw = x1a - x1b
  225. padh = y1a - y1b
  226. labels_patch = self._update_labels(labels_patch, padw, padh)
  227. mosaic_labels.append(labels_patch)
  228. final_labels = self._cat_labels(mosaic_labels)
  229. final_labels["img"] = img4
  230. return final_labels
  231. def _mosaic9(self, labels):
  232. """Create a 3x3 image mosaic."""
  233. mosaic_labels = []
  234. s = self.imgsz
  235. hp, wp = -1, -1 # height, width previous
  236. for i in range(9):
  237. labels_patch = labels if i == 0 else labels["mix_labels"][i - 1]
  238. # Load image
  239. img = labels_patch["img"]
  240. h, w = labels_patch.pop("resized_shape")
  241. # Place img in img9
  242. if i == 0: # center
  243. img9 = np.full((s * 3, s * 3, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
  244. h0, w0 = h, w
  245. c = s, s, s + w, s + h # xmin, ymin, xmax, ymax (base) coordinates
  246. elif i == 1: # top
  247. c = s, s - h, s + w, s
  248. elif i == 2: # top right
  249. c = s + wp, s - h, s + wp + w, s
  250. elif i == 3: # right
  251. c = s + w0, s, s + w0 + w, s + h
  252. elif i == 4: # bottom right
  253. c = s + w0, s + hp, s + w0 + w, s + hp + h
  254. elif i == 5: # bottom
  255. c = s + w0 - w, s + h0, s + w0, s + h0 + h
  256. elif i == 6: # bottom left
  257. c = s + w0 - wp - w, s + h0, s + w0 - wp, s + h0 + h
  258. elif i == 7: # left
  259. c = s - w, s + h0 - h, s, s + h0
  260. elif i == 8: # top left
  261. c = s - w, s + h0 - hp - h, s, s + h0 - hp
  262. padw, padh = c[:2]
  263. x1, y1, x2, y2 = (max(x, 0) for x in c) # allocate coords
  264. # Image
  265. img9[y1:y2, x1:x2] = img[y1 - padh :, x1 - padw :] # img9[ymin:ymax, xmin:xmax]
  266. hp, wp = h, w # height, width previous for next iteration
  267. # Labels assuming imgsz*2 mosaic size
  268. labels_patch = self._update_labels(labels_patch, padw + self.border[0], padh + self.border[1])
  269. mosaic_labels.append(labels_patch)
  270. final_labels = self._cat_labels(mosaic_labels)
  271. final_labels["img"] = img9[-self.border[0] : self.border[0], -self.border[1] : self.border[1]]
  272. return final_labels
  273. @staticmethod
  274. def _update_labels(labels, padw, padh):
  275. """Update labels."""
  276. nh, nw = labels["img"].shape[:2]
  277. labels["instances"].convert_bbox(format="xyxy")
  278. labels["instances"].denormalize(nw, nh)
  279. labels["instances"].add_padding(padw, padh)
  280. return labels
  281. def _cat_labels(self, mosaic_labels):
  282. """Return labels with mosaic border instances clipped."""
  283. if len(mosaic_labels) == 0:
  284. return {}
  285. cls = []
  286. instances = []
  287. imgsz = self.imgsz * 2 # mosaic imgsz
  288. for labels in mosaic_labels:
  289. cls.append(labels["cls"])
  290. instances.append(labels["instances"])
  291. # Final labels
  292. final_labels = {
  293. "im_file": mosaic_labels[0]["im_file"],
  294. "ori_shape": mosaic_labels[0]["ori_shape"],
  295. "resized_shape": (imgsz, imgsz),
  296. "cls": np.concatenate(cls, 0),
  297. "instances": Instances.concatenate(instances, axis=0),
  298. "mosaic_border": self.border,
  299. }
  300. final_labels["instances"].clip(imgsz, imgsz)
  301. good = final_labels["instances"].remove_zero_area_boxes()
  302. final_labels["cls"] = final_labels["cls"][good]
  303. if "texts" in mosaic_labels[0]:
  304. final_labels["texts"] = mosaic_labels[0]["texts"]
  305. return final_labels
  306. class MixUp(BaseMixTransform):
  307. """Class for applying MixUp augmentation to the dataset."""
  308. def __init__(self, dataset, pre_transform=None, p=0.0) -> None:
  309. """Initializes MixUp object with dataset, pre_transform, and probability of applying MixUp."""
  310. super().__init__(dataset=dataset, pre_transform=pre_transform, p=p)
  311. def get_indexes(self):
  312. """Get a random index from the dataset."""
  313. return random.randint(0, len(self.dataset) - 1)
  314. def _mix_transform(self, labels):
  315. """Applies MixUp augmentation as per https://arxiv.org/pdf/1710.09412.pdf."""
  316. r = np.random.beta(32.0, 32.0) # mixup ratio, alpha=beta=32.0
  317. labels2 = labels["mix_labels"][0]
  318. labels["img"] = (labels["img"] * r + labels2["img"] * (1 - r)).astype(np.uint8)
  319. labels["instances"] = Instances.concatenate([labels["instances"], labels2["instances"]], axis=0)
  320. labels["cls"] = np.concatenate([labels["cls"], labels2["cls"]], 0)
  321. return labels
  322. class RandomPerspective:
  323. """
  324. Implements random perspective and affine transformations on images and corresponding bounding boxes, segments, and
  325. keypoints. These transformations include rotation, translation, scaling, and shearing. The class also offers the
  326. option to apply these transformations conditionally with a specified probability.
  327. Attributes:
  328. degrees (float): Degree range for random rotations.
  329. translate (float): Fraction of total width and height for random translation.
  330. scale (float): Scaling factor interval, e.g., a scale factor of 0.1 allows a resize between 90%-110%.
  331. shear (float): Shear intensity (angle in degrees).
  332. perspective (float): Perspective distortion factor.
  333. border (tuple): Tuple specifying mosaic border.
  334. pre_transform (callable): A function/transform to apply to the image before starting the random transformation.
  335. Methods:
  336. affine_transform(img, border): Applies a series of affine transformations to the image.
  337. apply_bboxes(bboxes, M): Transforms bounding boxes using the calculated affine matrix.
  338. apply_segments(segments, M): Transforms segments and generates new bounding boxes.
  339. apply_keypoints(keypoints, M): Transforms keypoints.
  340. __call__(labels): Main method to apply transformations to both images and their corresponding annotations.
  341. box_candidates(box1, box2): Filters out bounding boxes that don't meet certain criteria post-transformation.
  342. """
  343. def __init__(
  344. self, degrees=0.0, translate=0.1, scale=0.5, shear=0.0, perspective=0.0, border=(0, 0), pre_transform=None
  345. ):
  346. """Initializes RandomPerspective object with transformation parameters."""
  347. self.degrees = degrees
  348. self.translate = translate
  349. self.scale = scale
  350. self.shear = shear
  351. self.perspective = perspective
  352. self.border = border # mosaic border
  353. self.pre_transform = pre_transform
  354. def affine_transform(self, img, border):
  355. """
  356. Applies a sequence of affine transformations centered around the image center.
  357. Args:
  358. img (ndarray): Input image.
  359. border (tuple): Border dimensions.
  360. Returns:
  361. img (ndarray): Transformed image.
  362. M (ndarray): Transformation matrix.
  363. s (float): Scale factor.
  364. """
  365. # Center
  366. C = np.eye(3, dtype=np.float32)
  367. C[0, 2] = -img.shape[1] / 2 # x translation (pixels)
  368. C[1, 2] = -img.shape[0] / 2 # y translation (pixels)
  369. # Perspective
  370. P = np.eye(3, dtype=np.float32)
  371. P[2, 0] = random.uniform(-self.perspective, self.perspective) # x perspective (about y)
  372. P[2, 1] = random.uniform(-self.perspective, self.perspective) # y perspective (about x)
  373. # Rotation and Scale
  374. R = np.eye(3, dtype=np.float32)
  375. a = random.uniform(-self.degrees, self.degrees)
  376. # a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations
  377. s = random.uniform(1 - self.scale, 1 + self.scale)
  378. # s = 2 ** random.uniform(-scale, scale)
  379. R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)
  380. # Shear
  381. S = np.eye(3, dtype=np.float32)
  382. S[0, 1] = math.tan(random.uniform(-self.shear, self.shear) * math.pi / 180) # x shear (deg)
  383. S[1, 0] = math.tan(random.uniform(-self.shear, self.shear) * math.pi / 180) # y shear (deg)
  384. # Translation
  385. T = np.eye(3, dtype=np.float32)
  386. T[0, 2] = random.uniform(0.5 - self.translate, 0.5 + self.translate) * self.size[0] # x translation (pixels)
  387. T[1, 2] = random.uniform(0.5 - self.translate, 0.5 + self.translate) * self.size[1] # y translation (pixels)
  388. # Combined rotation matrix
  389. M = T @ S @ R @ P @ C # order of operations (right to left) is IMPORTANT
  390. # Affine image
  391. if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any(): # image changed
  392. if self.perspective:
  393. img = cv2.warpPerspective(img, M, dsize=self.size, borderValue=(114, 114, 114))
  394. else: # affine
  395. img = cv2.warpAffine(img, M[:2], dsize=self.size, borderValue=(114, 114, 114))
  396. return img, M, s
  397. def apply_bboxes(self, bboxes, M):
  398. """
  399. Apply affine to bboxes only.
  400. Args:
  401. bboxes (ndarray): list of bboxes, xyxy format, with shape (num_bboxes, 4).
  402. M (ndarray): affine matrix.
  403. Returns:
  404. new_bboxes (ndarray): bboxes after affine, [num_bboxes, 4].
  405. """
  406. n = len(bboxes)
  407. if n == 0:
  408. return bboxes
  409. xy = np.ones((n * 4, 3), dtype=bboxes.dtype)
  410. xy[:, :2] = bboxes[:, [0, 1, 2, 3, 0, 3, 2, 1]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1
  411. xy = xy @ M.T # transform
  412. xy = (xy[:, :2] / xy[:, 2:3] if self.perspective else xy[:, :2]).reshape(n, 8) # perspective rescale or affine
  413. # Create new boxes
  414. x = xy[:, [0, 2, 4, 6]]
  415. y = xy[:, [1, 3, 5, 7]]
  416. return np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1)), dtype=bboxes.dtype).reshape(4, n).T
  417. def apply_segments(self, segments, M):
  418. """
  419. Apply affine to segments and generate new bboxes from segments.
  420. Args:
  421. segments (ndarray): list of segments, [num_samples, 500, 2].
  422. M (ndarray): affine matrix.
  423. Returns:
  424. new_segments (ndarray): list of segments after affine, [num_samples, 500, 2].
  425. new_bboxes (ndarray): bboxes after affine, [N, 4].
  426. """
  427. n, num = segments.shape[:2]
  428. if n == 0:
  429. return [], segments
  430. xy = np.ones((n * num, 3), dtype=segments.dtype)
  431. segments = segments.reshape(-1, 2)
  432. xy[:, :2] = segments
  433. xy = xy @ M.T # transform
  434. xy = xy[:, :2] / xy[:, 2:3]
  435. segments = xy.reshape(n, -1, 2)
  436. bboxes = np.stack([segment2box(xy, self.size[0], self.size[1]) for xy in segments], 0)
  437. segments[..., 0] = segments[..., 0].clip(bboxes[:, 0:1], bboxes[:, 2:3])
  438. segments[..., 1] = segments[..., 1].clip(bboxes[:, 1:2], bboxes[:, 3:4])
  439. return bboxes, segments
  440. def apply_keypoints(self, keypoints, M):
  441. """
  442. Apply affine to keypoints.
  443. Args:
  444. keypoints (ndarray): keypoints, [N, 17, 3].
  445. M (ndarray): affine matrix.
  446. Returns:
  447. new_keypoints (ndarray): keypoints after affine, [N, 17, 3].
  448. """
  449. n, nkpt = keypoints.shape[:2]
  450. if n == 0:
  451. return keypoints
  452. xy = np.ones((n * nkpt, 3), dtype=keypoints.dtype)
  453. visible = keypoints[..., 2].reshape(n * nkpt, 1)
  454. xy[:, :2] = keypoints[..., :2].reshape(n * nkpt, 2)
  455. xy = xy @ M.T # transform
  456. xy = xy[:, :2] / xy[:, 2:3] # perspective rescale or affine
  457. out_mask = (xy[:, 0] < 0) | (xy[:, 1] < 0) | (xy[:, 0] > self.size[0]) | (xy[:, 1] > self.size[1])
  458. visible[out_mask] = 0
  459. return np.concatenate([xy, visible], axis=-1).reshape(n, nkpt, 3)
  460. def __call__(self, labels):
  461. """
  462. Affine images and targets.
  463. Args:
  464. labels (dict): a dict of `bboxes`, `segments`, `keypoints`.
  465. """
  466. if self.pre_transform and "mosaic_border" not in labels:
  467. labels = self.pre_transform(labels)
  468. labels.pop("ratio_pad", None) # do not need ratio pad
  469. img = labels["img"]
  470. cls = labels["cls"]
  471. instances = labels.pop("instances")
  472. # Make sure the coord formats are right
  473. instances.convert_bbox(format="xyxy")
  474. instances.denormalize(*img.shape[:2][::-1])
  475. border = labels.pop("mosaic_border", self.border)
  476. self.size = img.shape[1] + border[1] * 2, img.shape[0] + border[0] * 2 # w, h
  477. # M is affine matrix
  478. # Scale for func:`box_candidates`
  479. img, M, scale = self.affine_transform(img, border)
  480. bboxes = self.apply_bboxes(instances.bboxes, M)
  481. segments = instances.segments
  482. keypoints = instances.keypoints
  483. # Update bboxes if there are segments.
  484. if len(segments):
  485. bboxes, segments = self.apply_segments(segments, M)
  486. if keypoints is not None:
  487. keypoints = self.apply_keypoints(keypoints, M)
  488. new_instances = Instances(bboxes, segments, keypoints, bbox_format="xyxy", normalized=False)
  489. # Clip
  490. new_instances.clip(*self.size)
  491. # Filter instances
  492. instances.scale(scale_w=scale, scale_h=scale, bbox_only=True)
  493. # Make the bboxes have the same scale with new_bboxes
  494. i = self.box_candidates(
  495. box1=instances.bboxes.T, box2=new_instances.bboxes.T, area_thr=0.01 if len(segments) else 0.10
  496. )
  497. labels["instances"] = new_instances[i]
  498. labels["cls"] = cls[i]
  499. labels["img"] = img
  500. labels["resized_shape"] = img.shape[:2]
  501. return labels
  502. def box_candidates(self, box1, box2, wh_thr=2, ar_thr=100, area_thr=0.1, eps=1e-16):
  503. """
  504. Compute box candidates based on a set of thresholds. This method compares the characteristics of the boxes
  505. before and after augmentation to decide whether a box is a candidate for further processing.
  506. Args:
  507. box1 (numpy.ndarray): The 4,n bounding box before augmentation, represented as [x1, y1, x2, y2].
  508. box2 (numpy.ndarray): The 4,n bounding box after augmentation, represented as [x1, y1, x2, y2].
  509. wh_thr (float, optional): The width and height threshold in pixels. Default is 2.
  510. ar_thr (float, optional): The aspect ratio threshold. Default is 100.
  511. area_thr (float, optional): The area ratio threshold. Default is 0.1.
  512. eps (float, optional): A small epsilon value to prevent division by zero. Default is 1e-16.
  513. Returns:
  514. (numpy.ndarray): A boolean array indicating which boxes are candidates based on the given thresholds.
  515. """
  516. w1, h1 = box1[2] - box1[0], box1[3] - box1[1]
  517. w2, h2 = box2[2] - box2[0], box2[3] - box2[1]
  518. ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps)) # aspect ratio
  519. return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr) # candidates
  520. class RandomHSV:
  521. """
  522. This class is responsible for performing random adjustments to the Hue, Saturation, and Value (HSV) channels of an
  523. image.
  524. The adjustments are random but within limits set by hgain, sgain, and vgain.
  525. """
  526. def __init__(self, hgain=0.5, sgain=0.5, vgain=0.5) -> None:
  527. """
  528. Initialize RandomHSV class with gains for each HSV channel.
  529. Args:
  530. hgain (float, optional): Maximum variation for hue. Default is 0.5.
  531. sgain (float, optional): Maximum variation for saturation. Default is 0.5.
  532. vgain (float, optional): Maximum variation for value. Default is 0.5.
  533. """
  534. self.hgain = hgain
  535. self.sgain = sgain
  536. self.vgain = vgain
  537. def __call__(self, labels):
  538. """
  539. Applies random HSV augmentation to an image within the predefined limits.
  540. The modified image replaces the original image in the input 'labels' dict.
  541. """
  542. img = labels["img"]
  543. if self.hgain or self.sgain or self.vgain:
  544. r = np.random.uniform(-1, 1, 3) * [self.hgain, self.sgain, self.vgain] + 1 # random gains
  545. hue, sat, val = cv2.split(cv2.cvtColor(img, cv2.COLOR_BGR2HSV))
  546. dtype = img.dtype # uint8
  547. x = np.arange(0, 256, dtype=r.dtype)
  548. lut_hue = ((x * r[0]) % 180).astype(dtype)
  549. lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)
  550. lut_val = np.clip(x * r[2], 0, 255).astype(dtype)
  551. im_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val)))
  552. cv2.cvtColor(im_hsv, cv2.COLOR_HSV2BGR, dst=img) # no return needed
  553. return labels
  554. class RandomFlip:
  555. """
  556. Applies a random horizontal or vertical flip to an image with a given probability.
  557. Also updates any instances (bounding boxes, keypoints, etc.) accordingly.
  558. """
  559. def __init__(self, p=0.5, direction="horizontal", flip_idx=None) -> None:
  560. """
  561. Initializes the RandomFlip class with probability and direction.
  562. Args:
  563. p (float, optional): The probability of applying the flip. Must be between 0 and 1. Default is 0.5.
  564. direction (str, optional): The direction to apply the flip. Must be 'horizontal' or 'vertical'.
  565. Default is 'horizontal'.
  566. flip_idx (array-like, optional): Index mapping for flipping keypoints, if any.
  567. """
  568. assert direction in {"horizontal", "vertical"}, f"Support direction `horizontal` or `vertical`, got {direction}"
  569. assert 0 <= p <= 1.0, f"The probability should be in range [0, 1], but got {p}."
  570. self.p = p
  571. self.direction = direction
  572. self.flip_idx = flip_idx
  573. def __call__(self, labels):
  574. """
  575. Applies random flip to an image and updates any instances like bounding boxes or keypoints accordingly.
  576. Args:
  577. labels (dict): A dictionary containing the keys 'img' and 'instances'. 'img' is the image to be flipped.
  578. 'instances' is an object containing bounding boxes and optionally keypoints.
  579. Returns:
  580. (dict): The same dict with the flipped image and updated instances under the 'img' and 'instances' keys.
  581. """
  582. img = labels["img"]
  583. instances = labels.pop("instances")
  584. instances.convert_bbox(format="xywh")
  585. h, w = img.shape[:2]
  586. h = 1 if instances.normalized else h
  587. w = 1 if instances.normalized else w
  588. # Flip up-down
  589. if self.direction == "vertical" and random.random() < self.p:
  590. img = np.flipud(img)
  591. instances.flipud(h)
  592. if self.direction == "horizontal" and random.random() < self.p:
  593. img = np.fliplr(img)
  594. instances.fliplr(w)
  595. # For keypoints
  596. if self.flip_idx is not None and instances.keypoints is not None:
  597. instances.keypoints = np.ascontiguousarray(instances.keypoints[:, self.flip_idx, :])
  598. labels["img"] = np.ascontiguousarray(img)
  599. labels["instances"] = instances
  600. return labels
  601. class LetterBox:
  602. """Resize image and padding for detection, instance segmentation, pose."""
  603. def __init__(self, new_shape=(640, 640), auto=False, scaleFill=False, scaleup=True, center=True, stride=32):
  604. """Initialize LetterBox object with specific parameters."""
  605. self.new_shape = new_shape
  606. self.auto = auto
  607. self.scaleFill = scaleFill
  608. self.scaleup = scaleup
  609. self.stride = stride
  610. self.center = center # Put the image in the middle or top-left
  611. def __call__(self, labels=None, image=None):
  612. """Return updated labels and image with added border."""
  613. if labels is None:
  614. labels = {}
  615. img = labels.get("img") if image is None else image
  616. shape = img.shape[:2] # current shape [height, width]
  617. new_shape = labels.pop("rect_shape", self.new_shape)
  618. if isinstance(new_shape, int):
  619. new_shape = (new_shape, new_shape)
  620. # Scale ratio (new / old)
  621. r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
  622. if not self.scaleup: # only scale down, do not scale up (for better val mAP)
  623. r = min(r, 1.0)
  624. # Compute padding
  625. ratio = r, r # width, height ratios
  626. new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
  627. dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding
  628. if self.auto: # minimum rectangle
  629. dw, dh = np.mod(dw, self.stride), np.mod(dh, self.stride) # wh padding
  630. elif self.scaleFill: # stretch
  631. dw, dh = 0.0, 0.0
  632. new_unpad = (new_shape[1], new_shape[0])
  633. ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios
  634. if self.center:
  635. dw /= 2 # divide padding into 2 sides
  636. dh /= 2
  637. if shape[::-1] != new_unpad: # resize
  638. img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR)
  639. top, bottom = int(round(dh - 0.1)) if self.center else 0, int(round(dh + 0.1))
  640. left, right = int(round(dw - 0.1)) if self.center else 0, int(round(dw + 0.1))
  641. img = cv2.copyMakeBorder(
  642. img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=(114, 114, 114)
  643. ) # add border
  644. if labels.get("ratio_pad"):
  645. labels["ratio_pad"] = (labels["ratio_pad"], (left, top)) # for evaluation
  646. if len(labels):
  647. labels = self._update_labels(labels, ratio, dw, dh)
  648. labels["img"] = img
  649. labels["resized_shape"] = new_shape
  650. return labels
  651. else:
  652. return img
  653. def _update_labels(self, labels, ratio, padw, padh):
  654. """Update labels."""
  655. labels["instances"].convert_bbox(format="xyxy")
  656. labels["instances"].denormalize(*labels["img"].shape[:2][::-1])
  657. labels["instances"].scale(*ratio)
  658. labels["instances"].add_padding(padw, padh)
  659. return labels
  660. class CopyPaste:
  661. """
  662. Implements the Copy-Paste augmentation as described in the paper https://arxiv.org/abs/2012.07177. This class is
  663. responsible for applying the Copy-Paste augmentation on images and their corresponding instances.
  664. """
  665. def __init__(self, p=0.5) -> None:
  666. """
  667. Initializes the CopyPaste class with a given probability.
  668. Args:
  669. p (float, optional): The probability of applying the Copy-Paste augmentation. Must be between 0 and 1.
  670. Default is 0.5.
  671. """
  672. self.p = p
  673. def __call__(self, labels):
  674. """
  675. Applies the Copy-Paste augmentation to the given image and instances.
  676. Args:
  677. labels (dict): A dictionary containing:
  678. - 'img': The image to augment.
  679. - 'cls': Class labels associated with the instances.
  680. - 'instances': Object containing bounding boxes, and optionally, keypoints and segments.
  681. Returns:
  682. (dict): Dict with augmented image and updated instances under the 'img', 'cls', and 'instances' keys.
  683. Notes:
  684. 1. Instances are expected to have 'segments' as one of their attributes for this augmentation to work.
  685. 2. This method modifies the input dictionary 'labels' in place.
  686. """
  687. im = labels["img"]
  688. cls = labels["cls"]
  689. h, w = im.shape[:2]
  690. instances = labels.pop("instances")
  691. instances.convert_bbox(format="xyxy")
  692. instances.denormalize(w, h)
  693. if self.p and len(instances.segments):
  694. n = len(instances)
  695. _, w, _ = im.shape # height, width, channels
  696. im_new = np.zeros(im.shape, np.uint8)
  697. # Calculate ioa first then select indexes randomly
  698. ins_flip = deepcopy(instances)
  699. ins_flip.fliplr(w)
  700. ioa = bbox_ioa(ins_flip.bboxes, instances.bboxes) # intersection over area, (N, M)
  701. indexes = np.nonzero((ioa < 0.30).all(1))[0] # (N, )
  702. n = len(indexes)
  703. for j in random.sample(list(indexes), k=round(self.p * n)):
  704. cls = np.concatenate((cls, cls[[j]]), axis=0)
  705. instances = Instances.concatenate((instances, ins_flip[[j]]), axis=0)
  706. cv2.drawContours(im_new, instances.segments[[j]].astype(np.int32), -1, (1, 1, 1), cv2.FILLED)
  707. result = cv2.flip(im, 1) # augment segments (flip left-right)
  708. i = cv2.flip(im_new, 1).astype(bool)
  709. im[i] = result[i]
  710. labels["img"] = im
  711. labels["cls"] = cls
  712. labels["instances"] = instances
  713. return labels
  714. class Albumentations:
  715. """
  716. Albumentations transformations.
  717. Optional, uninstall package to disable. Applies Blur, Median Blur, convert to grayscale, Contrast Limited Adaptive
  718. Histogram Equalization, random change of brightness and contrast, RandomGamma and lowering of image quality by
  719. compression.
  720. """
  721. def __init__(self, p=1.0):
  722. """Initialize the transform object for YOLO bbox formatted params."""
  723. self.p = p
  724. self.transform = None
  725. prefix = colorstr("albumentations: ")
  726. try:
  727. import albumentations as A
  728. check_version(A.__version__, "1.0.3", hard=True) # version requirement
  729. # List of possible spatial transforms
  730. spatial_transforms = {
  731. "Affine",
  732. "BBoxSafeRandomCrop",
  733. "CenterCrop",
  734. "CoarseDropout",
  735. "Crop",
  736. "CropAndPad",
  737. "CropNonEmptyMaskIfExists",
  738. "D4",
  739. "ElasticTransform",
  740. "Flip",
  741. "GridDistortion",
  742. "GridDropout",
  743. "HorizontalFlip",
  744. "Lambda",
  745. "LongestMaxSize",
  746. "MaskDropout",
  747. "MixUp",
  748. "Morphological",
  749. "NoOp",
  750. "OpticalDistortion",
  751. "PadIfNeeded",
  752. "Perspective",
  753. "PiecewiseAffine",
  754. "PixelDropout",
  755. "RandomCrop",
  756. "RandomCropFromBorders",
  757. "RandomGridShuffle",
  758. "RandomResizedCrop",
  759. "RandomRotate90",
  760. "RandomScale",
  761. "RandomSizedBBoxSafeCrop",
  762. "RandomSizedCrop",
  763. "Resize",
  764. "Rotate",
  765. "SafeRotate",
  766. "ShiftScaleRotate",
  767. "SmallestMaxSize",
  768. "Transpose",
  769. "VerticalFlip",
  770. "XYMasking",
  771. } # from https://albumentations.ai/docs/getting_started/transforms_and_targets/#spatial-level-transforms
  772. # Transforms
  773. T = [
  774. A.Blur(p=0.01),
  775. A.MedianBlur(p=0.01),
  776. A.ToGray(p=0.01),
  777. A.CLAHE(p=0.01),
  778. A.RandomBrightnessContrast(p=0.0),
  779. A.RandomGamma(p=0.0),
  780. A.ImageCompression(quality_lower=75, p=0.0),
  781. ]
  782. # Compose transforms
  783. self.contains_spatial = any(transform.__class__.__name__ in spatial_transforms for transform in T)
  784. self.transform = (
  785. A.Compose(T, bbox_params=A.BboxParams(format="yolo", label_fields=["class_labels"]))
  786. if self.contains_spatial
  787. else A.Compose(T)
  788. )
  789. LOGGER.info(prefix + ", ".join(f"{x}".replace("always_apply=False, ", "") for x in T if x.p))
  790. except ImportError: # package not installed, skip
  791. pass
  792. except Exception as e:
  793. LOGGER.info(f"{prefix}{e}")
  794. def __call__(self, labels):
  795. """Generates object detections and returns a dictionary with detection results."""
  796. if self.transform is None or random.random() > self.p:
  797. return labels
  798. if self.contains_spatial:
  799. cls = labels["cls"]
  800. if len(cls):
  801. im = labels["img"]
  802. labels["instances"].convert_bbox("xywh")
  803. labels["instances"].normalize(*im.shape[:2][::-1])
  804. bboxes = labels["instances"].bboxes
  805. # TODO: add supports of segments and keypoints
  806. new = self.transform(image=im, bboxes=bboxes, class_labels=cls) # transformed
  807. if len(new["class_labels"]) > 0: # skip update if no bbox in new im
  808. labels["img"] = new["image"]
  809. labels["cls"] = np.array(new["class_labels"])
  810. bboxes = np.array(new["bboxes"], dtype=np.float32)
  811. labels["instances"].update(bboxes=bboxes)
  812. else:
  813. labels["img"] = self.transform(image=labels["img"])["image"] # transformed
  814. return labels
  815. class Format:
  816. """
  817. Formats image annotations for object detection, instance segmentation, and pose estimation tasks. The class
  818. standardizes the image and instance annotations to be used by the `collate_fn` in PyTorch DataLoader.
  819. Attributes:
  820. bbox_format (str): Format for bounding boxes. Default is 'xywh'.
  821. normalize (bool): Whether to normalize bounding boxes. Default is True.
  822. return_mask (bool): Return instance masks for segmentation. Default is False.
  823. return_keypoint (bool): Return keypoints for pose estimation. Default is False.
  824. mask_ratio (int): Downsample ratio for masks. Default is 4.
  825. mask_overlap (bool): Whether to overlap masks. Default is True.
  826. batch_idx (bool): Keep batch indexes. Default is True.
  827. bgr (float): The probability to return BGR images. Default is 0.0.
  828. """
  829. def __init__(
  830. self,
  831. bbox_format="xywh",
  832. normalize=True,
  833. return_mask=False,
  834. return_keypoint=False,
  835. return_obb=False,
  836. mask_ratio=4,
  837. mask_overlap=True,
  838. batch_idx=True,
  839. bgr=0.0,
  840. ):
  841. """Initializes the Format class with given parameters."""
  842. self.bbox_format = bbox_format
  843. self.normalize = normalize
  844. self.return_mask = return_mask # set False when training detection only
  845. self.return_keypoint = return_keypoint
  846. self.return_obb = return_obb
  847. self.mask_ratio = mask_ratio
  848. self.mask_overlap = mask_overlap
  849. self.batch_idx = batch_idx # keep the batch indexes
  850. self.bgr = bgr
  851. def __call__(self, labels):
  852. """Return formatted image, classes, bounding boxes & keypoints to be used by 'collate_fn'."""
  853. img = labels.pop("img")
  854. h, w = img.shape[:2]
  855. cls = labels.pop("cls")
  856. instances = labels.pop("instances")
  857. instances.convert_bbox(format=self.bbox_format)
  858. instances.denormalize(w, h)
  859. nl = len(instances)
  860. if self.return_mask:
  861. if nl:
  862. masks, instances, cls = self._format_segments(instances, cls, w, h)
  863. masks = torch.from_numpy(masks)
  864. else:
  865. masks = torch.zeros(
  866. 1 if self.mask_overlap else nl, img.shape[0] // self.mask_ratio, img.shape[1] // self.mask_ratio
  867. )
  868. labels["masks"] = masks
  869. labels["img"] = self._format_img(img)
  870. labels["cls"] = torch.from_numpy(cls) if nl else torch.zeros(nl)
  871. labels["bboxes"] = torch.from_numpy(instances.bboxes) if nl else torch.zeros((nl, 4))
  872. if self.return_keypoint:
  873. labels["keypoints"] = torch.from_numpy(instances.keypoints)
  874. if self.normalize:
  875. labels["keypoints"][..., 0] /= w
  876. labels["keypoints"][..., 1] /= h
  877. if self.return_obb:
  878. labels["bboxes"] = (
  879. xyxyxyxy2xywhr(torch.from_numpy(instances.segments)) if len(instances.segments) else torch.zeros((0, 5))
  880. )
  881. # NOTE: need to normalize obb in xywhr format for width-height consistency
  882. if self.normalize:
  883. labels["bboxes"][:, [0, 2]] /= w
  884. labels["bboxes"][:, [1, 3]] /= h
  885. # Then we can use collate_fn
  886. if self.batch_idx:
  887. labels["batch_idx"] = torch.zeros(nl)
  888. return labels
  889. def _format_img(self, img):
  890. """Format the image for YOLO from Numpy array to PyTorch tensor."""
  891. if len(img.shape) < 3:
  892. img = np.expand_dims(img, -1)
  893. img = img.transpose(2, 0, 1)
  894. img = np.ascontiguousarray(img[::-1] if random.uniform(0, 1) > self.bgr else img)
  895. img = torch.from_numpy(img)
  896. return img
  897. def _format_segments(self, instances, cls, w, h):
  898. """Convert polygon points to bitmap."""
  899. segments = instances.segments
  900. if self.mask_overlap:
  901. masks, sorted_idx = polygons2masks_overlap((h, w), segments, downsample_ratio=self.mask_ratio)
  902. masks = masks[None] # (640, 640) -> (1, 640, 640)
  903. instances = instances[sorted_idx]
  904. cls = cls[sorted_idx]
  905. else:
  906. masks = polygons2masks((h, w), segments, color=1, downsample_ratio=self.mask_ratio)
  907. return masks, instances, cls
  908. class RandomLoadText:
  909. """
  910. Randomly sample positive texts and negative texts and update the class indices accordingly to the number of samples.
  911. Attributes:
  912. prompt_format (str): Format for prompt. Default is '{}'.
  913. neg_samples (tuple[int]): A ranger to randomly sample negative texts, Default is (80, 80).
  914. max_samples (int): The max number of different text samples in one image, Default is 80.
  915. padding (bool): Whether to pad texts to max_samples. Default is False.
  916. padding_value (str): The padding text. Default is "".
  917. """
  918. def __init__(
  919. self,
  920. prompt_format: str = "{}",
  921. neg_samples: Tuple[int, int] = (80, 80),
  922. max_samples: int = 80,
  923. padding: bool = False,
  924. padding_value: str = "",
  925. ) -> None:
  926. """Initializes the RandomLoadText class with given parameters."""
  927. self.prompt_format = prompt_format
  928. self.neg_samples = neg_samples
  929. self.max_samples = max_samples
  930. self.padding = padding
  931. self.padding_value = padding_value
  932. def __call__(self, labels: dict) -> dict:
  933. """Return updated classes and texts."""
  934. assert "texts" in labels, "No texts found in labels."
  935. class_texts = labels["texts"]
  936. num_classes = len(class_texts)
  937. cls = np.asarray(labels.pop("cls"), dtype=int)
  938. pos_labels = np.unique(cls).tolist()
  939. if len(pos_labels) > self.max_samples:
  940. pos_labels = set(random.sample(pos_labels, k=self.max_samples))
  941. neg_samples = min(min(num_classes, self.max_samples) - len(pos_labels), random.randint(*self.neg_samples))
  942. neg_labels = [i for i in range(num_classes) if i not in pos_labels]
  943. neg_labels = random.sample(neg_labels, k=neg_samples)
  944. sampled_labels = pos_labels + neg_labels
  945. random.shuffle(sampled_labels)
  946. label2ids = {label: i for i, label in enumerate(sampled_labels)}
  947. valid_idx = np.zeros(len(labels["instances"]), dtype=bool)
  948. new_cls = []
  949. for i, label in enumerate(cls.squeeze(-1).tolist()):
  950. if label not in label2ids:
  951. continue
  952. valid_idx[i] = True
  953. new_cls.append([label2ids[label]])
  954. labels["instances"] = labels["instances"][valid_idx]
  955. labels["cls"] = np.array(new_cls)
  956. # Randomly select one prompt when there's more than one prompts
  957. texts = []
  958. for label in sampled_labels:
  959. prompts = class_texts[label]
  960. assert len(prompts) > 0
  961. prompt = self.prompt_format.format(prompts[random.randrange(len(prompts))])
  962. texts.append(prompt)
  963. if self.padding:
  964. valid_labels = len(pos_labels) + len(neg_labels)
  965. num_padding = self.max_samples - valid_labels
  966. if num_padding > 0:
  967. texts += [self.padding_value] * num_padding
  968. labels["texts"] = texts
  969. return labels
  970. def v8_transforms(dataset, imgsz, hyp, stretch=False):
  971. """Convert images to a size suitable for YOLOv8 training."""
  972. pre_transform = Compose(
  973. [
  974. Mosaic(dataset, imgsz=imgsz, p=hyp.mosaic),
  975. CopyPaste(p=hyp.copy_paste),
  976. RandomPerspective(
  977. degrees=hyp.degrees,
  978. translate=hyp.translate,
  979. scale=hyp.scale,
  980. shear=hyp.shear,
  981. perspective=hyp.perspective,
  982. pre_transform=None if stretch else LetterBox(new_shape=(imgsz, imgsz)),
  983. ),
  984. ]
  985. )
  986. flip_idx = dataset.data.get("flip_idx", []) # for keypoints augmentation
  987. if dataset.use_keypoints:
  988. kpt_shape = dataset.data.get("kpt_shape", None)
  989. if len(flip_idx) == 0 and hyp.fliplr > 0.0:
  990. hyp.fliplr = 0.0
  991. LOGGER.warning("WARNING ⚠️ No 'flip_idx' array defined in data.yaml, setting augmentation 'fliplr=0.0'")
  992. elif flip_idx and (len(flip_idx) != kpt_shape[0]):
  993. raise ValueError(f"data.yaml flip_idx={flip_idx} length must be equal to kpt_shape[0]={kpt_shape[0]}")
  994. return Compose(
  995. [
  996. pre_transform,
  997. MixUp(dataset, pre_transform=pre_transform, p=hyp.mixup),
  998. Albumentations(p=1.0),
  999. RandomHSV(hgain=hyp.hsv_h, sgain=hyp.hsv_s, vgain=hyp.hsv_v),
  1000. RandomFlip(direction="vertical", p=hyp.flipud),
  1001. RandomFlip(direction="horizontal", p=hyp.fliplr, flip_idx=flip_idx),
  1002. ]
  1003. ) # transforms
  1004. # Classification augmentations -----------------------------------------------------------------------------------------
  1005. def classify_transforms(
  1006. size=224,
  1007. mean=DEFAULT_MEAN,
  1008. std=DEFAULT_STD,
  1009. interpolation=Image.BILINEAR,
  1010. crop_fraction: float = DEFAULT_CROP_FRACTION,
  1011. ):
  1012. """
  1013. Classification transforms for evaluation/inference. Inspired by timm/data/transforms_factory.py.
  1014. Args:
  1015. size (int): image size
  1016. mean (tuple): mean values of RGB channels
  1017. std (tuple): std values of RGB channels
  1018. interpolation (T.InterpolationMode): interpolation mode. default is T.InterpolationMode.BILINEAR.
  1019. crop_fraction (float): fraction of image to crop. default is 1.0.
  1020. Returns:
  1021. (T.Compose): torchvision transforms
  1022. """
  1023. import torchvision.transforms as T # scope for faster 'import ultralytics'
  1024. if isinstance(size, (tuple, list)):
  1025. assert len(size) == 2, f"'size' tuples must be length 2, not length {len(size)}"
  1026. scale_size = tuple(math.floor(x / crop_fraction) for x in size)
  1027. else:
  1028. scale_size = math.floor(size / crop_fraction)
  1029. scale_size = (scale_size, scale_size)
  1030. # Aspect ratio is preserved, crops center within image, no borders are added, image is lost
  1031. if scale_size[0] == scale_size[1]:
  1032. # Simple case, use torchvision built-in Resize with the shortest edge mode (scalar size arg)
  1033. tfl = [T.Resize(scale_size[0], interpolation=interpolation)]
  1034. else:
  1035. # Resize the shortest edge to matching target dim for non-square target
  1036. tfl = [T.Resize(scale_size)]
  1037. tfl.extend(
  1038. [
  1039. T.CenterCrop(size),
  1040. T.ToTensor(),
  1041. T.Normalize(mean=torch.tensor(mean), std=torch.tensor(std)),
  1042. ]
  1043. )
  1044. return T.Compose(tfl)
  1045. # Classification training augmentations --------------------------------------------------------------------------------
  1046. def classify_augmentations(
  1047. size=224,
  1048. mean=DEFAULT_MEAN,
  1049. std=DEFAULT_STD,
  1050. scale=None,
  1051. ratio=None,
  1052. hflip=0.5,
  1053. vflip=0.0,
  1054. auto_augment=None,
  1055. hsv_h=0.015, # image HSV-Hue augmentation (fraction)
  1056. hsv_s=0.4, # image HSV-Saturation augmentation (fraction)
  1057. hsv_v=0.4, # image HSV-Value augmentation (fraction)
  1058. force_color_jitter=False,
  1059. erasing=0.0,
  1060. interpolation=Image.BILINEAR,
  1061. ):
  1062. """
  1063. Classification transforms with augmentation for training. Inspired by timm/data/transforms_factory.py.
  1064. Args:
  1065. size (int): image size
  1066. scale (tuple): scale range of the image. default is (0.08, 1.0)
  1067. ratio (tuple): aspect ratio range of the image. default is (3./4., 4./3.)
  1068. mean (tuple): mean values of RGB channels
  1069. std (tuple): std values of RGB channels
  1070. hflip (float): probability of horizontal flip
  1071. vflip (float): probability of vertical flip
  1072. auto_augment (str): auto augmentation policy. can be 'randaugment', 'augmix', 'autoaugment' or None.
  1073. hsv_h (float): image HSV-Hue augmentation (fraction)
  1074. hsv_s (float): image HSV-Saturation augmentation (fraction)
  1075. hsv_v (float): image HSV-Value augmentation (fraction)
  1076. force_color_jitter (bool): force to apply color jitter even if auto augment is enabled
  1077. erasing (float): probability of random erasing
  1078. interpolation (T.InterpolationMode): interpolation mode. default is T.InterpolationMode.BILINEAR.
  1079. Returns:
  1080. (T.Compose): torchvision transforms
  1081. """
  1082. # Transforms to apply if Albumentations not installed
  1083. import torchvision.transforms as T # scope for faster 'import ultralytics'
  1084. if not isinstance(size, int):
  1085. raise TypeError(f"classify_transforms() size {size} must be integer, not (list, tuple)")
  1086. scale = tuple(scale or (0.08, 1.0)) # default imagenet scale range
  1087. ratio = tuple(ratio or (3.0 / 4.0, 4.0 / 3.0)) # default imagenet ratio range
  1088. primary_tfl = [T.RandomResizedCrop(size, scale=scale, ratio=ratio, interpolation=interpolation)]
  1089. if hflip > 0.0:
  1090. primary_tfl.append(T.RandomHorizontalFlip(p=hflip))
  1091. if vflip > 0.0:
  1092. primary_tfl.append(T.RandomVerticalFlip(p=vflip))
  1093. secondary_tfl = []
  1094. disable_color_jitter = False
  1095. if auto_augment:
  1096. assert isinstance(auto_augment, str), f"Provided argument should be string, but got type {type(auto_augment)}"
  1097. # color jitter is typically disabled if AA/RA on,
  1098. # this allows override without breaking old hparm cfgs
  1099. disable_color_jitter = not force_color_jitter
  1100. if auto_augment == "randaugment":
  1101. if TORCHVISION_0_11:
  1102. secondary_tfl.append(T.RandAugment(interpolation=interpolation))
  1103. else:
  1104. LOGGER.warning('"auto_augment=randaugment" requires torchvision >= 0.11.0. Disabling it.')
  1105. elif auto_augment == "augmix":
  1106. if TORCHVISION_0_13:
  1107. secondary_tfl.append(T.AugMix(interpolation=interpolation))
  1108. else:
  1109. LOGGER.warning('"auto_augment=augmix" requires torchvision >= 0.13.0. Disabling it.')
  1110. elif auto_augment == "autoaugment":
  1111. if TORCHVISION_0_10:
  1112. secondary_tfl.append(T.AutoAugment(interpolation=interpolation))
  1113. else:
  1114. LOGGER.warning('"auto_augment=autoaugment" requires torchvision >= 0.10.0. Disabling it.')
  1115. else:
  1116. raise ValueError(
  1117. f'Invalid auto_augment policy: {auto_augment}. Should be one of "randaugment", '
  1118. f'"augmix", "autoaugment" or None'
  1119. )
  1120. if not disable_color_jitter:
  1121. secondary_tfl.append(T.ColorJitter(brightness=hsv_v, contrast=hsv_v, saturation=hsv_s, hue=hsv_h))
  1122. final_tfl = [
  1123. T.ToTensor(),
  1124. T.Normalize(mean=torch.tensor(mean), std=torch.tensor(std)),
  1125. T.RandomErasing(p=erasing, inplace=True),
  1126. ]
  1127. return T.Compose(primary_tfl + secondary_tfl + final_tfl)
  1128. # NOTE: keep this class for backward compatibility
  1129. class ClassifyLetterBox:
  1130. """
  1131. YOLOv8 LetterBox class for image preprocessing, designed to be part of a transformation pipeline, e.g.,
  1132. T.Compose([LetterBox(size), ToTensor()]).
  1133. Attributes:
  1134. h (int): Target height of the image.
  1135. w (int): Target width of the image.
  1136. auto (bool): If True, automatically solves for short side using stride.
  1137. stride (int): The stride value, used when 'auto' is True.
  1138. """
  1139. def __init__(self, size=(640, 640), auto=False, stride=32):
  1140. """
  1141. Initializes the ClassifyLetterBox class with a target size, auto-flag, and stride.
  1142. Args:
  1143. size (Union[int, Tuple[int, int]]): The target dimensions (height, width) for the letterbox.
  1144. auto (bool): If True, automatically calculates the short side based on stride.
  1145. stride (int): The stride value, used when 'auto' is True.
  1146. """
  1147. super().__init__()
  1148. self.h, self.w = (size, size) if isinstance(size, int) else size
  1149. self.auto = auto # pass max size integer, automatically solve for short side using stride
  1150. self.stride = stride # used with auto
  1151. def __call__(self, im):
  1152. """
  1153. Resizes the image and pads it with a letterbox method.
  1154. Args:
  1155. im (numpy.ndarray): The input image as a numpy array of shape HWC.
  1156. Returns:
  1157. (numpy.ndarray): The letterboxed and resized image as a numpy array.
  1158. """
  1159. imh, imw = im.shape[:2]
  1160. r = min(self.h / imh, self.w / imw) # ratio of new/old dimensions
  1161. h, w = round(imh * r), round(imw * r) # resized image dimensions
  1162. # Calculate padding dimensions
  1163. hs, ws = (math.ceil(x / self.stride) * self.stride for x in (h, w)) if self.auto else (self.h, self.w)
  1164. top, left = round((hs - h) / 2 - 0.1), round((ws - w) / 2 - 0.1)
  1165. # Create padded image
  1166. im_out = np.full((hs, ws, 3), 114, dtype=im.dtype)
  1167. im_out[top : top + h, left : left + w] = cv2.resize(im, (w, h), interpolation=cv2.INTER_LINEAR)
  1168. return im_out
  1169. # NOTE: keep this class for backward compatibility
  1170. class CenterCrop:
  1171. """YOLOv8 CenterCrop class for image preprocessing, designed to be part of a transformation pipeline, e.g.,
  1172. T.Compose([CenterCrop(size), ToTensor()]).
  1173. """
  1174. def __init__(self, size=640):
  1175. """Converts an image from numpy array to PyTorch tensor."""
  1176. super().__init__()
  1177. self.h, self.w = (size, size) if isinstance(size, int) else size
  1178. def __call__(self, im):
  1179. """
  1180. Resizes and crops the center of the image using a letterbox method.
  1181. Args:
  1182. im (numpy.ndarray): The input image as a numpy array of shape HWC.
  1183. Returns:
  1184. (numpy.ndarray): The center-cropped and resized image as a numpy array.
  1185. """
  1186. imh, imw = im.shape[:2]
  1187. m = min(imh, imw) # min dimension
  1188. top, left = (imh - m) // 2, (imw - m) // 2
  1189. return cv2.resize(im[top : top + m, left : left + m], (self.w, self.h), interpolation=cv2.INTER_LINEAR)
  1190. # NOTE: keep this class for backward compatibility
  1191. class ToTensor:
  1192. """YOLOv8 ToTensor class for image preprocessing, i.e., T.Compose([LetterBox(size), ToTensor()])."""
  1193. def __init__(self, half=False):
  1194. """Initialize YOLOv8 ToTensor object with optional half-precision support."""
  1195. super().__init__()
  1196. self.half = half
  1197. def __call__(self, im):
  1198. """
  1199. Transforms an image from a numpy array to a PyTorch tensor, applying optional half-precision and normalization.
  1200. Args:
  1201. im (numpy.ndarray): Input image as a numpy array with shape (H, W, C) in BGR order.
  1202. Returns:
  1203. (torch.Tensor): The transformed image as a PyTorch tensor in float32 or float16, normalized to [0, 1].
  1204. """
  1205. im = np.ascontiguousarray(im.transpose((2, 0, 1))[::-1]) # HWC to CHW -> BGR to RGB -> contiguous
  1206. im = torch.from_numpy(im) # to torch
  1207. im = im.half() if self.half else im.float() # uint8 to fp16/32
  1208. im /= 255.0 # 0-255 to 0.0-1.0
  1209. return im