augment.py 118 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744
  1. # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/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. class BaseTransform:
  21. """
  22. Base class for image transformations in the Ultralytics library.
  23. This class serves as a foundation for implementing various image processing operations, designed to be
  24. compatible with both classification and semantic segmentation tasks.
  25. Methods:
  26. apply_image: Applies image transformations to labels.
  27. apply_instances: Applies transformations to object instances in labels.
  28. apply_semantic: Applies semantic segmentation to an image.
  29. __call__: Applies all label transformations to an image, instances, and semantic masks.
  30. Examples:
  31. >>> transform = BaseTransform()
  32. >>> labels = {"image": np.array(...), "instances": [...], "semantic": np.array(...)}
  33. >>> transformed_labels = transform(labels)
  34. """
  35. def __init__(self) -> None:
  36. """
  37. Initializes the BaseTransform object.
  38. This constructor sets up the base transformation object, which can be extended for specific image
  39. processing tasks. It is designed to be compatible with both classification and semantic segmentation.
  40. Examples:
  41. >>> transform = BaseTransform()
  42. """
  43. pass
  44. def apply_image(self, labels):
  45. """
  46. Applies image transformations to labels.
  47. This method is intended to be overridden by subclasses to implement specific image transformation
  48. logic. In its base form, it returns the input labels unchanged.
  49. Args:
  50. labels (Any): The input labels to be transformed. The exact type and structure of labels may
  51. vary depending on the specific implementation.
  52. Returns:
  53. (Any): The transformed labels. In the base implementation, this is identical to the input.
  54. Examples:
  55. >>> transform = BaseTransform()
  56. >>> original_labels = [1, 2, 3]
  57. >>> transformed_labels = transform.apply_image(original_labels)
  58. >>> print(transformed_labels)
  59. [1, 2, 3]
  60. """
  61. pass
  62. def apply_instances(self, labels):
  63. """
  64. Applies transformations to object instances in labels.
  65. This method is responsible for applying various transformations to object instances within the given
  66. labels. It is designed to be overridden by subclasses to implement specific instance transformation
  67. logic.
  68. Args:
  69. labels (Dict): A dictionary containing label information, including object instances.
  70. Returns:
  71. (Dict): The modified labels dictionary with transformed object instances.
  72. Examples:
  73. >>> transform = BaseTransform()
  74. >>> labels = {"instances": Instances(xyxy=torch.rand(5, 4), cls=torch.randint(0, 80, (5,)))}
  75. >>> transformed_labels = transform.apply_instances(labels)
  76. """
  77. pass
  78. def apply_semantic(self, labels):
  79. """
  80. Applies semantic segmentation transformations to an image.
  81. This method is intended to be overridden by subclasses to implement specific semantic segmentation
  82. transformations. In its base form, it does not perform any operations.
  83. Args:
  84. labels (Any): The input labels or semantic segmentation mask to be transformed.
  85. Returns:
  86. (Any): The transformed semantic segmentation mask or labels.
  87. Examples:
  88. >>> transform = BaseTransform()
  89. >>> semantic_mask = np.zeros((100, 100), dtype=np.uint8)
  90. >>> transformed_mask = transform.apply_semantic(semantic_mask)
  91. """
  92. pass
  93. def __call__(self, labels):
  94. """
  95. Applies all label transformations to an image, instances, and semantic masks.
  96. This method orchestrates the application of various transformations defined in the BaseTransform class
  97. to the input labels. It sequentially calls the apply_image and apply_instances methods to process the
  98. image and object instances, respectively.
  99. Args:
  100. labels (Dict): A dictionary containing image data and annotations. Expected keys include 'img' for
  101. the image data, and 'instances' for object instances.
  102. Returns:
  103. (Dict): The input labels dictionary with transformed image and instances.
  104. Examples:
  105. >>> transform = BaseTransform()
  106. >>> labels = {"img": np.random.rand(640, 640, 3), "instances": []}
  107. >>> transformed_labels = transform(labels)
  108. """
  109. self.apply_image(labels)
  110. self.apply_instances(labels)
  111. self.apply_semantic(labels)
  112. class Compose:
  113. """
  114. A class for composing multiple image transformations.
  115. Attributes:
  116. transforms (List[Callable]): A list of transformation functions to be applied sequentially.
  117. Methods:
  118. __call__: Applies a series of transformations to input data.
  119. append: Appends a new transform to the existing list of transforms.
  120. insert: Inserts a new transform at a specified index in the list of transforms.
  121. __getitem__: Retrieves a specific transform or a set of transforms using indexing.
  122. __setitem__: Sets a specific transform or a set of transforms using indexing.
  123. tolist: Converts the list of transforms to a standard Python list.
  124. Examples:
  125. >>> transforms = [RandomFlip(), RandomPerspective(30)]
  126. >>> compose = Compose(transforms)
  127. >>> transformed_data = compose(data)
  128. >>> compose.append(CenterCrop((224, 224)))
  129. >>> compose.insert(0, RandomFlip())
  130. """
  131. def __init__(self, transforms):
  132. """
  133. Initializes the Compose object with a list of transforms.
  134. Args:
  135. transforms (List[Callable]): A list of callable transform objects to be applied sequentially.
  136. Examples:
  137. >>> from ultralytics.data.augment import Compose, RandomHSV, RandomFlip
  138. >>> transforms = [RandomHSV(), RandomFlip()]
  139. >>> compose = Compose(transforms)
  140. """
  141. self.transforms = transforms if isinstance(transforms, list) else [transforms]
  142. def __call__(self, data):
  143. """
  144. Applies a series of transformations to input data. This method sequentially applies each transformation in the
  145. Compose object's list of transforms to the input data.
  146. Args:
  147. data (Any): The input data to be transformed. This can be of any type, depending on the
  148. transformations in the list.
  149. Returns:
  150. (Any): The transformed data after applying all transformations in sequence.
  151. Examples:
  152. >>> transforms = [Transform1(), Transform2(), Transform3()]
  153. >>> compose = Compose(transforms)
  154. >>> transformed_data = compose(input_data)
  155. """
  156. for t in self.transforms:
  157. data = t(data)
  158. return data
  159. def append(self, transform):
  160. """
  161. Appends a new transform to the existing list of transforms.
  162. Args:
  163. transform (BaseTransform): The transformation to be added to the composition.
  164. Examples:
  165. >>> compose = Compose([RandomFlip(), RandomPerspective()])
  166. >>> compose.append(RandomHSV())
  167. """
  168. self.transforms.append(transform)
  169. def insert(self, index, transform):
  170. """
  171. Inserts a new transform at a specified index in the existing list of transforms.
  172. Args:
  173. index (int): The index at which to insert the new transform.
  174. transform (BaseTransform): The transform object to be inserted.
  175. Examples:
  176. >>> compose = Compose([Transform1(), Transform2()])
  177. >>> compose.insert(1, Transform3())
  178. >>> len(compose.transforms)
  179. 3
  180. """
  181. self.transforms.insert(index, transform)
  182. def __getitem__(self, index: Union[list, int]) -> "Compose":
  183. """
  184. Retrieves a specific transform or a set of transforms using indexing.
  185. Args:
  186. index (int | List[int]): Index or list of indices of the transforms to retrieve.
  187. Returns:
  188. (Compose): A new Compose object containing the selected transform(s).
  189. Raises:
  190. AssertionError: If the index is not of type int or list.
  191. Examples:
  192. >>> transforms = [RandomFlip(), RandomPerspective(10), RandomHSV(0.5, 0.5, 0.5)]
  193. >>> compose = Compose(transforms)
  194. >>> single_transform = compose[1] # Returns a Compose object with only RandomPerspective
  195. >>> multiple_transforms = compose[0:2] # Returns a Compose object with RandomFlip and RandomPerspective
  196. """
  197. assert isinstance(index, (int, list)), f"The indices should be either list or int type but got {type(index)}"
  198. index = [index] if isinstance(index, int) else index
  199. return Compose([self.transforms[i] for i in index])
  200. def __setitem__(self, index: Union[list, int], value: Union[list, int]) -> None:
  201. """
  202. Sets one or more transforms in the composition using indexing.
  203. Args:
  204. index (int | List[int]): Index or list of indices to set transforms at.
  205. value (Any | List[Any]): Transform or list of transforms to set at the specified index(es).
  206. Raises:
  207. AssertionError: If index type is invalid, value type doesn't match index type, or index is out of range.
  208. Examples:
  209. >>> compose = Compose([Transform1(), Transform2(), Transform3()])
  210. >>> compose[1] = NewTransform() # Replace second transform
  211. >>> compose[0:2] = [NewTransform1(), NewTransform2()] # Replace first two transforms
  212. """
  213. assert isinstance(index, (int, list)), f"The indices should be either list or int type but got {type(index)}"
  214. if isinstance(index, list):
  215. assert isinstance(value, list), (
  216. f"The indices should be the same type as values, but got {type(index)} and {type(value)}"
  217. )
  218. if isinstance(index, int):
  219. index, value = [index], [value]
  220. for i, v in zip(index, value):
  221. assert i < len(self.transforms), f"list index {i} out of range {len(self.transforms)}."
  222. self.transforms[i] = v
  223. def tolist(self):
  224. """
  225. Converts the list of transforms to a standard Python list.
  226. Returns:
  227. (List): A list containing all the transform objects in the Compose instance.
  228. Examples:
  229. >>> transforms = [RandomFlip(), RandomPerspective(10), CenterCrop()]
  230. >>> compose = Compose(transforms)
  231. >>> transform_list = compose.tolist()
  232. >>> print(len(transform_list))
  233. 3
  234. """
  235. return self.transforms
  236. def __repr__(self):
  237. """
  238. Returns a string representation of the Compose object.
  239. Returns:
  240. (str): A string representation of the Compose object, including the list of transforms.
  241. Examples:
  242. >>> transforms = [RandomFlip(), RandomPerspective(degrees=10, translate=0.1, scale=0.1)]
  243. >>> compose = Compose(transforms)
  244. >>> print(compose)
  245. Compose([
  246. RandomFlip(),
  247. RandomPerspective(degrees=10, translate=0.1, scale=0.1)
  248. ])
  249. """
  250. return f"{self.__class__.__name__}({', '.join([f'{t}' for t in self.transforms])})"
  251. class BaseMixTransform:
  252. """
  253. Base class for mix transformations like MixUp and Mosaic.
  254. This class provides a foundation for implementing mix transformations on datasets. It handles the
  255. probability-based application of transforms and manages the mixing of multiple images and labels.
  256. Attributes:
  257. dataset (Any): The dataset object containing images and labels.
  258. pre_transform (Callable | None): Optional transform to apply before mixing.
  259. p (float): Probability of applying the mix transformation.
  260. Methods:
  261. __call__: Applies the mix transformation to the input labels.
  262. _mix_transform: Abstract method to be implemented by subclasses for specific mix operations.
  263. get_indexes: Abstract method to get indexes of images to be mixed.
  264. _update_label_text: Updates label text for mixed images.
  265. Examples:
  266. >>> class CustomMixTransform(BaseMixTransform):
  267. ... def _mix_transform(self, labels):
  268. ... # Implement custom mix logic here
  269. ... return labels
  270. ...
  271. ... def get_indexes(self):
  272. ... return [random.randint(0, len(self.dataset) - 1) for _ in range(3)]
  273. >>> dataset = YourDataset()
  274. >>> transform = CustomMixTransform(dataset, p=0.5)
  275. >>> mixed_labels = transform(original_labels)
  276. """
  277. def __init__(self, dataset, pre_transform=None, p=0.0) -> None:
  278. """
  279. Initializes the BaseMixTransform object for mix transformations like MixUp and Mosaic.
  280. This class serves as a base for implementing mix transformations in image processing pipelines.
  281. Args:
  282. dataset (Any): The dataset object containing images and labels for mixing.
  283. pre_transform (Callable | None): Optional transform to apply before mixing.
  284. p (float): Probability of applying the mix transformation. Should be in the range [0.0, 1.0].
  285. Examples:
  286. >>> dataset = YOLODataset("path/to/data")
  287. >>> pre_transform = Compose([RandomFlip(), RandomPerspective()])
  288. >>> mix_transform = BaseMixTransform(dataset, pre_transform, p=0.5)
  289. """
  290. self.dataset = dataset
  291. self.pre_transform = pre_transform
  292. self.p = p
  293. def __call__(self, labels):
  294. """
  295. Applies pre-processing transforms and mixup/mosaic transforms to labels data.
  296. This method determines whether to apply the mix transform based on a probability factor. If applied, it
  297. selects additional images, applies pre-transforms if specified, and then performs the mix transform.
  298. Args:
  299. labels (Dict): A dictionary containing label data for an image.
  300. Returns:
  301. (Dict): The transformed labels dictionary, which may include mixed data from other images.
  302. Examples:
  303. >>> transform = BaseMixTransform(dataset, pre_transform=None, p=0.5)
  304. >>> result = transform({"image": img, "bboxes": boxes, "cls": classes})
  305. """
  306. if random.uniform(0, 1) > self.p:
  307. return labels
  308. # Get index of one or three other images
  309. indexes = self.get_indexes()
  310. if isinstance(indexes, int):
  311. indexes = [indexes]
  312. # Get images information will be used for Mosaic or MixUp
  313. mix_labels = [self.dataset.get_image_and_label(i) for i in indexes]
  314. if self.pre_transform is not None:
  315. for i, data in enumerate(mix_labels):
  316. mix_labels[i] = self.pre_transform(data)
  317. labels["mix_labels"] = mix_labels
  318. # Update cls and texts
  319. labels = self._update_label_text(labels)
  320. # Mosaic or MixUp
  321. labels = self._mix_transform(labels)
  322. labels.pop("mix_labels", None)
  323. return labels
  324. def _mix_transform(self, labels):
  325. """
  326. Applies MixUp or Mosaic augmentation to the label dictionary.
  327. This method should be implemented by subclasses to perform specific mix transformations like MixUp or
  328. Mosaic. It modifies the input label dictionary in-place with the augmented data.
  329. Args:
  330. labels (Dict): A dictionary containing image and label data. Expected to have a 'mix_labels' key
  331. with a list of additional image and label data for mixing.
  332. Returns:
  333. (Dict): The modified labels dictionary with augmented data after applying the mix transform.
  334. Examples:
  335. >>> transform = BaseMixTransform(dataset)
  336. >>> labels = {"image": img, "bboxes": boxes, "mix_labels": [{"image": img2, "bboxes": boxes2}]}
  337. >>> augmented_labels = transform._mix_transform(labels)
  338. """
  339. raise NotImplementedError
  340. def get_indexes(self):
  341. """
  342. Gets a list of shuffled indexes for mosaic augmentation.
  343. Returns:
  344. (List[int]): A list of shuffled indexes from the dataset.
  345. Examples:
  346. >>> transform = BaseMixTransform(dataset)
  347. >>> indexes = transform.get_indexes()
  348. >>> print(indexes) # [3, 18, 7, 2]
  349. """
  350. raise NotImplementedError
  351. @staticmethod
  352. def _update_label_text(labels):
  353. """
  354. Updates label text and class IDs for mixed labels in image augmentation.
  355. This method processes the 'texts' and 'cls' fields of the input labels dictionary and any mixed labels,
  356. creating a unified set of text labels and updating class IDs accordingly.
  357. Args:
  358. labels (Dict): A dictionary containing label information, including 'texts' and 'cls' fields,
  359. and optionally a 'mix_labels' field with additional label dictionaries.
  360. Returns:
  361. (Dict): The updated labels dictionary with unified text labels and updated class IDs.
  362. Examples:
  363. >>> labels = {
  364. ... "texts": [["cat"], ["dog"]],
  365. ... "cls": torch.tensor([[0], [1]]),
  366. ... "mix_labels": [{"texts": [["bird"], ["fish"]], "cls": torch.tensor([[0], [1]])}],
  367. ... }
  368. >>> updated_labels = self._update_label_text(labels)
  369. >>> print(updated_labels["texts"])
  370. [['cat'], ['dog'], ['bird'], ['fish']]
  371. >>> print(updated_labels["cls"])
  372. tensor([[0],
  373. [1]])
  374. >>> print(updated_labels["mix_labels"][0]["cls"])
  375. tensor([[2],
  376. [3]])
  377. """
  378. if "texts" not in labels:
  379. return labels
  380. mix_texts = sum([labels["texts"]] + [x["texts"] for x in labels["mix_labels"]], [])
  381. mix_texts = list({tuple(x) for x in mix_texts})
  382. text2id = {text: i for i, text in enumerate(mix_texts)}
  383. for label in [labels] + labels["mix_labels"]:
  384. for i, cls in enumerate(label["cls"].squeeze(-1).tolist()):
  385. text = label["texts"][int(cls)]
  386. label["cls"][i] = text2id[tuple(text)]
  387. label["texts"] = mix_texts
  388. return labels
  389. class Mosaic(BaseMixTransform):
  390. """
  391. Mosaic augmentation for image datasets.
  392. This class performs mosaic augmentation by combining multiple (4 or 9) images into a single mosaic image.
  393. The augmentation is applied to a dataset with a given probability.
  394. Attributes:
  395. dataset: The dataset on which the mosaic augmentation is applied.
  396. imgsz (int): Image size (height and width) after mosaic pipeline of a single image.
  397. p (float): Probability of applying the mosaic augmentation. Must be in the range 0-1.
  398. n (int): The grid size, either 4 (for 2x2) or 9 (for 3x3).
  399. border (Tuple[int, int]): Border size for width and height.
  400. Methods:
  401. get_indexes: Returns a list of random indexes from the dataset.
  402. _mix_transform: Applies mixup transformation to the input image and labels.
  403. _mosaic3: Creates a 1x3 image mosaic.
  404. _mosaic4: Creates a 2x2 image mosaic.
  405. _mosaic9: Creates a 3x3 image mosaic.
  406. _update_labels: Updates labels with padding.
  407. _cat_labels: Concatenates labels and clips mosaic border instances.
  408. Examples:
  409. >>> from ultralytics.data.augment import Mosaic
  410. >>> dataset = YourDataset(...) # Your image dataset
  411. >>> mosaic_aug = Mosaic(dataset, imgsz=640, p=0.5, n=4)
  412. >>> augmented_labels = mosaic_aug(original_labels)
  413. """
  414. def __init__(self, dataset, imgsz=640, p=1.0, n=4):
  415. """
  416. Initializes the Mosaic augmentation object.
  417. This class performs mosaic augmentation by combining multiple (4 or 9) images into a single mosaic image.
  418. The augmentation is applied to a dataset with a given probability.
  419. Args:
  420. dataset (Any): The dataset on which the mosaic augmentation is applied.
  421. imgsz (int): Image size (height and width) after mosaic pipeline of a single image.
  422. p (float): Probability of applying the mosaic augmentation. Must be in the range 0-1.
  423. n (int): The grid size, either 4 (for 2x2) or 9 (for 3x3).
  424. Examples:
  425. >>> from ultralytics.data.augment import Mosaic
  426. >>> dataset = YourDataset(...)
  427. >>> mosaic_aug = Mosaic(dataset, imgsz=640, p=0.5, n=4)
  428. """
  429. assert 0 <= p <= 1.0, f"The probability should be in range [0, 1], but got {p}."
  430. assert n in {4, 9}, "grid must be equal to 4 or 9."
  431. super().__init__(dataset=dataset, p=p)
  432. self.imgsz = imgsz
  433. self.border = (-imgsz // 2, -imgsz // 2) # width, height
  434. self.n = n
  435. def get_indexes(self, buffer=True):
  436. """
  437. Returns a list of random indexes from the dataset for mosaic augmentation.
  438. This method selects random image indexes either from a buffer or from the entire dataset, depending on
  439. the 'buffer' parameter. It is used to choose images for creating mosaic augmentations.
  440. Args:
  441. buffer (bool): If True, selects images from the dataset buffer. If False, selects from the entire
  442. dataset.
  443. Returns:
  444. (List[int]): A list of random image indexes. The length of the list is n-1, where n is the number
  445. of images used in the mosaic (either 3 or 8, depending on whether n is 4 or 9).
  446. Examples:
  447. >>> mosaic = Mosaic(dataset, imgsz=640, p=1.0, n=4)
  448. >>> indexes = mosaic.get_indexes()
  449. >>> print(len(indexes)) # Output: 3
  450. """
  451. if buffer: # select images from buffer
  452. return random.choices(list(self.dataset.buffer), k=self.n - 1)
  453. else: # select any images
  454. return [random.randint(0, len(self.dataset) - 1) for _ in range(self.n - 1)]
  455. def _mix_transform(self, labels):
  456. """
  457. Applies mosaic augmentation to the input image and labels.
  458. This method combines multiple images (3, 4, or 9) into a single mosaic image based on the 'n' attribute.
  459. It ensures that rectangular annotations are not present and that there are other images available for
  460. mosaic augmentation.
  461. Args:
  462. labels (Dict): A dictionary containing image data and annotations. Expected keys include:
  463. - 'rect_shape': Should be None as rect and mosaic are mutually exclusive.
  464. - 'mix_labels': A list of dictionaries containing data for other images to be used in the mosaic.
  465. Returns:
  466. (Dict): A dictionary containing the mosaic-augmented image and updated annotations.
  467. Raises:
  468. AssertionError: If 'rect_shape' is not None or if 'mix_labels' is empty.
  469. Examples:
  470. >>> mosaic = Mosaic(dataset, imgsz=640, p=1.0, n=4)
  471. >>> augmented_data = mosaic._mix_transform(labels)
  472. """
  473. assert labels.get("rect_shape", None) is None, "rect and mosaic are mutually exclusive."
  474. assert len(labels.get("mix_labels", [])), "There are no other images for mosaic augment."
  475. return (
  476. self._mosaic3(labels) if self.n == 3 else self._mosaic4(labels) if self.n == 4 else self._mosaic9(labels)
  477. ) # This code is modified for mosaic3 method.
  478. def _mosaic3(self, labels):
  479. """
  480. Creates a 1x3 image mosaic by combining three images.
  481. This method arranges three images in a horizontal layout, with the main image in the center and two
  482. additional images on either side. It's part of the Mosaic augmentation technique used in object detection.
  483. Args:
  484. labels (Dict): A dictionary containing image and label information for the main (center) image.
  485. Must include 'img' key with the image array, and 'mix_labels' key with a list of two
  486. dictionaries containing information for the side images.
  487. Returns:
  488. (Dict): A dictionary with the mosaic image and updated labels. Keys include:
  489. - 'img' (np.ndarray): The mosaic image array with shape (H, W, C).
  490. - Other keys from the input labels, updated to reflect the new image dimensions.
  491. Examples:
  492. >>> mosaic = Mosaic(dataset, imgsz=640, p=1.0, n=3)
  493. >>> labels = {
  494. ... "img": np.random.rand(480, 640, 3),
  495. ... "mix_labels": [{"img": np.random.rand(480, 640, 3)} for _ in range(2)],
  496. ... }
  497. >>> result = mosaic._mosaic3(labels)
  498. >>> print(result["img"].shape)
  499. (640, 640, 3)
  500. """
  501. mosaic_labels = []
  502. s = self.imgsz
  503. for i in range(3):
  504. labels_patch = labels if i == 0 else labels["mix_labels"][i - 1]
  505. # Load image
  506. img = labels_patch["img"]
  507. h, w = labels_patch.pop("resized_shape")
  508. # Place img in img3
  509. if i == 0: # center
  510. img3 = np.full((s * 3, s * 3, img.shape[2]), 114, dtype=np.uint8) # base image with 3 tiles
  511. h0, w0 = h, w
  512. c = s, s, s + w, s + h # xmin, ymin, xmax, ymax (base) coordinates
  513. elif i == 1: # right
  514. c = s + w0, s, s + w0 + w, s + h
  515. elif i == 2: # left
  516. c = s - w, s + h0 - h, s, s + h0
  517. padw, padh = c[:2]
  518. x1, y1, x2, y2 = (max(x, 0) for x in c) # allocate coordinates
  519. img3[y1:y2, x1:x2] = img[y1 - padh :, x1 - padw :] # img3[ymin:ymax, xmin:xmax]
  520. # hp, wp = h, w # height, width previous for next iteration
  521. # Labels assuming imgsz*2 mosaic size
  522. labels_patch = self._update_labels(labels_patch, padw + self.border[0], padh + self.border[1])
  523. mosaic_labels.append(labels_patch)
  524. final_labels = self._cat_labels(mosaic_labels)
  525. final_labels["img"] = img3[-self.border[0] : self.border[0], -self.border[1] : self.border[1]]
  526. return final_labels
  527. def _mosaic4(self, labels):
  528. """
  529. Creates a 2x2 image mosaic from four input images.
  530. This method combines four images into a single mosaic image by placing them in a 2x2 grid. It also
  531. updates the corresponding labels for each image in the mosaic.
  532. Args:
  533. labels (Dict): A dictionary containing image data and labels for the base image (index 0) and three
  534. additional images (indices 1-3) in the 'mix_labels' key.
  535. Returns:
  536. (Dict): A dictionary containing the mosaic image and updated labels. The 'img' key contains the mosaic
  537. image as a numpy array, and other keys contain the combined and adjusted labels for all four images.
  538. Examples:
  539. >>> mosaic = Mosaic(dataset, imgsz=640, p=1.0, n=4)
  540. >>> labels = {
  541. ... "img": np.random.rand(480, 640, 3),
  542. ... "mix_labels": [{"img": np.random.rand(480, 640, 3)} for _ in range(3)],
  543. ... }
  544. >>> result = mosaic._mosaic4(labels)
  545. >>> assert result["img"].shape == (1280, 1280, 3)
  546. """
  547. mosaic_labels = []
  548. s = self.imgsz
  549. yc, xc = (int(random.uniform(-x, 2 * s + x)) for x in self.border) # mosaic center x, y
  550. for i in range(4):
  551. labels_patch = labels if i == 0 else labels["mix_labels"][i - 1]
  552. # Load image
  553. img = labels_patch["img"]
  554. h, w = labels_patch.pop("resized_shape")
  555. # Place img in img4
  556. if i == 0: # top left
  557. img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
  558. x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image)
  559. x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image)
  560. elif i == 1: # top right
  561. x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc
  562. x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h
  563. elif i == 2: # bottom left
  564. x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h)
  565. x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h)
  566. elif i == 3: # bottom right
  567. x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h)
  568. x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)
  569. img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax]
  570. padw = x1a - x1b
  571. padh = y1a - y1b
  572. labels_patch = self._update_labels(labels_patch, padw, padh)
  573. mosaic_labels.append(labels_patch)
  574. final_labels = self._cat_labels(mosaic_labels)
  575. final_labels["img"] = img4
  576. return final_labels
  577. def _mosaic9(self, labels):
  578. """
  579. Creates a 3x3 image mosaic from the input image and eight additional images.
  580. This method combines nine images into a single mosaic image. The input image is placed at the center,
  581. and eight additional images from the dataset are placed around it in a 3x3 grid pattern.
  582. Args:
  583. labels (Dict): A dictionary containing the input image and its associated labels. It should have
  584. the following keys:
  585. - 'img' (numpy.ndarray): The input image.
  586. - 'resized_shape' (Tuple[int, int]): The shape of the resized image (height, width).
  587. - 'mix_labels' (List[Dict]): A list of dictionaries containing information for the additional
  588. eight images, each with the same structure as the input labels.
  589. Returns:
  590. (Dict): A dictionary containing the mosaic image and updated labels. It includes the following keys:
  591. - 'img' (numpy.ndarray): The final mosaic image.
  592. - Other keys from the input labels, updated to reflect the new mosaic arrangement.
  593. Examples:
  594. >>> mosaic = Mosaic(dataset, imgsz=640, p=1.0, n=9)
  595. >>> input_labels = dataset[0]
  596. >>> mosaic_result = mosaic._mosaic9(input_labels)
  597. >>> mosaic_image = mosaic_result["img"]
  598. """
  599. mosaic_labels = []
  600. s = self.imgsz
  601. hp, wp = -1, -1 # height, width previous
  602. for i in range(9):
  603. labels_patch = labels if i == 0 else labels["mix_labels"][i - 1]
  604. # Load image
  605. img = labels_patch["img"]
  606. h, w = labels_patch.pop("resized_shape")
  607. # Place img in img9
  608. if i == 0: # center
  609. img9 = np.full((s * 3, s * 3, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
  610. h0, w0 = h, w
  611. c = s, s, s + w, s + h # xmin, ymin, xmax, ymax (base) coordinates
  612. elif i == 1: # top
  613. c = s, s - h, s + w, s
  614. elif i == 2: # top right
  615. c = s + wp, s - h, s + wp + w, s
  616. elif i == 3: # right
  617. c = s + w0, s, s + w0 + w, s + h
  618. elif i == 4: # bottom right
  619. c = s + w0, s + hp, s + w0 + w, s + hp + h
  620. elif i == 5: # bottom
  621. c = s + w0 - w, s + h0, s + w0, s + h0 + h
  622. elif i == 6: # bottom left
  623. c = s + w0 - wp - w, s + h0, s + w0 - wp, s + h0 + h
  624. elif i == 7: # left
  625. c = s - w, s + h0 - h, s, s + h0
  626. elif i == 8: # top left
  627. c = s - w, s + h0 - hp - h, s, s + h0 - hp
  628. padw, padh = c[:2]
  629. x1, y1, x2, y2 = (max(x, 0) for x in c) # allocate coordinates
  630. # Image
  631. img9[y1:y2, x1:x2] = img[y1 - padh :, x1 - padw :] # img9[ymin:ymax, xmin:xmax]
  632. hp, wp = h, w # height, width previous for next iteration
  633. # Labels assuming imgsz*2 mosaic size
  634. labels_patch = self._update_labels(labels_patch, padw + self.border[0], padh + self.border[1])
  635. mosaic_labels.append(labels_patch)
  636. final_labels = self._cat_labels(mosaic_labels)
  637. final_labels["img"] = img9[-self.border[0] : self.border[0], -self.border[1] : self.border[1]]
  638. return final_labels
  639. @staticmethod
  640. def _update_labels(labels, padw, padh):
  641. """
  642. Updates label coordinates with padding values.
  643. This method adjusts the bounding box coordinates of object instances in the labels by adding padding
  644. values. It also denormalizes the coordinates if they were previously normalized.
  645. Args:
  646. labels (Dict): A dictionary containing image and instance information.
  647. padw (int): Padding width to be added to the x-coordinates.
  648. padh (int): Padding height to be added to the y-coordinates.
  649. Returns:
  650. (Dict): Updated labels dictionary with adjusted instance coordinates.
  651. Examples:
  652. >>> labels = {"img": np.zeros((100, 100, 3)), "instances": Instances(...)}
  653. >>> padw, padh = 50, 50
  654. >>> updated_labels = Mosaic._update_labels(labels, padw, padh)
  655. """
  656. nh, nw = labels["img"].shape[:2]
  657. labels["instances"].convert_bbox(format="xyxy")
  658. labels["instances"].denormalize(nw, nh)
  659. labels["instances"].add_padding(padw, padh)
  660. return labels
  661. def _cat_labels(self, mosaic_labels):
  662. """
  663. Concatenates and processes labels for mosaic augmentation.
  664. This method combines labels from multiple images used in mosaic augmentation, clips instances to the
  665. mosaic border, and removes zero-area boxes.
  666. Args:
  667. mosaic_labels (List[Dict]): A list of label dictionaries for each image in the mosaic.
  668. Returns:
  669. (Dict): A dictionary containing concatenated and processed labels for the mosaic image, including:
  670. - im_file (str): File path of the first image in the mosaic.
  671. - ori_shape (Tuple[int, int]): Original shape of the first image.
  672. - resized_shape (Tuple[int, int]): Shape of the mosaic image (imgsz * 2, imgsz * 2).
  673. - cls (np.ndarray): Concatenated class labels.
  674. - instances (Instances): Concatenated instance annotations.
  675. - mosaic_border (Tuple[int, int]): Mosaic border size.
  676. - texts (List[str], optional): Text labels if present in the original labels.
  677. Examples:
  678. >>> mosaic = Mosaic(dataset, imgsz=640)
  679. >>> mosaic_labels = [{"cls": np.array([0, 1]), "instances": Instances(...)} for _ in range(4)]
  680. >>> result = mosaic._cat_labels(mosaic_labels)
  681. >>> print(result.keys())
  682. dict_keys(['im_file', 'ori_shape', 'resized_shape', 'cls', 'instances', 'mosaic_border'])
  683. """
  684. if len(mosaic_labels) == 0:
  685. return {}
  686. cls = []
  687. instances = []
  688. imgsz = self.imgsz * 2 # mosaic imgsz
  689. for labels in mosaic_labels:
  690. cls.append(labels["cls"])
  691. instances.append(labels["instances"])
  692. # Final labels
  693. final_labels = {
  694. "im_file": mosaic_labels[0]["im_file"],
  695. "ori_shape": mosaic_labels[0]["ori_shape"],
  696. "resized_shape": (imgsz, imgsz),
  697. "cls": np.concatenate(cls, 0),
  698. "instances": Instances.concatenate(instances, axis=0),
  699. "mosaic_border": self.border,
  700. }
  701. final_labels["instances"].clip(imgsz, imgsz)
  702. good = final_labels["instances"].remove_zero_area_boxes()
  703. final_labels["cls"] = final_labels["cls"][good]
  704. if "texts" in mosaic_labels[0]:
  705. final_labels["texts"] = mosaic_labels[0]["texts"]
  706. return final_labels
  707. class MixUp(BaseMixTransform):
  708. """
  709. Applies MixUp augmentation to image datasets.
  710. This class implements the MixUp augmentation technique as described in the paper "mixup: Beyond Empirical Risk
  711. Minimization" (https://arxiv.org/abs/1710.09412). MixUp combines two images and their labels using a random weight.
  712. Attributes:
  713. dataset (Any): The dataset to which MixUp augmentation will be applied.
  714. pre_transform (Callable | None): Optional transform to apply before MixUp.
  715. p (float): Probability of applying MixUp augmentation.
  716. Methods:
  717. get_indexes: Returns a random index from the dataset.
  718. _mix_transform: Applies MixUp augmentation to the input labels.
  719. Examples:
  720. >>> from ultralytics.data.augment import MixUp
  721. >>> dataset = YourDataset(...) # Your image dataset
  722. >>> mixup = MixUp(dataset, p=0.5)
  723. >>> augmented_labels = mixup(original_labels)
  724. """
  725. def __init__(self, dataset, pre_transform=None, p=0.0) -> None:
  726. """
  727. Initializes the MixUp augmentation object.
  728. MixUp is an image augmentation technique that combines two images by taking a weighted sum of their pixel
  729. values and labels. This implementation is designed for use with the Ultralytics YOLO framework.
  730. Args:
  731. dataset (Any): The dataset to which MixUp augmentation will be applied.
  732. pre_transform (Callable | None): Optional transform to apply to images before MixUp.
  733. p (float): Probability of applying MixUp augmentation to an image. Must be in the range [0, 1].
  734. Examples:
  735. >>> from ultralytics.data.dataset import YOLODataset
  736. >>> dataset = YOLODataset("path/to/data.yaml")
  737. >>> mixup = MixUp(dataset, pre_transform=None, p=0.5)
  738. """
  739. super().__init__(dataset=dataset, pre_transform=pre_transform, p=p)
  740. def get_indexes(self):
  741. """
  742. Get a random index from the dataset.
  743. This method returns a single random index from the dataset, which is used to select an image for MixUp
  744. augmentation.
  745. Returns:
  746. (int): A random integer index within the range of the dataset length.
  747. Examples:
  748. >>> mixup = MixUp(dataset)
  749. >>> index = mixup.get_indexes()
  750. >>> print(index)
  751. 42
  752. """
  753. return random.randint(0, len(self.dataset) - 1)
  754. def _mix_transform(self, labels):
  755. """
  756. Applies MixUp augmentation to the input labels.
  757. This method implements the MixUp augmentation technique as described in the paper
  758. "mixup: Beyond Empirical Risk Minimization" (https://arxiv.org/abs/1710.09412).
  759. Args:
  760. labels (Dict): A dictionary containing the original image and label information.
  761. Returns:
  762. (Dict): A dictionary containing the mixed-up image and combined label information.
  763. Examples:
  764. >>> mixer = MixUp(dataset)
  765. >>> mixed_labels = mixer._mix_transform(labels)
  766. """
  767. r = np.random.beta(32.0, 32.0) # mixup ratio, alpha=beta=32.0
  768. labels2 = labels["mix_labels"][0]
  769. labels["img"] = (labels["img"] * r + labels2["img"] * (1 - r)).astype(np.uint8)
  770. labels["instances"] = Instances.concatenate([labels["instances"], labels2["instances"]], axis=0)
  771. labels["cls"] = np.concatenate([labels["cls"], labels2["cls"]], 0)
  772. return labels
  773. class RandomPerspective:
  774. """
  775. Implements random perspective and affine transformations on images and corresponding annotations.
  776. This class applies random rotations, translations, scaling, shearing, and perspective transformations
  777. to images and their associated bounding boxes, segments, and keypoints. It can be used as part of an
  778. augmentation pipeline for object detection and instance segmentation tasks.
  779. Attributes:
  780. degrees (float): Maximum absolute degree range for random rotations.
  781. translate (float): Maximum translation as a fraction of the image size.
  782. scale (float): Scaling factor range, e.g., scale=0.1 means 0.9-1.1.
  783. shear (float): Maximum shear angle in degrees.
  784. perspective (float): Perspective distortion factor.
  785. border (Tuple[int, int]): Mosaic border size as (x, y).
  786. pre_transform (Callable | None): Optional transform to apply before the random perspective.
  787. Methods:
  788. affine_transform: Applies affine transformations to the input image.
  789. apply_bboxes: Transforms bounding boxes using the affine matrix.
  790. apply_segments: Transforms segments and generates new bounding boxes.
  791. apply_keypoints: Transforms keypoints using the affine matrix.
  792. __call__: Applies the random perspective transformation to images and annotations.
  793. box_candidates: Filters transformed bounding boxes based on size and aspect ratio.
  794. Examples:
  795. >>> transform = RandomPerspective(degrees=10, translate=0.1, scale=0.1, shear=10)
  796. >>> image = np.random.randint(0, 255, (640, 640, 3), dtype=np.uint8)
  797. >>> labels = {"img": image, "cls": np.array([0, 1]), "instances": Instances(...)}
  798. >>> result = transform(labels)
  799. >>> transformed_image = result["img"]
  800. >>> transformed_instances = result["instances"]
  801. """
  802. def __init__(
  803. self, degrees=0.0, translate=0.1, scale=0.5, shear=0.0, perspective=0.0, border=(0, 0), pre_transform=None
  804. ):
  805. """
  806. Initializes RandomPerspective object with transformation parameters.
  807. This class implements random perspective and affine transformations on images and corresponding bounding boxes,
  808. segments, and keypoints. Transformations include rotation, translation, scaling, and shearing.
  809. Args:
  810. degrees (float): Degree range for random rotations.
  811. translate (float): Fraction of total width and height for random translation.
  812. scale (float): Scaling factor interval, e.g., a scale factor of 0.5 allows a resize between 50%-150%.
  813. shear (float): Shear intensity (angle in degrees).
  814. perspective (float): Perspective distortion factor.
  815. border (Tuple[int, int]): Tuple specifying mosaic border (top/bottom, left/right).
  816. pre_transform (Callable | None): Function/transform to apply to the image before starting the random
  817. transformation.
  818. Examples:
  819. >>> transform = RandomPerspective(degrees=10.0, translate=0.1, scale=0.5, shear=5.0)
  820. >>> result = transform(labels) # Apply random perspective to labels
  821. """
  822. self.degrees = degrees
  823. self.translate = translate
  824. self.scale = scale
  825. self.shear = shear
  826. self.perspective = perspective
  827. self.border = border # mosaic border
  828. self.pre_transform = pre_transform
  829. def affine_transform(self, img, border):
  830. """
  831. Applies a sequence of affine transformations centered around the image center.
  832. This function performs a series of geometric transformations on the input image, including
  833. translation, perspective change, rotation, scaling, and shearing. The transformations are
  834. applied in a specific order to maintain consistency.
  835. Args:
  836. img (np.ndarray): Input image to be transformed.
  837. border (Tuple[int, int]): Border dimensions for the transformed image.
  838. Returns:
  839. (Tuple[np.ndarray, np.ndarray, float]): A tuple containing:
  840. - np.ndarray: Transformed image.
  841. - np.ndarray: 3x3 transformation matrix.
  842. - float: Scale factor applied during the transformation.
  843. Examples:
  844. >>> import numpy as np
  845. >>> img = np.random.rand(100, 100, 3)
  846. >>> border = (10, 10)
  847. >>> transformed_img, matrix, scale = affine_transform(img, border)
  848. """
  849. # Center
  850. C = np.eye(3, dtype=np.float32)
  851. C[0, 2] = -img.shape[1] / 2 # x translation (pixels)
  852. C[1, 2] = -img.shape[0] / 2 # y translation (pixels)
  853. # Perspective
  854. P = np.eye(3, dtype=np.float32)
  855. P[2, 0] = random.uniform(-self.perspective, self.perspective) # x perspective (about y)
  856. P[2, 1] = random.uniform(-self.perspective, self.perspective) # y perspective (about x)
  857. # Rotation and Scale
  858. R = np.eye(3, dtype=np.float32)
  859. a = random.uniform(-self.degrees, self.degrees)
  860. # a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations
  861. s = random.uniform(1 - self.scale, 1 + self.scale)
  862. # s = 2 ** random.uniform(-scale, scale)
  863. R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)
  864. # Shear
  865. S = np.eye(3, dtype=np.float32)
  866. S[0, 1] = math.tan(random.uniform(-self.shear, self.shear) * math.pi / 180) # x shear (deg)
  867. S[1, 0] = math.tan(random.uniform(-self.shear, self.shear) * math.pi / 180) # y shear (deg)
  868. # Translation
  869. T = np.eye(3, dtype=np.float32)
  870. T[0, 2] = random.uniform(0.5 - self.translate, 0.5 + self.translate) * self.size[0] # x translation (pixels)
  871. T[1, 2] = random.uniform(0.5 - self.translate, 0.5 + self.translate) * self.size[1] # y translation (pixels)
  872. # Combined rotation matrix
  873. M = T @ S @ R @ P @ C # order of operations (right to left) is IMPORTANT
  874. # Affine image
  875. if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any(): # image changed
  876. if self.perspective:
  877. img = cv2.warpPerspective(img, M, dsize=self.size, borderValue=(114, 114, 114))
  878. else: # affine
  879. img = cv2.warpAffine(img, M[:2], dsize=self.size, borderValue=(114, 114, 114))
  880. return img, M, s
  881. def apply_bboxes(self, bboxes, M):
  882. """
  883. Apply affine transformation to bounding boxes.
  884. This function applies an affine transformation to a set of bounding boxes using the provided
  885. transformation matrix.
  886. Args:
  887. bboxes (torch.Tensor): Bounding boxes in xyxy format with shape (N, 4), where N is the number
  888. of bounding boxes.
  889. M (torch.Tensor): Affine transformation matrix with shape (3, 3).
  890. Returns:
  891. (torch.Tensor): Transformed bounding boxes in xyxy format with shape (N, 4).
  892. Examples:
  893. >>> bboxes = torch.tensor([[10, 10, 20, 20], [30, 30, 40, 40]])
  894. >>> M = torch.eye(3)
  895. >>> transformed_bboxes = apply_bboxes(bboxes, M)
  896. """
  897. n = len(bboxes)
  898. if n == 0:
  899. return bboxes
  900. xy = np.ones((n * 4, 3), dtype=bboxes.dtype)
  901. xy[:, :2] = bboxes[:, [0, 1, 2, 3, 0, 3, 2, 1]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1
  902. xy = xy @ M.T # transform
  903. xy = (xy[:, :2] / xy[:, 2:3] if self.perspective else xy[:, :2]).reshape(n, 8) # perspective rescale or affine
  904. # Create new boxes
  905. x = xy[:, [0, 2, 4, 6]]
  906. y = xy[:, [1, 3, 5, 7]]
  907. return np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1)), dtype=bboxes.dtype).reshape(4, n).T
  908. def apply_segments(self, segments, M):
  909. """
  910. Apply affine transformations to segments and generate new bounding boxes.
  911. This function applies affine transformations to input segments and generates new bounding boxes based on
  912. the transformed segments. It clips the transformed segments to fit within the new bounding boxes.
  913. Args:
  914. segments (np.ndarray): Input segments with shape (N, M, 2), where N is the number of segments and M is the
  915. number of points in each segment.
  916. M (np.ndarray): Affine transformation matrix with shape (3, 3).
  917. Returns:
  918. (Tuple[np.ndarray, np.ndarray]): A tuple containing:
  919. - New bounding boxes with shape (N, 4) in xyxy format.
  920. - Transformed and clipped segments with shape (N, M, 2).
  921. Examples:
  922. >>> segments = np.random.rand(10, 500, 2) # 10 segments with 500 points each
  923. >>> M = np.eye(3) # Identity transformation matrix
  924. >>> new_bboxes, new_segments = apply_segments(segments, M)
  925. """
  926. n, num = segments.shape[:2]
  927. if n == 0:
  928. return [], segments
  929. xy = np.ones((n * num, 3), dtype=segments.dtype)
  930. segments = segments.reshape(-1, 2)
  931. xy[:, :2] = segments
  932. xy = xy @ M.T # transform
  933. xy = xy[:, :2] / xy[:, 2:3]
  934. segments = xy.reshape(n, -1, 2)
  935. bboxes = np.stack([segment2box(xy, self.size[0], self.size[1]) for xy in segments], 0)
  936. segments[..., 0] = segments[..., 0].clip(bboxes[:, 0:1], bboxes[:, 2:3])
  937. segments[..., 1] = segments[..., 1].clip(bboxes[:, 1:2], bboxes[:, 3:4])
  938. return bboxes, segments
  939. def apply_keypoints(self, keypoints, M):
  940. """
  941. Applies affine transformation to keypoints.
  942. This method transforms the input keypoints using the provided affine transformation matrix. It handles
  943. perspective rescaling if necessary and updates the visibility of keypoints that fall outside the image
  944. boundaries after transformation.
  945. Args:
  946. keypoints (np.ndarray): Array of keypoints with shape (N, 17, 3), where N is the number of instances,
  947. 17 is the number of keypoints per instance, and 3 represents (x, y, visibility).
  948. M (np.ndarray): 3x3 affine transformation matrix.
  949. Returns:
  950. (np.ndarray): Transformed keypoints array with the same shape as input (N, 17, 3).
  951. Examples:
  952. >>> random_perspective = RandomPerspective()
  953. >>> keypoints = np.random.rand(5, 17, 3) # 5 instances, 17 keypoints each
  954. >>> M = np.eye(3) # Identity transformation
  955. >>> transformed_keypoints = random_perspective.apply_keypoints(keypoints, M)
  956. """
  957. n, nkpt = keypoints.shape[:2]
  958. if n == 0:
  959. return keypoints
  960. xy = np.ones((n * nkpt, 3), dtype=keypoints.dtype)
  961. visible = keypoints[..., 2].reshape(n * nkpt, 1)
  962. xy[:, :2] = keypoints[..., :2].reshape(n * nkpt, 2)
  963. xy = xy @ M.T # transform
  964. xy = xy[:, :2] / xy[:, 2:3] # perspective rescale or affine
  965. out_mask = (xy[:, 0] < 0) | (xy[:, 1] < 0) | (xy[:, 0] > self.size[0]) | (xy[:, 1] > self.size[1])
  966. visible[out_mask] = 0
  967. return np.concatenate([xy, visible], axis=-1).reshape(n, nkpt, 3)
  968. def __call__(self, labels):
  969. """
  970. Applies random perspective and affine transformations to an image and its associated labels.
  971. This method performs a series of transformations including rotation, translation, scaling, shearing,
  972. and perspective distortion on the input image and adjusts the corresponding bounding boxes, segments,
  973. and keypoints accordingly.
  974. Args:
  975. labels (Dict): A dictionary containing image data and annotations.
  976. Must include:
  977. 'img' (ndarray): The input image.
  978. 'cls' (ndarray): Class labels.
  979. 'instances' (Instances): Object instances with bounding boxes, segments, and keypoints.
  980. May include:
  981. 'mosaic_border' (Tuple[int, int]): Border size for mosaic augmentation.
  982. Returns:
  983. (Dict): Transformed labels dictionary containing:
  984. - 'img' (np.ndarray): The transformed image.
  985. - 'cls' (np.ndarray): Updated class labels.
  986. - 'instances' (Instances): Updated object instances.
  987. - 'resized_shape' (Tuple[int, int]): New image shape after transformation.
  988. Examples:
  989. >>> transform = RandomPerspective()
  990. >>> image = np.random.randint(0, 255, (640, 640, 3), dtype=np.uint8)
  991. >>> labels = {
  992. ... "img": image,
  993. ... "cls": np.array([0, 1, 2]),
  994. ... "instances": Instances(bboxes=np.array([[10, 10, 50, 50], [100, 100, 150, 150]])),
  995. ... }
  996. >>> result = transform(labels)
  997. >>> assert result["img"].shape[:2] == result["resized_shape"]
  998. """
  999. if self.pre_transform and "mosaic_border" not in labels:
  1000. labels = self.pre_transform(labels)
  1001. labels.pop("ratio_pad", None) # do not need ratio pad
  1002. img = labels["img"]
  1003. cls = labels["cls"]
  1004. instances = labels.pop("instances")
  1005. # Make sure the coord formats are right
  1006. instances.convert_bbox(format="xyxy")
  1007. instances.denormalize(*img.shape[:2][::-1])
  1008. border = labels.pop("mosaic_border", self.border)
  1009. self.size = img.shape[1] + border[1] * 2, img.shape[0] + border[0] * 2 # w, h
  1010. # M is affine matrix
  1011. # Scale for func:`box_candidates`
  1012. img, M, scale = self.affine_transform(img, border)
  1013. bboxes = self.apply_bboxes(instances.bboxes, M)
  1014. segments = instances.segments
  1015. keypoints = instances.keypoints
  1016. # Update bboxes if there are segments.
  1017. if len(segments):
  1018. bboxes, segments = self.apply_segments(segments, M)
  1019. if keypoints is not None:
  1020. keypoints = self.apply_keypoints(keypoints, M)
  1021. new_instances = Instances(bboxes, segments, keypoints, bbox_format="xyxy", normalized=False)
  1022. # Clip
  1023. new_instances.clip(*self.size)
  1024. # Filter instances
  1025. instances.scale(scale_w=scale, scale_h=scale, bbox_only=True)
  1026. # Make the bboxes have the same scale with new_bboxes
  1027. i = self.box_candidates(
  1028. box1=instances.bboxes.T, box2=new_instances.bboxes.T, area_thr=0.01 if len(segments) else 0.10
  1029. )
  1030. labels["instances"] = new_instances[i]
  1031. labels["cls"] = cls[i]
  1032. labels["img"] = img
  1033. labels["resized_shape"] = img.shape[:2]
  1034. return labels
  1035. @staticmethod
  1036. def box_candidates(box1, box2, wh_thr=2, ar_thr=100, area_thr=0.1, eps=1e-16):
  1037. """
  1038. Compute candidate boxes for further processing based on size and aspect ratio criteria.
  1039. This method compares boxes before and after augmentation to determine if they meet specified
  1040. thresholds for width, height, aspect ratio, and area. It's used to filter out boxes that have
  1041. been overly distorted or reduced by the augmentation process.
  1042. Args:
  1043. box1 (numpy.ndarray): Original boxes before augmentation, shape (4, N) where n is the
  1044. number of boxes. Format is [x1, y1, x2, y2] in absolute coordinates.
  1045. box2 (numpy.ndarray): Augmented boxes after transformation, shape (4, N). Format is
  1046. [x1, y1, x2, y2] in absolute coordinates.
  1047. wh_thr (float): Width and height threshold in pixels. Boxes smaller than this in either
  1048. dimension are rejected.
  1049. ar_thr (float): Aspect ratio threshold. Boxes with an aspect ratio greater than this
  1050. value are rejected.
  1051. area_thr (float): Area ratio threshold. Boxes with an area ratio (new/old) less than
  1052. this value are rejected.
  1053. eps (float): Small epsilon value to prevent division by zero.
  1054. Returns:
  1055. (numpy.ndarray): Boolean array of shape (n) indicating which boxes are candidates.
  1056. True values correspond to boxes that meet all criteria.
  1057. Examples:
  1058. >>> random_perspective = RandomPerspective()
  1059. >>> box1 = np.array([[0, 0, 100, 100], [0, 0, 50, 50]]).T
  1060. >>> box2 = np.array([[10, 10, 90, 90], [5, 5, 45, 45]]).T
  1061. >>> candidates = random_perspective.box_candidates(box1, box2)
  1062. >>> print(candidates)
  1063. [True True]
  1064. """
  1065. w1, h1 = box1[2] - box1[0], box1[3] - box1[1]
  1066. w2, h2 = box2[2] - box2[0], box2[3] - box2[1]
  1067. ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps)) # aspect ratio
  1068. return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr) # candidates
  1069. class RandomHSV:
  1070. """
  1071. Randomly adjusts the Hue, Saturation, and Value (HSV) channels of an image.
  1072. This class applies random HSV augmentation to images within predefined limits set by hgain, sgain, and vgain.
  1073. Attributes:
  1074. hgain (float): Maximum variation for hue. Range is typically [0, 1].
  1075. sgain (float): Maximum variation for saturation. Range is typically [0, 1].
  1076. vgain (float): Maximum variation for value. Range is typically [0, 1].
  1077. Methods:
  1078. __call__: Applies random HSV augmentation to an image.
  1079. Examples:
  1080. >>> import numpy as np
  1081. >>> from ultralytics.data.augment import RandomHSV
  1082. >>> augmenter = RandomHSV(hgain=0.5, sgain=0.5, vgain=0.5)
  1083. >>> image = np.random.randint(0, 255, (100, 100, 3), dtype=np.uint8)
  1084. >>> labels = {"img": image}
  1085. >>> augmenter(labels)
  1086. >>> augmented_image = augmented_labels["img"]
  1087. """
  1088. def __init__(self, hgain=0.5, sgain=0.5, vgain=0.5) -> None:
  1089. """
  1090. Initializes the RandomHSV object for random HSV (Hue, Saturation, Value) augmentation.
  1091. This class applies random adjustments to the HSV channels of an image within specified limits.
  1092. Args:
  1093. hgain (float): Maximum variation for hue. Should be in the range [0, 1].
  1094. sgain (float): Maximum variation for saturation. Should be in the range [0, 1].
  1095. vgain (float): Maximum variation for value. Should be in the range [0, 1].
  1096. Examples:
  1097. >>> hsv_aug = RandomHSV(hgain=0.5, sgain=0.5, vgain=0.5)
  1098. >>> hsv_aug(image)
  1099. """
  1100. self.hgain = hgain
  1101. self.sgain = sgain
  1102. self.vgain = vgain
  1103. def __call__(self, labels):
  1104. """
  1105. Applies random HSV augmentation to an image within predefined limits.
  1106. This method modifies the input image by randomly adjusting its Hue, Saturation, and Value (HSV) channels.
  1107. The adjustments are made within the limits set by hgain, sgain, and vgain during initialization.
  1108. Args:
  1109. labels (Dict): A dictionary containing image data and metadata. Must include an 'img' key with
  1110. the image as a numpy array.
  1111. Returns:
  1112. (None): The function modifies the input 'labels' dictionary in-place, updating the 'img' key
  1113. with the HSV-augmented image.
  1114. Examples:
  1115. >>> hsv_augmenter = RandomHSV(hgain=0.5, sgain=0.5, vgain=0.5)
  1116. >>> labels = {"img": np.random.randint(0, 255, (100, 100, 3), dtype=np.uint8)}
  1117. >>> hsv_augmenter(labels)
  1118. >>> augmented_img = labels["img"]
  1119. """
  1120. img = labels["img"]
  1121. if self.hgain or self.sgain or self.vgain:
  1122. r = np.random.uniform(-1, 1, 3) * [self.hgain, self.sgain, self.vgain] + 1 # random gains
  1123. hue, sat, val = cv2.split(cv2.cvtColor(img, cv2.COLOR_BGR2HSV))
  1124. dtype = img.dtype # uint8
  1125. x = np.arange(0, 256, dtype=r.dtype)
  1126. lut_hue = ((x * r[0]) % 180).astype(dtype)
  1127. lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)
  1128. lut_val = np.clip(x * r[2], 0, 255).astype(dtype)
  1129. im_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val)))
  1130. cv2.cvtColor(im_hsv, cv2.COLOR_HSV2BGR, dst=img) # no return needed
  1131. return labels
  1132. class RandomFlip:
  1133. """
  1134. Applies a random horizontal or vertical flip to an image with a given probability.
  1135. This class performs random image flipping and updates corresponding instance annotations such as
  1136. bounding boxes and keypoints.
  1137. Attributes:
  1138. p (float): Probability of applying the flip. Must be between 0 and 1.
  1139. direction (str): Direction of flip, either 'horizontal' or 'vertical'.
  1140. flip_idx (array-like): Index mapping for flipping keypoints, if applicable.
  1141. Methods:
  1142. __call__: Applies the random flip transformation to an image and its annotations.
  1143. Examples:
  1144. >>> transform = RandomFlip(p=0.5, direction="horizontal")
  1145. >>> result = transform({"img": image, "instances": instances})
  1146. >>> flipped_image = result["img"]
  1147. >>> flipped_instances = result["instances"]
  1148. """
  1149. def __init__(self, p=0.5, direction="horizontal", flip_idx=None) -> None:
  1150. """
  1151. Initializes the RandomFlip class with probability and direction.
  1152. This class applies a random horizontal or vertical flip to an image with a given probability.
  1153. It also updates any instances (bounding boxes, keypoints, etc.) accordingly.
  1154. Args:
  1155. p (float): The probability of applying the flip. Must be between 0 and 1.
  1156. direction (str): The direction to apply the flip. Must be 'horizontal' or 'vertical'.
  1157. flip_idx (List[int] | None): Index mapping for flipping keypoints, if any.
  1158. Raises:
  1159. AssertionError: If direction is not 'horizontal' or 'vertical', or if p is not between 0 and 1.
  1160. Examples:
  1161. >>> flip = RandomFlip(p=0.5, direction="horizontal")
  1162. >>> flip_with_idx = RandomFlip(p=0.7, direction="vertical", flip_idx=[1, 0, 3, 2, 5, 4])
  1163. """
  1164. assert direction in {"horizontal", "vertical"}, f"Support direction `horizontal` or `vertical`, got {direction}"
  1165. assert 0 <= p <= 1.0, f"The probability should be in range [0, 1], but got {p}."
  1166. self.p = p
  1167. self.direction = direction
  1168. self.flip_idx = flip_idx
  1169. def __call__(self, labels):
  1170. """
  1171. Applies random flip to an image and updates any instances like bounding boxes or keypoints accordingly.
  1172. This method randomly flips the input image either horizontally or vertically based on the initialized
  1173. probability and direction. It also updates the corresponding instances (bounding boxes, keypoints) to
  1174. match the flipped image.
  1175. Args:
  1176. labels (Dict): A dictionary containing the following keys:
  1177. 'img' (numpy.ndarray): The image to be flipped.
  1178. 'instances' (ultralytics.utils.instance.Instances): An object containing bounding boxes and
  1179. optionally keypoints.
  1180. Returns:
  1181. (Dict): The same dictionary with the flipped image and updated instances:
  1182. 'img' (numpy.ndarray): The flipped image.
  1183. 'instances' (ultralytics.utils.instance.Instances): Updated instances matching the flipped image.
  1184. Examples:
  1185. >>> labels = {"img": np.random.rand(640, 640, 3), "instances": Instances(...)}
  1186. >>> random_flip = RandomFlip(p=0.5, direction="horizontal")
  1187. >>> flipped_labels = random_flip(labels)
  1188. """
  1189. img = labels["img"]
  1190. instances = labels.pop("instances")
  1191. instances.convert_bbox(format="xywh")
  1192. h, w = img.shape[:2]
  1193. h = 1 if instances.normalized else h
  1194. w = 1 if instances.normalized else w
  1195. # Flip up-down
  1196. if self.direction == "vertical" and random.random() < self.p:
  1197. img = np.flipud(img)
  1198. instances.flipud(h)
  1199. if self.direction == "horizontal" and random.random() < self.p:
  1200. img = np.fliplr(img)
  1201. instances.fliplr(w)
  1202. # For keypoints
  1203. if self.flip_idx is not None and instances.keypoints is not None:
  1204. instances.keypoints = np.ascontiguousarray(instances.keypoints[:, self.flip_idx, :])
  1205. labels["img"] = np.ascontiguousarray(img)
  1206. labels["instances"] = instances
  1207. return labels
  1208. class LetterBox:
  1209. """
  1210. Resize image and padding for detection, instance segmentation, pose.
  1211. This class resizes and pads images to a specified shape while preserving aspect ratio. It also updates
  1212. corresponding labels and bounding boxes.
  1213. Attributes:
  1214. new_shape (tuple): Target shape (height, width) for resizing.
  1215. auto (bool): Whether to use minimum rectangle.
  1216. scaleFill (bool): Whether to stretch the image to new_shape.
  1217. scaleup (bool): Whether to allow scaling up. If False, only scale down.
  1218. stride (int): Stride for rounding padding.
  1219. center (bool): Whether to center the image or align to top-left.
  1220. Methods:
  1221. __call__: Resize and pad image, update labels and bounding boxes.
  1222. Examples:
  1223. >>> transform = LetterBox(new_shape=(640, 640))
  1224. >>> result = transform(labels)
  1225. >>> resized_img = result["img"]
  1226. >>> updated_instances = result["instances"]
  1227. """
  1228. def __init__(self, new_shape=(640, 640), auto=False, scaleFill=False, scaleup=True, center=True, stride=32):
  1229. """
  1230. Initialize LetterBox object for resizing and padding images.
  1231. This class is designed to resize and pad images for object detection, instance segmentation, and pose estimation
  1232. tasks. It supports various resizing modes including auto-sizing, scale-fill, and letterboxing.
  1233. Args:
  1234. new_shape (Tuple[int, int]): Target size (height, width) for the resized image.
  1235. auto (bool): If True, use minimum rectangle to resize. If False, use new_shape directly.
  1236. scaleFill (bool): If True, stretch the image to new_shape without padding.
  1237. scaleup (bool): If True, allow scaling up. If False, only scale down.
  1238. center (bool): If True, center the placed image. If False, place image in top-left corner.
  1239. stride (int): Stride of the model (e.g., 32 for YOLOv5).
  1240. Attributes:
  1241. new_shape (Tuple[int, int]): Target size for the resized image.
  1242. auto (bool): Flag for using minimum rectangle resizing.
  1243. scaleFill (bool): Flag for stretching image without padding.
  1244. scaleup (bool): Flag for allowing upscaling.
  1245. stride (int): Stride value for ensuring image size is divisible by stride.
  1246. Examples:
  1247. >>> letterbox = LetterBox(new_shape=(640, 640), auto=False, scaleFill=False, scaleup=True, stride=32)
  1248. >>> resized_img = letterbox(original_img)
  1249. """
  1250. self.new_shape = new_shape
  1251. self.auto = auto
  1252. self.scaleFill = scaleFill
  1253. self.scaleup = scaleup
  1254. self.stride = stride
  1255. self.center = center # Put the image in the middle or top-left
  1256. def __call__(self, labels=None, image=None):
  1257. """
  1258. Resizes and pads an image for object detection, instance segmentation, or pose estimation tasks.
  1259. This method applies letterboxing to the input image, which involves resizing the image while maintaining its
  1260. aspect ratio and adding padding to fit the new shape. It also updates any associated labels accordingly.
  1261. Args:
  1262. labels (Dict | None): A dictionary containing image data and associated labels, or empty dict if None.
  1263. image (np.ndarray | None): The input image as a numpy array. If None, the image is taken from 'labels'.
  1264. Returns:
  1265. (Dict | Tuple): If 'labels' is provided, returns an updated dictionary with the resized and padded image,
  1266. updated labels, and additional metadata. If 'labels' is empty, returns a tuple containing the resized
  1267. and padded image, and a tuple of (ratio, (left_pad, top_pad)).
  1268. Examples:
  1269. >>> letterbox = LetterBox(new_shape=(640, 640))
  1270. >>> result = letterbox(labels={"img": np.zeros((480, 640, 3)), "instances": Instances(...)})
  1271. >>> resized_img = result["img"]
  1272. >>> updated_instances = result["instances"]
  1273. """
  1274. if labels is None:
  1275. labels = {}
  1276. img = labels.get("img") if image is None else image
  1277. shape = img.shape[:2] # current shape [height, width]
  1278. new_shape = labels.pop("rect_shape", self.new_shape)
  1279. if isinstance(new_shape, int):
  1280. new_shape = (new_shape, new_shape)
  1281. # Scale ratio (new / old)
  1282. r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
  1283. if not self.scaleup: # only scale down, do not scale up (for better val mAP)
  1284. r = min(r, 1.0)
  1285. # Compute padding
  1286. ratio = r, r # width, height ratios
  1287. new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
  1288. dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding
  1289. if self.auto: # minimum rectangle
  1290. dw, dh = np.mod(dw, self.stride), np.mod(dh, self.stride) # wh padding
  1291. elif self.scaleFill: # stretch
  1292. dw, dh = 0.0, 0.0
  1293. new_unpad = (new_shape[1], new_shape[0])
  1294. ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios
  1295. if self.center:
  1296. dw /= 2 # divide padding into 2 sides
  1297. dh /= 2
  1298. if shape[::-1] != new_unpad: # resize
  1299. img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR)
  1300. top, bottom = int(round(dh - 0.1)) if self.center else 0, int(round(dh + 0.1))
  1301. left, right = int(round(dw - 0.1)) if self.center else 0, int(round(dw + 0.1))
  1302. img = cv2.copyMakeBorder(
  1303. img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=(114, 114, 114)
  1304. ) # add border
  1305. if labels.get("ratio_pad"):
  1306. labels["ratio_pad"] = (labels["ratio_pad"], (left, top)) # for evaluation
  1307. if len(labels):
  1308. labels = self._update_labels(labels, ratio, left, top)
  1309. labels["img"] = img
  1310. labels["resized_shape"] = new_shape
  1311. return labels
  1312. else:
  1313. return img
  1314. @staticmethod
  1315. def _update_labels(labels, ratio, padw, padh):
  1316. """
  1317. Updates labels after applying letterboxing to an image.
  1318. This method modifies the bounding box coordinates of instances in the labels
  1319. to account for resizing and padding applied during letterboxing.
  1320. Args:
  1321. labels (Dict): A dictionary containing image labels and instances.
  1322. ratio (Tuple[float, float]): Scaling ratios (width, height) applied to the image.
  1323. padw (float): Padding width added to the image.
  1324. padh (float): Padding height added to the image.
  1325. Returns:
  1326. (Dict): Updated labels dictionary with modified instance coordinates.
  1327. Examples:
  1328. >>> letterbox = LetterBox(new_shape=(640, 640))
  1329. >>> labels = {"instances": Instances(...)}
  1330. >>> ratio = (0.5, 0.5)
  1331. >>> padw, padh = 10, 20
  1332. >>> updated_labels = letterbox._update_labels(labels, ratio, padw, padh)
  1333. """
  1334. labels["instances"].convert_bbox(format="xyxy")
  1335. labels["instances"].denormalize(*labels["img"].shape[:2][::-1])
  1336. labels["instances"].scale(*ratio)
  1337. labels["instances"].add_padding(padw, padh)
  1338. return labels
  1339. class CopyPaste(BaseMixTransform):
  1340. """
  1341. CopyPaste class for applying Copy-Paste augmentation to image datasets.
  1342. This class implements the Copy-Paste augmentation technique as described in the paper "Simple Copy-Paste is a Strong
  1343. Data Augmentation Method for Instance Segmentation" (https://arxiv.org/abs/2012.07177). It combines objects from
  1344. different images to create new training samples.
  1345. Attributes:
  1346. dataset (Any): The dataset to which Copy-Paste augmentation will be applied.
  1347. pre_transform (Callable | None): Optional transform to apply before Copy-Paste.
  1348. p (float): Probability of applying Copy-Paste augmentation.
  1349. Methods:
  1350. get_indexes: Returns a random index from the dataset.
  1351. _mix_transform: Applies Copy-Paste augmentation to the input labels.
  1352. __call__: Applies the Copy-Paste transformation to images and annotations.
  1353. Examples:
  1354. >>> from ultralytics.data.augment import CopyPaste
  1355. >>> dataset = YourDataset(...) # Your image dataset
  1356. >>> copypaste = CopyPaste(dataset, p=0.5)
  1357. >>> augmented_labels = copypaste(original_labels)
  1358. """
  1359. def __init__(self, dataset=None, pre_transform=None, p=0.5, mode="flip") -> None:
  1360. """Initializes CopyPaste object with dataset, pre_transform, and probability of applying MixUp."""
  1361. super().__init__(dataset=dataset, pre_transform=pre_transform, p=p)
  1362. assert mode in {"flip", "mixup"}, f"Expected `mode` to be `flip` or `mixup`, but got {mode}."
  1363. self.mode = mode
  1364. def get_indexes(self):
  1365. """Returns a list of random indexes from the dataset for CopyPaste augmentation."""
  1366. return random.randint(0, len(self.dataset) - 1)
  1367. def _mix_transform(self, labels):
  1368. """Applies Copy-Paste augmentation to combine objects from another image into the current image."""
  1369. labels2 = labels["mix_labels"][0]
  1370. return self._transform(labels, labels2)
  1371. def __call__(self, labels):
  1372. """Applies Copy-Paste augmentation to an image and its labels."""
  1373. if len(labels["instances"].segments) == 0 or self.p == 0:
  1374. return labels
  1375. if self.mode == "flip":
  1376. return self._transform(labels)
  1377. # Get index of one or three other images
  1378. indexes = self.get_indexes()
  1379. if isinstance(indexes, int):
  1380. indexes = [indexes]
  1381. # Get images information will be used for Mosaic or MixUp
  1382. mix_labels = [self.dataset.get_image_and_label(i) for i in indexes]
  1383. if self.pre_transform is not None:
  1384. for i, data in enumerate(mix_labels):
  1385. mix_labels[i] = self.pre_transform(data)
  1386. labels["mix_labels"] = mix_labels
  1387. # Update cls and texts
  1388. labels = self._update_label_text(labels)
  1389. # Mosaic or MixUp
  1390. labels = self._mix_transform(labels)
  1391. labels.pop("mix_labels", None)
  1392. return labels
  1393. def _transform(self, labels1, labels2={}):
  1394. """Applies Copy-Paste augmentation to combine objects from another image into the current image."""
  1395. im = labels1["img"]
  1396. cls = labels1["cls"]
  1397. h, w = im.shape[:2]
  1398. instances = labels1.pop("instances")
  1399. instances.convert_bbox(format="xyxy")
  1400. instances.denormalize(w, h)
  1401. im_new = np.zeros(im.shape, np.uint8)
  1402. instances2 = labels2.pop("instances", None)
  1403. if instances2 is None:
  1404. instances2 = deepcopy(instances)
  1405. instances2.fliplr(w)
  1406. ioa = bbox_ioa(instances2.bboxes, instances.bboxes) # intersection over area, (N, M)
  1407. indexes = np.nonzero((ioa < 0.30).all(1))[0] # (N, )
  1408. n = len(indexes)
  1409. sorted_idx = np.argsort(ioa.max(1)[indexes])
  1410. indexes = indexes[sorted_idx]
  1411. for j in indexes[: round(self.p * n)]:
  1412. cls = np.concatenate((cls, labels2.get("cls", cls)[[j]]), axis=0)
  1413. instances = Instances.concatenate((instances, instances2[[j]]), axis=0)
  1414. cv2.drawContours(im_new, instances2.segments[[j]].astype(np.int32), -1, (1, 1, 1), cv2.FILLED)
  1415. result = labels2.get("img", cv2.flip(im, 1)) # augment segments
  1416. i = im_new.astype(bool)
  1417. im[i] = result[i]
  1418. labels1["img"] = im
  1419. labels1["cls"] = cls
  1420. labels1["instances"] = instances
  1421. return labels1
  1422. class Albumentations:
  1423. """
  1424. Albumentations transformations for image augmentation.
  1425. This class applies various image transformations using the Albumentations library. It includes operations such as
  1426. Blur, Median Blur, conversion to grayscale, Contrast Limited Adaptive Histogram Equalization (CLAHE), random changes
  1427. in brightness and contrast, RandomGamma, and image quality reduction through compression.
  1428. Attributes:
  1429. p (float): Probability of applying the transformations.
  1430. transform (albumentations.Compose): Composed Albumentations transforms.
  1431. contains_spatial (bool): Indicates if the transforms include spatial operations.
  1432. Methods:
  1433. __call__: Applies the Albumentations transformations to the input labels.
  1434. Examples:
  1435. >>> transform = Albumentations(p=0.5)
  1436. >>> augmented_labels = transform(labels)
  1437. Notes:
  1438. - The Albumentations package must be installed to use this class.
  1439. - If the package is not installed or an error occurs during initialization, the transform will be set to None.
  1440. - Spatial transforms are handled differently and require special processing for bounding boxes.
  1441. """
  1442. def __init__(self, p=1.0):
  1443. """
  1444. Initialize the Albumentations transform object for YOLO bbox formatted parameters.
  1445. This class applies various image augmentations using the Albumentations library, including Blur, Median Blur,
  1446. conversion to grayscale, Contrast Limited Adaptive Histogram Equalization, random changes of brightness and
  1447. contrast, RandomGamma, and image quality reduction through compression.
  1448. Args:
  1449. p (float): Probability of applying the augmentations. Must be between 0 and 1.
  1450. Attributes:
  1451. p (float): Probability of applying the augmentations.
  1452. transform (albumentations.Compose): Composed Albumentations transforms.
  1453. contains_spatial (bool): Indicates if the transforms include spatial transformations.
  1454. Raises:
  1455. ImportError: If the Albumentations package is not installed.
  1456. Exception: For any other errors during initialization.
  1457. Examples:
  1458. >>> transform = Albumentations(p=0.5)
  1459. >>> augmented = transform(image=image, bboxes=bboxes, class_labels=classes)
  1460. >>> augmented_image = augmented["image"]
  1461. >>> augmented_bboxes = augmented["bboxes"]
  1462. Notes:
  1463. - Requires Albumentations version 1.0.3 or higher.
  1464. - Spatial transforms are handled differently to ensure bbox compatibility.
  1465. - Some transforms are applied with very low probability (0.01) by default.
  1466. """
  1467. self.p = p
  1468. self.transform = None
  1469. prefix = colorstr("albumentations: ")
  1470. try:
  1471. import albumentations as A
  1472. check_version(A.__version__, "1.0.3", hard=True) # version requirement
  1473. # List of possible spatial transforms
  1474. spatial_transforms = {
  1475. "Affine",
  1476. "BBoxSafeRandomCrop",
  1477. "CenterCrop",
  1478. "CoarseDropout",
  1479. "Crop",
  1480. "CropAndPad",
  1481. "CropNonEmptyMaskIfExists",
  1482. "D4",
  1483. "ElasticTransform",
  1484. "Flip",
  1485. "GridDistortion",
  1486. "GridDropout",
  1487. "HorizontalFlip",
  1488. "Lambda",
  1489. "LongestMaxSize",
  1490. "MaskDropout",
  1491. "MixUp",
  1492. "Morphological",
  1493. "NoOp",
  1494. "OpticalDistortion",
  1495. "PadIfNeeded",
  1496. "Perspective",
  1497. "PiecewiseAffine",
  1498. "PixelDropout",
  1499. "RandomCrop",
  1500. "RandomCropFromBorders",
  1501. "RandomGridShuffle",
  1502. "RandomResizedCrop",
  1503. "RandomRotate90",
  1504. "RandomScale",
  1505. "RandomSizedBBoxSafeCrop",
  1506. "RandomSizedCrop",
  1507. "Resize",
  1508. "Rotate",
  1509. "SafeRotate",
  1510. "ShiftScaleRotate",
  1511. "SmallestMaxSize",
  1512. "Transpose",
  1513. "VerticalFlip",
  1514. "XYMasking",
  1515. } # from https://albumentations.ai/docs/getting_started/transforms_and_targets/#spatial-level-transforms
  1516. # Transforms
  1517. T = [
  1518. A.Blur(p=0.01),
  1519. A.MedianBlur(p=0.01),
  1520. A.ToGray(p=0.01),
  1521. A.CLAHE(p=0.01),
  1522. A.RandomBrightnessContrast(p=0.0),
  1523. A.RandomGamma(p=0.0),
  1524. A.ImageCompression(quality_range=(75, 100), p=0.5),
  1525. ]
  1526. # Compose transforms
  1527. self.contains_spatial = any(transform.__class__.__name__ in spatial_transforms for transform in T)
  1528. self.transform = (
  1529. A.Compose(T, bbox_params=A.BboxParams(format="yolo", label_fields=["class_labels"]))
  1530. if self.contains_spatial
  1531. else A.Compose(T)
  1532. )
  1533. if hasattr(self.transform, "set_random_seed"):
  1534. # Required for deterministic transforms in albumentations>=1.4.21
  1535. self.transform.set_random_seed(torch.initial_seed())
  1536. LOGGER.info(prefix + ", ".join(f"{x}".replace("always_apply=False, ", "") for x in T if x.p))
  1537. except ImportError: # package not installed, skip
  1538. pass
  1539. except Exception as e:
  1540. LOGGER.info(f"{prefix}{e}")
  1541. def __call__(self, labels):
  1542. """
  1543. Applies Albumentations transformations to input labels.
  1544. This method applies a series of image augmentations using the Albumentations library. It can perform both
  1545. spatial and non-spatial transformations on the input image and its corresponding labels.
  1546. Args:
  1547. labels (Dict): A dictionary containing image data and annotations. Expected keys are:
  1548. - 'img': numpy.ndarray representing the image
  1549. - 'cls': numpy.ndarray of class labels
  1550. - 'instances': object containing bounding boxes and other instance information
  1551. Returns:
  1552. (Dict): The input dictionary with augmented image and updated annotations.
  1553. Examples:
  1554. >>> transform = Albumentations(p=0.5)
  1555. >>> labels = {
  1556. ... "img": np.random.rand(640, 640, 3),
  1557. ... "cls": np.array([0, 1]),
  1558. ... "instances": Instances(bboxes=np.array([[0, 0, 1, 1], [0.5, 0.5, 0.8, 0.8]])),
  1559. ... }
  1560. >>> augmented = transform(labels)
  1561. >>> assert augmented["img"].shape == (640, 640, 3)
  1562. Notes:
  1563. - The method applies transformations with probability self.p.
  1564. - Spatial transforms update bounding boxes, while non-spatial transforms only modify the image.
  1565. - Requires the Albumentations library to be installed.
  1566. """
  1567. if self.transform is None or random.random() > self.p:
  1568. return labels
  1569. if self.contains_spatial:
  1570. cls = labels["cls"]
  1571. if len(cls):
  1572. im = labels["img"]
  1573. labels["instances"].convert_bbox("xywh")
  1574. labels["instances"].normalize(*im.shape[:2][::-1])
  1575. bboxes = labels["instances"].bboxes
  1576. # TODO: add supports of segments and keypoints
  1577. new = self.transform(image=im, bboxes=bboxes, class_labels=cls) # transformed
  1578. if len(new["class_labels"]) > 0: # skip update if no bbox in new im
  1579. labels["img"] = new["image"]
  1580. labels["cls"] = np.array(new["class_labels"])
  1581. bboxes = np.array(new["bboxes"], dtype=np.float32)
  1582. labels["instances"].update(bboxes=bboxes)
  1583. else:
  1584. labels["img"] = self.transform(image=labels["img"])["image"] # transformed
  1585. return labels
  1586. class Format:
  1587. """
  1588. A class for formatting image annotations for object detection, instance segmentation, and pose estimation tasks.
  1589. This class standardizes image and instance annotations to be used by the `collate_fn` in PyTorch DataLoader.
  1590. Attributes:
  1591. bbox_format (str): Format for bounding boxes. Options are 'xywh' or 'xyxy'.
  1592. normalize (bool): Whether to normalize bounding boxes.
  1593. return_mask (bool): Whether to return instance masks for segmentation.
  1594. return_keypoint (bool): Whether to return keypoints for pose estimation.
  1595. return_obb (bool): Whether to return oriented bounding boxes.
  1596. mask_ratio (int): Downsample ratio for masks.
  1597. mask_overlap (bool): Whether to overlap masks.
  1598. batch_idx (bool): Whether to keep batch indexes.
  1599. bgr (float): The probability to return BGR images.
  1600. Methods:
  1601. __call__: Formats labels dictionary with image, classes, bounding boxes, and optionally masks and keypoints.
  1602. _format_img: Converts image from Numpy array to PyTorch tensor.
  1603. _format_segments: Converts polygon points to bitmap masks.
  1604. Examples:
  1605. >>> formatter = Format(bbox_format="xywh", normalize=True, return_mask=True)
  1606. >>> formatted_labels = formatter(labels)
  1607. >>> img = formatted_labels["img"]
  1608. >>> bboxes = formatted_labels["bboxes"]
  1609. >>> masks = formatted_labels["masks"]
  1610. """
  1611. def __init__(
  1612. self,
  1613. bbox_format="xywh",
  1614. normalize=True,
  1615. return_mask=False,
  1616. return_keypoint=False,
  1617. return_obb=False,
  1618. mask_ratio=4,
  1619. mask_overlap=True,
  1620. batch_idx=True,
  1621. bgr=0.0,
  1622. ):
  1623. """
  1624. Initializes the Format class with given parameters for image and instance annotation formatting.
  1625. This class standardizes image and instance annotations for object detection, instance segmentation, and pose
  1626. estimation tasks, preparing them for use in PyTorch DataLoader's `collate_fn`.
  1627. Args:
  1628. bbox_format (str): Format for bounding boxes. Options are 'xywh', 'xyxy', etc.
  1629. normalize (bool): Whether to normalize bounding boxes to [0,1].
  1630. return_mask (bool): If True, returns instance masks for segmentation tasks.
  1631. return_keypoint (bool): If True, returns keypoints for pose estimation tasks.
  1632. return_obb (bool): If True, returns oriented bounding boxes.
  1633. mask_ratio (int): Downsample ratio for masks.
  1634. mask_overlap (bool): If True, allows mask overlap.
  1635. batch_idx (bool): If True, keeps batch indexes.
  1636. bgr (float): Probability of returning BGR images instead of RGB.
  1637. Attributes:
  1638. bbox_format (str): Format for bounding boxes.
  1639. normalize (bool): Whether bounding boxes are normalized.
  1640. return_mask (bool): Whether to return instance masks.
  1641. return_keypoint (bool): Whether to return keypoints.
  1642. return_obb (bool): Whether to return oriented bounding boxes.
  1643. mask_ratio (int): Downsample ratio for masks.
  1644. mask_overlap (bool): Whether masks can overlap.
  1645. batch_idx (bool): Whether to keep batch indexes.
  1646. bgr (float): The probability to return BGR images.
  1647. Examples:
  1648. >>> format = Format(bbox_format="xyxy", return_mask=True, return_keypoint=False)
  1649. >>> print(format.bbox_format)
  1650. xyxy
  1651. """
  1652. self.bbox_format = bbox_format
  1653. self.normalize = normalize
  1654. self.return_mask = return_mask # set False when training detection only
  1655. self.return_keypoint = return_keypoint
  1656. self.return_obb = return_obb
  1657. self.mask_ratio = mask_ratio
  1658. self.mask_overlap = mask_overlap
  1659. self.batch_idx = batch_idx # keep the batch indexes
  1660. self.bgr = bgr
  1661. def __call__(self, labels):
  1662. """
  1663. Formats image annotations for object detection, instance segmentation, and pose estimation tasks.
  1664. This method standardizes the image and instance annotations to be used by the `collate_fn` in PyTorch
  1665. DataLoader. It processes the input labels dictionary, converting annotations to the specified format and
  1666. applying normalization if required.
  1667. Args:
  1668. labels (Dict): A dictionary containing image and annotation data with the following keys:
  1669. - 'img': The input image as a numpy array.
  1670. - 'cls': Class labels for instances.
  1671. - 'instances': An Instances object containing bounding boxes, segments, and keypoints.
  1672. Returns:
  1673. (Dict): A dictionary with formatted data, including:
  1674. - 'img': Formatted image tensor.
  1675. - 'cls': Class label's tensor.
  1676. - 'bboxes': Bounding boxes tensor in the specified format.
  1677. - 'masks': Instance masks tensor (if return_mask is True).
  1678. - 'keypoints': Keypoints tensor (if return_keypoint is True).
  1679. - 'batch_idx': Batch index tensor (if batch_idx is True).
  1680. Examples:
  1681. >>> formatter = Format(bbox_format="xywh", normalize=True, return_mask=True)
  1682. >>> labels = {"img": np.random.rand(640, 640, 3), "cls": np.array([0, 1]), "instances": Instances(...)}
  1683. >>> formatted_labels = formatter(labels)
  1684. >>> print(formatted_labels.keys())
  1685. """
  1686. img = labels.pop("img")
  1687. h, w = img.shape[:2]
  1688. cls = labels.pop("cls")
  1689. instances = labels.pop("instances")
  1690. instances.convert_bbox(format=self.bbox_format)
  1691. instances.denormalize(w, h)
  1692. nl = len(instances)
  1693. if self.return_mask:
  1694. if nl:
  1695. masks, instances, cls = self._format_segments(instances, cls, w, h)
  1696. masks = torch.from_numpy(masks)
  1697. else:
  1698. masks = torch.zeros(
  1699. 1 if self.mask_overlap else nl, img.shape[0] // self.mask_ratio, img.shape[1] // self.mask_ratio
  1700. )
  1701. labels["masks"] = masks
  1702. labels["img"] = self._format_img(img)
  1703. labels["cls"] = torch.from_numpy(cls) if nl else torch.zeros(nl)
  1704. labels["bboxes"] = torch.from_numpy(instances.bboxes) if nl else torch.zeros((nl, 4))
  1705. if self.return_keypoint:
  1706. labels["keypoints"] = torch.from_numpy(instances.keypoints)
  1707. if self.normalize:
  1708. labels["keypoints"][..., 0] /= w
  1709. labels["keypoints"][..., 1] /= h
  1710. if self.return_obb:
  1711. labels["bboxes"] = (
  1712. xyxyxyxy2xywhr(torch.from_numpy(instances.segments)) if len(instances.segments) else torch.zeros((0, 5))
  1713. )
  1714. # NOTE: need to normalize obb in xywhr format for width-height consistency
  1715. if self.normalize:
  1716. labels["bboxes"][:, [0, 2]] /= w
  1717. labels["bboxes"][:, [1, 3]] /= h
  1718. # Then we can use collate_fn
  1719. if self.batch_idx:
  1720. labels["batch_idx"] = torch.zeros(nl)
  1721. return labels
  1722. def _format_img(self, img):
  1723. """
  1724. Formats an image for YOLO from a Numpy array to a PyTorch tensor.
  1725. This function performs the following operations:
  1726. 1. Ensures the image has 3 dimensions (adds a channel dimension if needed).
  1727. 2. Transposes the image from HWC to CHW format.
  1728. 3. Optionally flips the color channels from RGB to BGR.
  1729. 4. Converts the image to a contiguous array.
  1730. 5. Converts the Numpy array to a PyTorch tensor.
  1731. Args:
  1732. img (np.ndarray): Input image as a Numpy array with shape (H, W, C) or (H, W).
  1733. Returns:
  1734. (torch.Tensor): Formatted image as a PyTorch tensor with shape (C, H, W).
  1735. Examples:
  1736. >>> import numpy as np
  1737. >>> img = np.random.rand(100, 100, 3)
  1738. >>> formatted_img = self._format_img(img)
  1739. >>> print(formatted_img.shape)
  1740. torch.Size([3, 100, 100])
  1741. """
  1742. if len(img.shape) < 3:
  1743. img = np.expand_dims(img, -1)
  1744. img = img.transpose(2, 0, 1)
  1745. img = np.ascontiguousarray(img[::-1] if random.uniform(0, 1) > self.bgr else img)
  1746. img = torch.from_numpy(img)
  1747. return img
  1748. def _format_segments(self, instances, cls, w, h):
  1749. """
  1750. Converts polygon segments to bitmap masks.
  1751. Args:
  1752. instances (Instances): Object containing segment information.
  1753. cls (numpy.ndarray): Class labels for each instance.
  1754. w (int): Width of the image.
  1755. h (int): Height of the image.
  1756. Returns:
  1757. masks (numpy.ndarray): Bitmap masks with shape (N, H, W) or (1, H, W) if mask_overlap is True.
  1758. instances (Instances): Updated instances object with sorted segments if mask_overlap is True.
  1759. cls (numpy.ndarray): Updated class labels, sorted if mask_overlap is True.
  1760. Notes:
  1761. - If self.mask_overlap is True, masks are overlapped and sorted by area.
  1762. - If self.mask_overlap is False, each mask is represented separately.
  1763. - Masks are downsampled according to self.mask_ratio.
  1764. """
  1765. segments = instances.segments
  1766. if self.mask_overlap:
  1767. masks, sorted_idx = polygons2masks_overlap((h, w), segments, downsample_ratio=self.mask_ratio)
  1768. masks = masks[None] # (640, 640) -> (1, 640, 640)
  1769. instances = instances[sorted_idx]
  1770. cls = cls[sorted_idx]
  1771. else:
  1772. masks = polygons2masks((h, w), segments, color=1, downsample_ratio=self.mask_ratio)
  1773. return masks, instances, cls
  1774. class RandomLoadText:
  1775. """
  1776. Randomly samples positive and negative texts and updates class indices accordingly.
  1777. This class is responsible for sampling texts from a given set of class texts, including both positive
  1778. (present in the image) and negative (not present in the image) samples. It updates the class indices
  1779. to reflect the sampled texts and can optionally pad the text list to a fixed length.
  1780. Attributes:
  1781. prompt_format (str): Format string for text prompts.
  1782. neg_samples (Tuple[int, int]): Range for randomly sampling negative texts.
  1783. max_samples (int): Maximum number of different text samples in one image.
  1784. padding (bool): Whether to pad texts to max_samples.
  1785. padding_value (str): The text used for padding when padding is True.
  1786. Methods:
  1787. __call__: Processes the input labels and returns updated classes and texts.
  1788. Examples:
  1789. >>> loader = RandomLoadText(prompt_format="Object: {}", neg_samples=(5, 10), max_samples=20)
  1790. >>> labels = {"cls": [0, 1, 2], "texts": [["cat"], ["dog"], ["bird"]], "instances": [...]}
  1791. >>> updated_labels = loader(labels)
  1792. >>> print(updated_labels["texts"])
  1793. ['Object: cat', 'Object: dog', 'Object: bird', 'Object: elephant', 'Object: car']
  1794. """
  1795. def __init__(
  1796. self,
  1797. prompt_format: str = "{}",
  1798. neg_samples: Tuple[int, int] = (80, 80),
  1799. max_samples: int = 80,
  1800. padding: bool = False,
  1801. padding_value: str = "",
  1802. ) -> None:
  1803. """
  1804. Initializes the RandomLoadText class for randomly sampling positive and negative texts.
  1805. This class is designed to randomly sample positive texts and negative texts, and update the class
  1806. indices accordingly to the number of samples. It can be used for text-based object detection tasks.
  1807. Args:
  1808. prompt_format (str): Format string for the prompt. Default is '{}'. The format string should
  1809. contain a single pair of curly braces {} where the text will be inserted.
  1810. neg_samples (Tuple[int, int]): A range to randomly sample negative texts. The first integer
  1811. specifies the minimum number of negative samples, and the second integer specifies the
  1812. maximum. Default is (80, 80).
  1813. max_samples (int): The maximum number of different text samples in one image. Default is 80.
  1814. padding (bool): Whether to pad texts to max_samples. If True, the number of texts will always
  1815. be equal to max_samples. Default is False.
  1816. padding_value (str): The padding text to use when padding is True. Default is an empty string.
  1817. Attributes:
  1818. prompt_format (str): The format string for the prompt.
  1819. neg_samples (Tuple[int, int]): The range for sampling negative texts.
  1820. max_samples (int): The maximum number of text samples.
  1821. padding (bool): Whether padding is enabled.
  1822. padding_value (str): The value used for padding.
  1823. Examples:
  1824. >>> random_load_text = RandomLoadText(prompt_format="Object: {}", neg_samples=(50, 100), max_samples=120)
  1825. >>> random_load_text.prompt_format
  1826. 'Object: {}'
  1827. >>> random_load_text.neg_samples
  1828. (50, 100)
  1829. >>> random_load_text.max_samples
  1830. 120
  1831. """
  1832. self.prompt_format = prompt_format
  1833. self.neg_samples = neg_samples
  1834. self.max_samples = max_samples
  1835. self.padding = padding
  1836. self.padding_value = padding_value
  1837. def __call__(self, labels: dict) -> dict:
  1838. """
  1839. Randomly samples positive and negative texts and updates class indices accordingly.
  1840. This method samples positive texts based on the existing class labels in the image, and randomly
  1841. selects negative texts from the remaining classes. It then updates the class indices to match the
  1842. new sampled text order.
  1843. Args:
  1844. labels (Dict): A dictionary containing image labels and metadata. Must include 'texts' and 'cls' keys.
  1845. Returns:
  1846. (Dict): Updated labels dictionary with new 'cls' and 'texts' entries.
  1847. Examples:
  1848. >>> loader = RandomLoadText(prompt_format="A photo of {}", neg_samples=(5, 10), max_samples=20)
  1849. >>> labels = {"cls": np.array([[0], [1], [2]]), "texts": [["dog"], ["cat"], ["bird"]]}
  1850. >>> updated_labels = loader(labels)
  1851. """
  1852. assert "texts" in labels, "No texts found in labels."
  1853. class_texts = labels["texts"]
  1854. num_classes = len(class_texts)
  1855. cls = np.asarray(labels.pop("cls"), dtype=int)
  1856. pos_labels = np.unique(cls).tolist()
  1857. if len(pos_labels) > self.max_samples:
  1858. pos_labels = random.sample(pos_labels, k=self.max_samples)
  1859. neg_samples = min(min(num_classes, self.max_samples) - len(pos_labels), random.randint(*self.neg_samples))
  1860. neg_labels = [i for i in range(num_classes) if i not in pos_labels]
  1861. neg_labels = random.sample(neg_labels, k=neg_samples)
  1862. sampled_labels = pos_labels + neg_labels
  1863. random.shuffle(sampled_labels)
  1864. label2ids = {label: i for i, label in enumerate(sampled_labels)}
  1865. valid_idx = np.zeros(len(labels["instances"]), dtype=bool)
  1866. new_cls = []
  1867. for i, label in enumerate(cls.squeeze(-1).tolist()):
  1868. if label not in label2ids:
  1869. continue
  1870. valid_idx[i] = True
  1871. new_cls.append([label2ids[label]])
  1872. labels["instances"] = labels["instances"][valid_idx]
  1873. labels["cls"] = np.array(new_cls)
  1874. # Randomly select one prompt when there's more than one prompts
  1875. texts = []
  1876. for label in sampled_labels:
  1877. prompts = class_texts[label]
  1878. assert len(prompts) > 0
  1879. prompt = self.prompt_format.format(prompts[random.randrange(len(prompts))])
  1880. texts.append(prompt)
  1881. if self.padding:
  1882. valid_labels = len(pos_labels) + len(neg_labels)
  1883. num_padding = self.max_samples - valid_labels
  1884. if num_padding > 0:
  1885. texts += [self.padding_value] * num_padding
  1886. labels["texts"] = texts
  1887. return labels
  1888. def v8_transforms(dataset, imgsz, hyp, stretch=False):
  1889. """
  1890. Applies a series of image transformations for training.
  1891. This function creates a composition of image augmentation techniques to prepare images for YOLO training.
  1892. It includes operations such as mosaic, copy-paste, random perspective, mixup, and various color adjustments.
  1893. Args:
  1894. dataset (Dataset): The dataset object containing image data and annotations.
  1895. imgsz (int): The target image size for resizing.
  1896. hyp (Namespace): A dictionary of hyperparameters controlling various aspects of the transformations.
  1897. stretch (bool): If True, applies stretching to the image. If False, uses LetterBox resizing.
  1898. Returns:
  1899. (Compose): A composition of image transformations to be applied to the dataset.
  1900. Examples:
  1901. >>> from ultralytics.data.dataset import YOLODataset
  1902. >>> from ultralytics.utils import IterableSimpleNamespace
  1903. >>> dataset = YOLODataset(img_path="path/to/images", imgsz=640)
  1904. >>> hyp = IterableSimpleNamespace(mosaic=1.0, copy_paste=0.5, degrees=10.0, translate=0.2, scale=0.9)
  1905. >>> transforms = v8_transforms(dataset, imgsz=640, hyp=hyp)
  1906. >>> augmented_data = transforms(dataset[0])
  1907. """
  1908. mosaic = Mosaic(dataset, imgsz=imgsz, p=hyp.mosaic)
  1909. affine = RandomPerspective(
  1910. degrees=hyp.degrees,
  1911. translate=hyp.translate,
  1912. scale=hyp.scale,
  1913. shear=hyp.shear,
  1914. perspective=hyp.perspective,
  1915. pre_transform=None if stretch else LetterBox(new_shape=(imgsz, imgsz)),
  1916. )
  1917. pre_transform = Compose([mosaic, affine])
  1918. if hyp.copy_paste_mode == "flip":
  1919. pre_transform.insert(1, CopyPaste(p=hyp.copy_paste, mode=hyp.copy_paste_mode))
  1920. else:
  1921. pre_transform.append(
  1922. CopyPaste(
  1923. dataset,
  1924. pre_transform=Compose([Mosaic(dataset, imgsz=imgsz, p=hyp.mosaic), affine]),
  1925. p=hyp.copy_paste,
  1926. mode=hyp.copy_paste_mode,
  1927. )
  1928. )
  1929. flip_idx = dataset.data.get("flip_idx", []) # for keypoints augmentation
  1930. if dataset.use_keypoints:
  1931. kpt_shape = dataset.data.get("kpt_shape", None)
  1932. if len(flip_idx) == 0 and hyp.fliplr > 0.0:
  1933. hyp.fliplr = 0.0
  1934. LOGGER.warning("WARNING ⚠️ No 'flip_idx' array defined in data.yaml, setting augmentation 'fliplr=0.0'")
  1935. elif flip_idx and (len(flip_idx) != kpt_shape[0]):
  1936. raise ValueError(f"data.yaml flip_idx={flip_idx} length must be equal to kpt_shape[0]={kpt_shape[0]}")
  1937. return Compose(
  1938. [
  1939. pre_transform,
  1940. MixUp(dataset, pre_transform=pre_transform, p=hyp.mixup),
  1941. Albumentations(p=1.0),
  1942. RandomHSV(hgain=hyp.hsv_h, sgain=hyp.hsv_s, vgain=hyp.hsv_v),
  1943. RandomFlip(direction="vertical", p=hyp.flipud),
  1944. RandomFlip(direction="horizontal", p=hyp.fliplr, flip_idx=flip_idx),
  1945. ]
  1946. ) # transforms
  1947. # Classification augmentations -----------------------------------------------------------------------------------------
  1948. def classify_transforms(
  1949. size=224,
  1950. mean=DEFAULT_MEAN,
  1951. std=DEFAULT_STD,
  1952. interpolation="BILINEAR",
  1953. crop_fraction: float = DEFAULT_CROP_FRACTION,
  1954. ):
  1955. """
  1956. Creates a composition of image transforms for classification tasks.
  1957. This function generates a sequence of torchvision transforms suitable for preprocessing images
  1958. for classification models during evaluation or inference. The transforms include resizing,
  1959. center cropping, conversion to tensor, and normalization.
  1960. Args:
  1961. size (int | tuple): The target size for the transformed image. If an int, it defines the shortest edge. If a
  1962. tuple, it defines (height, width).
  1963. mean (tuple): Mean values for each RGB channel used in normalization.
  1964. std (tuple): Standard deviation values for each RGB channel used in normalization.
  1965. interpolation (str): Interpolation method of either 'NEAREST', 'BILINEAR' or 'BICUBIC'.
  1966. crop_fraction (float): Fraction of the image to be cropped.
  1967. Returns:
  1968. (torchvision.transforms.Compose): A composition of torchvision transforms.
  1969. Examples:
  1970. >>> transforms = classify_transforms(size=224)
  1971. >>> img = Image.open("path/to/image.jpg")
  1972. >>> transformed_img = transforms(img)
  1973. """
  1974. import torchvision.transforms as T # scope for faster 'import ultralytics'
  1975. if isinstance(size, (tuple, list)):
  1976. assert len(size) == 2, f"'size' tuples must be length 2, not length {len(size)}"
  1977. scale_size = tuple(math.floor(x / crop_fraction) for x in size)
  1978. else:
  1979. scale_size = math.floor(size / crop_fraction)
  1980. scale_size = (scale_size, scale_size)
  1981. # Aspect ratio is preserved, crops center within image, no borders are added, image is lost
  1982. if scale_size[0] == scale_size[1]:
  1983. # Simple case, use torchvision built-in Resize with the shortest edge mode (scalar size arg)
  1984. tfl = [T.Resize(scale_size[0], interpolation=getattr(T.InterpolationMode, interpolation))]
  1985. else:
  1986. # Resize the shortest edge to matching target dim for non-square target
  1987. tfl = [T.Resize(scale_size)]
  1988. tfl.extend(
  1989. [
  1990. T.CenterCrop(size),
  1991. T.ToTensor(),
  1992. T.Normalize(mean=torch.tensor(mean), std=torch.tensor(std)),
  1993. ]
  1994. )
  1995. return T.Compose(tfl)
  1996. # Classification training augmentations --------------------------------------------------------------------------------
  1997. def classify_augmentations(
  1998. size=224,
  1999. mean=DEFAULT_MEAN,
  2000. std=DEFAULT_STD,
  2001. scale=None,
  2002. ratio=None,
  2003. hflip=0.5,
  2004. vflip=0.0,
  2005. auto_augment=None,
  2006. hsv_h=0.015, # image HSV-Hue augmentation (fraction)
  2007. hsv_s=0.4, # image HSV-Saturation augmentation (fraction)
  2008. hsv_v=0.4, # image HSV-Value augmentation (fraction)
  2009. force_color_jitter=False,
  2010. erasing=0.0,
  2011. interpolation="BILINEAR",
  2012. ):
  2013. """
  2014. Creates a composition of image augmentation transforms for classification tasks.
  2015. This function generates a set of image transformations suitable for training classification models. It includes
  2016. options for resizing, flipping, color jittering, auto augmentation, and random erasing.
  2017. Args:
  2018. size (int): Target size for the image after transformations.
  2019. mean (tuple): Mean values for normalization, one per channel.
  2020. std (tuple): Standard deviation values for normalization, one per channel.
  2021. scale (tuple | None): Range of size of the origin size cropped.
  2022. ratio (tuple | None): Range of aspect ratio of the origin aspect ratio cropped.
  2023. hflip (float): Probability of horizontal flip.
  2024. vflip (float): Probability of vertical flip.
  2025. auto_augment (str | None): Auto augmentation policy. Can be 'randaugment', 'augmix', 'autoaugment' or None.
  2026. hsv_h (float): Image HSV-Hue augmentation factor.
  2027. hsv_s (float): Image HSV-Saturation augmentation factor.
  2028. hsv_v (float): Image HSV-Value augmentation factor.
  2029. force_color_jitter (bool): Whether to apply color jitter even if auto augment is enabled.
  2030. erasing (float): Probability of random erasing.
  2031. interpolation (str): Interpolation method of either 'NEAREST', 'BILINEAR' or 'BICUBIC'.
  2032. Returns:
  2033. (torchvision.transforms.Compose): A composition of image augmentation transforms.
  2034. Examples:
  2035. >>> transforms = classify_augmentations(size=224, auto_augment="randaugment")
  2036. >>> augmented_image = transforms(original_image)
  2037. """
  2038. # Transforms to apply if Albumentations not installed
  2039. import torchvision.transforms as T # scope for faster 'import ultralytics'
  2040. if not isinstance(size, int):
  2041. raise TypeError(f"classify_transforms() size {size} must be integer, not (list, tuple)")
  2042. scale = tuple(scale or (0.08, 1.0)) # default imagenet scale range
  2043. ratio = tuple(ratio or (3.0 / 4.0, 4.0 / 3.0)) # default imagenet ratio range
  2044. interpolation = getattr(T.InterpolationMode, interpolation)
  2045. primary_tfl = [T.RandomResizedCrop(size, scale=scale, ratio=ratio, interpolation=interpolation)]
  2046. if hflip > 0.0:
  2047. primary_tfl.append(T.RandomHorizontalFlip(p=hflip))
  2048. if vflip > 0.0:
  2049. primary_tfl.append(T.RandomVerticalFlip(p=vflip))
  2050. secondary_tfl = []
  2051. disable_color_jitter = False
  2052. if auto_augment:
  2053. assert isinstance(auto_augment, str), f"Provided argument should be string, but got type {type(auto_augment)}"
  2054. # color jitter is typically disabled if AA/RA on,
  2055. # this allows override without breaking old hparm cfgs
  2056. disable_color_jitter = not force_color_jitter
  2057. if auto_augment == "randaugment":
  2058. if TORCHVISION_0_11:
  2059. secondary_tfl.append(T.RandAugment(interpolation=interpolation))
  2060. else:
  2061. LOGGER.warning('"auto_augment=randaugment" requires torchvision >= 0.11.0. Disabling it.')
  2062. elif auto_augment == "augmix":
  2063. if TORCHVISION_0_13:
  2064. secondary_tfl.append(T.AugMix(interpolation=interpolation))
  2065. else:
  2066. LOGGER.warning('"auto_augment=augmix" requires torchvision >= 0.13.0. Disabling it.')
  2067. elif auto_augment == "autoaugment":
  2068. if TORCHVISION_0_10:
  2069. secondary_tfl.append(T.AutoAugment(interpolation=interpolation))
  2070. else:
  2071. LOGGER.warning('"auto_augment=autoaugment" requires torchvision >= 0.10.0. Disabling it.')
  2072. else:
  2073. raise ValueError(
  2074. f'Invalid auto_augment policy: {auto_augment}. Should be one of "randaugment", '
  2075. f'"augmix", "autoaugment" or None'
  2076. )
  2077. if not disable_color_jitter:
  2078. secondary_tfl.append(T.ColorJitter(brightness=hsv_v, contrast=hsv_v, saturation=hsv_s, hue=hsv_h))
  2079. final_tfl = [
  2080. T.ToTensor(),
  2081. T.Normalize(mean=torch.tensor(mean), std=torch.tensor(std)),
  2082. T.RandomErasing(p=erasing, inplace=True),
  2083. ]
  2084. return T.Compose(primary_tfl + secondary_tfl + final_tfl)
  2085. # NOTE: keep this class for backward compatibility
  2086. class ClassifyLetterBox:
  2087. """
  2088. A class for resizing and padding images for classification tasks.
  2089. This class is designed to be part of a transformation pipeline, e.g., T.Compose([LetterBox(size), ToTensor()]).
  2090. It resizes and pads images to a specified size while maintaining the original aspect ratio.
  2091. Attributes:
  2092. h (int): Target height of the image.
  2093. w (int): Target width of the image.
  2094. auto (bool): If True, automatically calculates the short side using stride.
  2095. stride (int): The stride value, used when 'auto' is True.
  2096. Methods:
  2097. __call__: Applies the letterbox transformation to an input image.
  2098. Examples:
  2099. >>> transform = ClassifyLetterBox(size=(640, 640), auto=False, stride=32)
  2100. >>> img = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8)
  2101. >>> result = transform(img)
  2102. >>> print(result.shape)
  2103. (640, 640, 3)
  2104. """
  2105. def __init__(self, size=(640, 640), auto=False, stride=32):
  2106. """
  2107. Initializes the ClassifyLetterBox object for image preprocessing.
  2108. This class is designed to be part of a transformation pipeline for image classification tasks. It resizes and
  2109. pads images to a specified size while maintaining the original aspect ratio.
  2110. Args:
  2111. size (int | Tuple[int, int]): Target size for the letterboxed image. If an int, a square image of
  2112. (size, size) is created. If a tuple, it should be (height, width).
  2113. auto (bool): If True, automatically calculates the short side based on stride. Default is False.
  2114. stride (int): The stride value, used when 'auto' is True. Default is 32.
  2115. Attributes:
  2116. h (int): Target height of the letterboxed image.
  2117. w (int): Target width of the letterboxed image.
  2118. auto (bool): Flag indicating whether to automatically calculate short side.
  2119. stride (int): Stride value for automatic short side calculation.
  2120. Examples:
  2121. >>> transform = ClassifyLetterBox(size=224)
  2122. >>> img = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8)
  2123. >>> result = transform(img)
  2124. >>> print(result.shape)
  2125. (224, 224, 3)
  2126. """
  2127. super().__init__()
  2128. self.h, self.w = (size, size) if isinstance(size, int) else size
  2129. self.auto = auto # pass max size integer, automatically solve for short side using stride
  2130. self.stride = stride # used with auto
  2131. def __call__(self, im):
  2132. """
  2133. Resizes and pads an image using the letterbox method.
  2134. This method resizes the input image to fit within the specified dimensions while maintaining its aspect ratio,
  2135. then pads the resized image to match the target size.
  2136. Args:
  2137. im (numpy.ndarray): Input image as a numpy array with shape (H, W, C).
  2138. Returns:
  2139. (numpy.ndarray): Resized and padded image as a numpy array with shape (hs, ws, 3), where hs and ws are
  2140. the target height and width respectively.
  2141. Examples:
  2142. >>> letterbox = ClassifyLetterBox(size=(640, 640))
  2143. >>> image = np.random.randint(0, 255, (720, 1280, 3), dtype=np.uint8)
  2144. >>> resized_image = letterbox(image)
  2145. >>> print(resized_image.shape)
  2146. (640, 640, 3)
  2147. """
  2148. imh, imw = im.shape[:2]
  2149. r = min(self.h / imh, self.w / imw) # ratio of new/old dimensions
  2150. h, w = round(imh * r), round(imw * r) # resized image dimensions
  2151. # Calculate padding dimensions
  2152. hs, ws = (math.ceil(x / self.stride) * self.stride for x in (h, w)) if self.auto else (self.h, self.w)
  2153. top, left = round((hs - h) / 2 - 0.1), round((ws - w) / 2 - 0.1)
  2154. # Create padded image
  2155. im_out = np.full((hs, ws, 3), 114, dtype=im.dtype)
  2156. im_out[top : top + h, left : left + w] = cv2.resize(im, (w, h), interpolation=cv2.INTER_LINEAR)
  2157. return im_out
  2158. # NOTE: keep this class for backward compatibility
  2159. class CenterCrop:
  2160. """
  2161. Applies center cropping to images for classification tasks.
  2162. This class performs center cropping on input images, resizing them to a specified size while maintaining the aspect
  2163. ratio. It is designed to be part of a transformation pipeline, e.g., T.Compose([CenterCrop(size), ToTensor()]).
  2164. Attributes:
  2165. h (int): Target height of the cropped image.
  2166. w (int): Target width of the cropped image.
  2167. Methods:
  2168. __call__: Applies the center crop transformation to an input image.
  2169. Examples:
  2170. >>> transform = CenterCrop(640)
  2171. >>> image = np.random.randint(0, 255, (1080, 1920, 3), dtype=np.uint8)
  2172. >>> cropped_image = transform(image)
  2173. >>> print(cropped_image.shape)
  2174. (640, 640, 3)
  2175. """
  2176. def __init__(self, size=640):
  2177. """
  2178. Initializes the CenterCrop object for image preprocessing.
  2179. This class is designed to be part of a transformation pipeline, e.g., T.Compose([CenterCrop(size), ToTensor()]).
  2180. It performs a center crop on input images to a specified size.
  2181. Args:
  2182. size (int | Tuple[int, int]): The desired output size of the crop. If size is an int, a square crop
  2183. (size, size) is made. If size is a sequence like (h, w), it is used as the output size.
  2184. Returns:
  2185. (None): This method initializes the object and does not return anything.
  2186. Examples:
  2187. >>> transform = CenterCrop(224)
  2188. >>> img = np.random.rand(300, 300, 3)
  2189. >>> cropped_img = transform(img)
  2190. >>> print(cropped_img.shape)
  2191. (224, 224, 3)
  2192. """
  2193. super().__init__()
  2194. self.h, self.w = (size, size) if isinstance(size, int) else size
  2195. def __call__(self, im):
  2196. """
  2197. Applies center cropping to an input image.
  2198. This method resizes and crops the center of the image using a letterbox method. It maintains the aspect
  2199. ratio of the original image while fitting it into the specified dimensions.
  2200. Args:
  2201. im (numpy.ndarray | PIL.Image.Image): The input image as a numpy array of shape (H, W, C) or a
  2202. PIL Image object.
  2203. Returns:
  2204. (numpy.ndarray): The center-cropped and resized image as a numpy array of shape (self.h, self.w, C).
  2205. Examples:
  2206. >>> transform = CenterCrop(size=224)
  2207. >>> image = np.random.randint(0, 255, (640, 480, 3), dtype=np.uint8)
  2208. >>> cropped_image = transform(image)
  2209. >>> assert cropped_image.shape == (224, 224, 3)
  2210. """
  2211. if isinstance(im, Image.Image): # convert from PIL to numpy array if required
  2212. im = np.asarray(im)
  2213. imh, imw = im.shape[:2]
  2214. m = min(imh, imw) # min dimension
  2215. top, left = (imh - m) // 2, (imw - m) // 2
  2216. return cv2.resize(im[top : top + m, left : left + m], (self.w, self.h), interpolation=cv2.INTER_LINEAR)
  2217. # NOTE: keep this class for backward compatibility
  2218. class ToTensor:
  2219. """
  2220. Converts an image from a numpy array to a PyTorch tensor.
  2221. This class is designed to be part of a transformation pipeline, e.g., T.Compose([LetterBox(size), ToTensor()]).
  2222. Attributes:
  2223. half (bool): If True, converts the image to half precision (float16).
  2224. Methods:
  2225. __call__: Applies the tensor conversion to an input image.
  2226. Examples:
  2227. >>> transform = ToTensor(half=True)
  2228. >>> img = np.random.randint(0, 255, (640, 640, 3), dtype=np.uint8)
  2229. >>> tensor_img = transform(img)
  2230. >>> print(tensor_img.shape, tensor_img.dtype)
  2231. torch.Size([3, 640, 640]) torch.float16
  2232. Notes:
  2233. The input image is expected to be in BGR format with shape (H, W, C).
  2234. The output tensor will be in RGB format with shape (C, H, W), normalized to [0, 1].
  2235. """
  2236. def __init__(self, half=False):
  2237. """
  2238. Initializes the ToTensor object for converting images to PyTorch tensors.
  2239. This class is designed to be used as part of a transformation pipeline for image preprocessing in the
  2240. Ultralytics YOLO framework. It converts numpy arrays or PIL Images to PyTorch tensors, with an option
  2241. for half-precision (float16) conversion.
  2242. Args:
  2243. half (bool): If True, converts the tensor to half precision (float16). Default is False.
  2244. Examples:
  2245. >>> transform = ToTensor(half=True)
  2246. >>> img = np.random.rand(640, 640, 3)
  2247. >>> tensor_img = transform(img)
  2248. >>> print(tensor_img.dtype)
  2249. torch.float16
  2250. """
  2251. super().__init__()
  2252. self.half = half
  2253. def __call__(self, im):
  2254. """
  2255. Transforms an image from a numpy array to a PyTorch tensor.
  2256. This method converts the input image from a numpy array to a PyTorch tensor, applying optional
  2257. half-precision conversion and normalization. The image is transposed from HWC to CHW format and
  2258. the color channels are reversed from BGR to RGB.
  2259. Args:
  2260. im (numpy.ndarray): Input image as a numpy array with shape (H, W, C) in BGR order.
  2261. Returns:
  2262. (torch.Tensor): The transformed image as a PyTorch tensor in float32 or float16, normalized
  2263. to [0, 1] with shape (C, H, W) in RGB order.
  2264. Examples:
  2265. >>> transform = ToTensor(half=True)
  2266. >>> img = np.random.randint(0, 255, (640, 640, 3), dtype=np.uint8)
  2267. >>> tensor_img = transform(img)
  2268. >>> print(tensor_img.shape, tensor_img.dtype)
  2269. torch.Size([3, 640, 640]) torch.float16
  2270. """
  2271. im = np.ascontiguousarray(im.transpose((2, 0, 1))[::-1]) # HWC to CHW -> BGR to RGB -> contiguous
  2272. im = torch.from_numpy(im) # to torch
  2273. im = im.half() if self.half else im.float() # uint8 to fp16/32
  2274. im /= 255.0 # 0-255 to 0.0-1.0
  2275. return im