dgenerate-ultralytics-headless 8.3.253__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (299) hide show
  1. dgenerate_ultralytics_headless-8.3.253.dist-info/METADATA +405 -0
  2. dgenerate_ultralytics_headless-8.3.253.dist-info/RECORD +299 -0
  3. dgenerate_ultralytics_headless-8.3.253.dist-info/WHEEL +5 -0
  4. dgenerate_ultralytics_headless-8.3.253.dist-info/entry_points.txt +3 -0
  5. dgenerate_ultralytics_headless-8.3.253.dist-info/licenses/LICENSE +661 -0
  6. dgenerate_ultralytics_headless-8.3.253.dist-info/top_level.txt +1 -0
  7. tests/__init__.py +23 -0
  8. tests/conftest.py +59 -0
  9. tests/test_cli.py +131 -0
  10. tests/test_cuda.py +216 -0
  11. tests/test_engine.py +157 -0
  12. tests/test_exports.py +309 -0
  13. tests/test_integrations.py +151 -0
  14. tests/test_python.py +777 -0
  15. tests/test_solutions.py +371 -0
  16. ultralytics/__init__.py +48 -0
  17. ultralytics/assets/bus.jpg +0 -0
  18. ultralytics/assets/zidane.jpg +0 -0
  19. ultralytics/cfg/__init__.py +1028 -0
  20. ultralytics/cfg/datasets/Argoverse.yaml +78 -0
  21. ultralytics/cfg/datasets/DOTAv1.5.yaml +37 -0
  22. ultralytics/cfg/datasets/DOTAv1.yaml +36 -0
  23. ultralytics/cfg/datasets/GlobalWheat2020.yaml +68 -0
  24. ultralytics/cfg/datasets/HomeObjects-3K.yaml +32 -0
  25. ultralytics/cfg/datasets/ImageNet.yaml +2025 -0
  26. ultralytics/cfg/datasets/Objects365.yaml +447 -0
  27. ultralytics/cfg/datasets/SKU-110K.yaml +58 -0
  28. ultralytics/cfg/datasets/TT100K.yaml +346 -0
  29. ultralytics/cfg/datasets/VOC.yaml +102 -0
  30. ultralytics/cfg/datasets/VisDrone.yaml +87 -0
  31. ultralytics/cfg/datasets/african-wildlife.yaml +25 -0
  32. ultralytics/cfg/datasets/brain-tumor.yaml +22 -0
  33. ultralytics/cfg/datasets/carparts-seg.yaml +44 -0
  34. ultralytics/cfg/datasets/coco-pose.yaml +64 -0
  35. ultralytics/cfg/datasets/coco.yaml +118 -0
  36. ultralytics/cfg/datasets/coco128-seg.yaml +101 -0
  37. ultralytics/cfg/datasets/coco128.yaml +101 -0
  38. ultralytics/cfg/datasets/coco8-grayscale.yaml +103 -0
  39. ultralytics/cfg/datasets/coco8-multispectral.yaml +104 -0
  40. ultralytics/cfg/datasets/coco8-pose.yaml +47 -0
  41. ultralytics/cfg/datasets/coco8-seg.yaml +101 -0
  42. ultralytics/cfg/datasets/coco8.yaml +101 -0
  43. ultralytics/cfg/datasets/construction-ppe.yaml +32 -0
  44. ultralytics/cfg/datasets/crack-seg.yaml +22 -0
  45. ultralytics/cfg/datasets/dog-pose.yaml +52 -0
  46. ultralytics/cfg/datasets/dota8-multispectral.yaml +38 -0
  47. ultralytics/cfg/datasets/dota8.yaml +35 -0
  48. ultralytics/cfg/datasets/hand-keypoints.yaml +50 -0
  49. ultralytics/cfg/datasets/kitti.yaml +27 -0
  50. ultralytics/cfg/datasets/lvis.yaml +1240 -0
  51. ultralytics/cfg/datasets/medical-pills.yaml +21 -0
  52. ultralytics/cfg/datasets/open-images-v7.yaml +663 -0
  53. ultralytics/cfg/datasets/package-seg.yaml +22 -0
  54. ultralytics/cfg/datasets/signature.yaml +21 -0
  55. ultralytics/cfg/datasets/tiger-pose.yaml +41 -0
  56. ultralytics/cfg/datasets/xView.yaml +155 -0
  57. ultralytics/cfg/default.yaml +130 -0
  58. ultralytics/cfg/models/11/yolo11-cls-resnet18.yaml +17 -0
  59. ultralytics/cfg/models/11/yolo11-cls.yaml +33 -0
  60. ultralytics/cfg/models/11/yolo11-obb.yaml +50 -0
  61. ultralytics/cfg/models/11/yolo11-pose.yaml +51 -0
  62. ultralytics/cfg/models/11/yolo11-seg.yaml +50 -0
  63. ultralytics/cfg/models/11/yolo11.yaml +50 -0
  64. ultralytics/cfg/models/11/yoloe-11-seg.yaml +48 -0
  65. ultralytics/cfg/models/11/yoloe-11.yaml +48 -0
  66. ultralytics/cfg/models/12/yolo12-cls.yaml +32 -0
  67. ultralytics/cfg/models/12/yolo12-obb.yaml +48 -0
  68. ultralytics/cfg/models/12/yolo12-pose.yaml +49 -0
  69. ultralytics/cfg/models/12/yolo12-seg.yaml +48 -0
  70. ultralytics/cfg/models/12/yolo12.yaml +48 -0
  71. ultralytics/cfg/models/rt-detr/rtdetr-l.yaml +53 -0
  72. ultralytics/cfg/models/rt-detr/rtdetr-resnet101.yaml +45 -0
  73. ultralytics/cfg/models/rt-detr/rtdetr-resnet50.yaml +45 -0
  74. ultralytics/cfg/models/rt-detr/rtdetr-x.yaml +57 -0
  75. ultralytics/cfg/models/v10/yolov10b.yaml +45 -0
  76. ultralytics/cfg/models/v10/yolov10l.yaml +45 -0
  77. ultralytics/cfg/models/v10/yolov10m.yaml +45 -0
  78. ultralytics/cfg/models/v10/yolov10n.yaml +45 -0
  79. ultralytics/cfg/models/v10/yolov10s.yaml +45 -0
  80. ultralytics/cfg/models/v10/yolov10x.yaml +45 -0
  81. ultralytics/cfg/models/v3/yolov3-spp.yaml +49 -0
  82. ultralytics/cfg/models/v3/yolov3-tiny.yaml +40 -0
  83. ultralytics/cfg/models/v3/yolov3.yaml +49 -0
  84. ultralytics/cfg/models/v5/yolov5-p6.yaml +62 -0
  85. ultralytics/cfg/models/v5/yolov5.yaml +51 -0
  86. ultralytics/cfg/models/v6/yolov6.yaml +56 -0
  87. ultralytics/cfg/models/v8/yoloe-v8-seg.yaml +48 -0
  88. ultralytics/cfg/models/v8/yoloe-v8.yaml +48 -0
  89. ultralytics/cfg/models/v8/yolov8-cls-resnet101.yaml +28 -0
  90. ultralytics/cfg/models/v8/yolov8-cls-resnet50.yaml +28 -0
  91. ultralytics/cfg/models/v8/yolov8-cls.yaml +32 -0
  92. ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml +58 -0
  93. ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml +60 -0
  94. ultralytics/cfg/models/v8/yolov8-ghost.yaml +50 -0
  95. ultralytics/cfg/models/v8/yolov8-obb.yaml +49 -0
  96. ultralytics/cfg/models/v8/yolov8-p2.yaml +57 -0
  97. ultralytics/cfg/models/v8/yolov8-p6.yaml +59 -0
  98. ultralytics/cfg/models/v8/yolov8-pose-p6.yaml +60 -0
  99. ultralytics/cfg/models/v8/yolov8-pose.yaml +50 -0
  100. ultralytics/cfg/models/v8/yolov8-rtdetr.yaml +49 -0
  101. ultralytics/cfg/models/v8/yolov8-seg-p6.yaml +59 -0
  102. ultralytics/cfg/models/v8/yolov8-seg.yaml +49 -0
  103. ultralytics/cfg/models/v8/yolov8-world.yaml +51 -0
  104. ultralytics/cfg/models/v8/yolov8-worldv2.yaml +49 -0
  105. ultralytics/cfg/models/v8/yolov8.yaml +49 -0
  106. ultralytics/cfg/models/v9/yolov9c-seg.yaml +41 -0
  107. ultralytics/cfg/models/v9/yolov9c.yaml +41 -0
  108. ultralytics/cfg/models/v9/yolov9e-seg.yaml +64 -0
  109. ultralytics/cfg/models/v9/yolov9e.yaml +64 -0
  110. ultralytics/cfg/models/v9/yolov9m.yaml +41 -0
  111. ultralytics/cfg/models/v9/yolov9s.yaml +41 -0
  112. ultralytics/cfg/models/v9/yolov9t.yaml +41 -0
  113. ultralytics/cfg/trackers/botsort.yaml +21 -0
  114. ultralytics/cfg/trackers/bytetrack.yaml +12 -0
  115. ultralytics/data/__init__.py +26 -0
  116. ultralytics/data/annotator.py +66 -0
  117. ultralytics/data/augment.py +2801 -0
  118. ultralytics/data/base.py +435 -0
  119. ultralytics/data/build.py +437 -0
  120. ultralytics/data/converter.py +855 -0
  121. ultralytics/data/dataset.py +834 -0
  122. ultralytics/data/loaders.py +704 -0
  123. ultralytics/data/scripts/download_weights.sh +18 -0
  124. ultralytics/data/scripts/get_coco.sh +61 -0
  125. ultralytics/data/scripts/get_coco128.sh +18 -0
  126. ultralytics/data/scripts/get_imagenet.sh +52 -0
  127. ultralytics/data/split.py +138 -0
  128. ultralytics/data/split_dota.py +344 -0
  129. ultralytics/data/utils.py +798 -0
  130. ultralytics/engine/__init__.py +1 -0
  131. ultralytics/engine/exporter.py +1580 -0
  132. ultralytics/engine/model.py +1125 -0
  133. ultralytics/engine/predictor.py +508 -0
  134. ultralytics/engine/results.py +1522 -0
  135. ultralytics/engine/trainer.py +977 -0
  136. ultralytics/engine/tuner.py +449 -0
  137. ultralytics/engine/validator.py +387 -0
  138. ultralytics/hub/__init__.py +166 -0
  139. ultralytics/hub/auth.py +151 -0
  140. ultralytics/hub/google/__init__.py +174 -0
  141. ultralytics/hub/session.py +422 -0
  142. ultralytics/hub/utils.py +162 -0
  143. ultralytics/models/__init__.py +9 -0
  144. ultralytics/models/fastsam/__init__.py +7 -0
  145. ultralytics/models/fastsam/model.py +79 -0
  146. ultralytics/models/fastsam/predict.py +169 -0
  147. ultralytics/models/fastsam/utils.py +23 -0
  148. ultralytics/models/fastsam/val.py +38 -0
  149. ultralytics/models/nas/__init__.py +7 -0
  150. ultralytics/models/nas/model.py +98 -0
  151. ultralytics/models/nas/predict.py +56 -0
  152. ultralytics/models/nas/val.py +38 -0
  153. ultralytics/models/rtdetr/__init__.py +7 -0
  154. ultralytics/models/rtdetr/model.py +63 -0
  155. ultralytics/models/rtdetr/predict.py +88 -0
  156. ultralytics/models/rtdetr/train.py +89 -0
  157. ultralytics/models/rtdetr/val.py +216 -0
  158. ultralytics/models/sam/__init__.py +25 -0
  159. ultralytics/models/sam/amg.py +275 -0
  160. ultralytics/models/sam/build.py +365 -0
  161. ultralytics/models/sam/build_sam3.py +377 -0
  162. ultralytics/models/sam/model.py +169 -0
  163. ultralytics/models/sam/modules/__init__.py +1 -0
  164. ultralytics/models/sam/modules/blocks.py +1067 -0
  165. ultralytics/models/sam/modules/decoders.py +495 -0
  166. ultralytics/models/sam/modules/encoders.py +794 -0
  167. ultralytics/models/sam/modules/memory_attention.py +298 -0
  168. ultralytics/models/sam/modules/sam.py +1160 -0
  169. ultralytics/models/sam/modules/tiny_encoder.py +979 -0
  170. ultralytics/models/sam/modules/transformer.py +344 -0
  171. ultralytics/models/sam/modules/utils.py +512 -0
  172. ultralytics/models/sam/predict.py +3940 -0
  173. ultralytics/models/sam/sam3/__init__.py +3 -0
  174. ultralytics/models/sam/sam3/decoder.py +546 -0
  175. ultralytics/models/sam/sam3/encoder.py +529 -0
  176. ultralytics/models/sam/sam3/geometry_encoders.py +415 -0
  177. ultralytics/models/sam/sam3/maskformer_segmentation.py +286 -0
  178. ultralytics/models/sam/sam3/model_misc.py +199 -0
  179. ultralytics/models/sam/sam3/necks.py +129 -0
  180. ultralytics/models/sam/sam3/sam3_image.py +339 -0
  181. ultralytics/models/sam/sam3/text_encoder_ve.py +307 -0
  182. ultralytics/models/sam/sam3/vitdet.py +547 -0
  183. ultralytics/models/sam/sam3/vl_combiner.py +160 -0
  184. ultralytics/models/utils/__init__.py +1 -0
  185. ultralytics/models/utils/loss.py +466 -0
  186. ultralytics/models/utils/ops.py +315 -0
  187. ultralytics/models/yolo/__init__.py +7 -0
  188. ultralytics/models/yolo/classify/__init__.py +7 -0
  189. ultralytics/models/yolo/classify/predict.py +90 -0
  190. ultralytics/models/yolo/classify/train.py +202 -0
  191. ultralytics/models/yolo/classify/val.py +216 -0
  192. ultralytics/models/yolo/detect/__init__.py +7 -0
  193. ultralytics/models/yolo/detect/predict.py +122 -0
  194. ultralytics/models/yolo/detect/train.py +227 -0
  195. ultralytics/models/yolo/detect/val.py +507 -0
  196. ultralytics/models/yolo/model.py +430 -0
  197. ultralytics/models/yolo/obb/__init__.py +7 -0
  198. ultralytics/models/yolo/obb/predict.py +56 -0
  199. ultralytics/models/yolo/obb/train.py +79 -0
  200. ultralytics/models/yolo/obb/val.py +302 -0
  201. ultralytics/models/yolo/pose/__init__.py +7 -0
  202. ultralytics/models/yolo/pose/predict.py +65 -0
  203. ultralytics/models/yolo/pose/train.py +110 -0
  204. ultralytics/models/yolo/pose/val.py +248 -0
  205. ultralytics/models/yolo/segment/__init__.py +7 -0
  206. ultralytics/models/yolo/segment/predict.py +109 -0
  207. ultralytics/models/yolo/segment/train.py +69 -0
  208. ultralytics/models/yolo/segment/val.py +307 -0
  209. ultralytics/models/yolo/world/__init__.py +5 -0
  210. ultralytics/models/yolo/world/train.py +173 -0
  211. ultralytics/models/yolo/world/train_world.py +178 -0
  212. ultralytics/models/yolo/yoloe/__init__.py +22 -0
  213. ultralytics/models/yolo/yoloe/predict.py +162 -0
  214. ultralytics/models/yolo/yoloe/train.py +287 -0
  215. ultralytics/models/yolo/yoloe/train_seg.py +122 -0
  216. ultralytics/models/yolo/yoloe/val.py +206 -0
  217. ultralytics/nn/__init__.py +27 -0
  218. ultralytics/nn/autobackend.py +964 -0
  219. ultralytics/nn/modules/__init__.py +182 -0
  220. ultralytics/nn/modules/activation.py +54 -0
  221. ultralytics/nn/modules/block.py +1947 -0
  222. ultralytics/nn/modules/conv.py +669 -0
  223. ultralytics/nn/modules/head.py +1183 -0
  224. ultralytics/nn/modules/transformer.py +793 -0
  225. ultralytics/nn/modules/utils.py +159 -0
  226. ultralytics/nn/tasks.py +1768 -0
  227. ultralytics/nn/text_model.py +356 -0
  228. ultralytics/py.typed +1 -0
  229. ultralytics/solutions/__init__.py +41 -0
  230. ultralytics/solutions/ai_gym.py +108 -0
  231. ultralytics/solutions/analytics.py +264 -0
  232. ultralytics/solutions/config.py +107 -0
  233. ultralytics/solutions/distance_calculation.py +123 -0
  234. ultralytics/solutions/heatmap.py +125 -0
  235. ultralytics/solutions/instance_segmentation.py +86 -0
  236. ultralytics/solutions/object_blurrer.py +89 -0
  237. ultralytics/solutions/object_counter.py +190 -0
  238. ultralytics/solutions/object_cropper.py +87 -0
  239. ultralytics/solutions/parking_management.py +280 -0
  240. ultralytics/solutions/queue_management.py +93 -0
  241. ultralytics/solutions/region_counter.py +133 -0
  242. ultralytics/solutions/security_alarm.py +151 -0
  243. ultralytics/solutions/similarity_search.py +219 -0
  244. ultralytics/solutions/solutions.py +828 -0
  245. ultralytics/solutions/speed_estimation.py +114 -0
  246. ultralytics/solutions/streamlit_inference.py +260 -0
  247. ultralytics/solutions/templates/similarity-search.html +156 -0
  248. ultralytics/solutions/trackzone.py +88 -0
  249. ultralytics/solutions/vision_eye.py +67 -0
  250. ultralytics/trackers/__init__.py +7 -0
  251. ultralytics/trackers/basetrack.py +115 -0
  252. ultralytics/trackers/bot_sort.py +257 -0
  253. ultralytics/trackers/byte_tracker.py +469 -0
  254. ultralytics/trackers/track.py +116 -0
  255. ultralytics/trackers/utils/__init__.py +1 -0
  256. ultralytics/trackers/utils/gmc.py +339 -0
  257. ultralytics/trackers/utils/kalman_filter.py +482 -0
  258. ultralytics/trackers/utils/matching.py +154 -0
  259. ultralytics/utils/__init__.py +1450 -0
  260. ultralytics/utils/autobatch.py +118 -0
  261. ultralytics/utils/autodevice.py +205 -0
  262. ultralytics/utils/benchmarks.py +728 -0
  263. ultralytics/utils/callbacks/__init__.py +5 -0
  264. ultralytics/utils/callbacks/base.py +233 -0
  265. ultralytics/utils/callbacks/clearml.py +146 -0
  266. ultralytics/utils/callbacks/comet.py +625 -0
  267. ultralytics/utils/callbacks/dvc.py +197 -0
  268. ultralytics/utils/callbacks/hub.py +110 -0
  269. ultralytics/utils/callbacks/mlflow.py +134 -0
  270. ultralytics/utils/callbacks/neptune.py +126 -0
  271. ultralytics/utils/callbacks/platform.py +453 -0
  272. ultralytics/utils/callbacks/raytune.py +42 -0
  273. ultralytics/utils/callbacks/tensorboard.py +123 -0
  274. ultralytics/utils/callbacks/wb.py +188 -0
  275. ultralytics/utils/checks.py +1020 -0
  276. ultralytics/utils/cpu.py +85 -0
  277. ultralytics/utils/dist.py +123 -0
  278. ultralytics/utils/downloads.py +529 -0
  279. ultralytics/utils/errors.py +35 -0
  280. ultralytics/utils/events.py +113 -0
  281. ultralytics/utils/export/__init__.py +7 -0
  282. ultralytics/utils/export/engine.py +237 -0
  283. ultralytics/utils/export/imx.py +325 -0
  284. ultralytics/utils/export/tensorflow.py +231 -0
  285. ultralytics/utils/files.py +219 -0
  286. ultralytics/utils/git.py +137 -0
  287. ultralytics/utils/instance.py +484 -0
  288. ultralytics/utils/logger.py +506 -0
  289. ultralytics/utils/loss.py +849 -0
  290. ultralytics/utils/metrics.py +1563 -0
  291. ultralytics/utils/nms.py +337 -0
  292. ultralytics/utils/ops.py +664 -0
  293. ultralytics/utils/patches.py +201 -0
  294. ultralytics/utils/plotting.py +1047 -0
  295. ultralytics/utils/tal.py +404 -0
  296. ultralytics/utils/torch_utils.py +984 -0
  297. ultralytics/utils/tqdm.py +443 -0
  298. ultralytics/utils/triton.py +112 -0
  299. ultralytics/utils/tuner.py +168 -0
@@ -0,0 +1,2801 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import random
7
+ from copy import deepcopy
8
+ from typing import Any
9
+
10
+ import cv2
11
+ import numpy as np
12
+ import torch
13
+ from PIL import Image
14
+ from torch.nn import functional as F
15
+
16
+ from ultralytics.data.utils import polygons2masks, polygons2masks_overlap
17
+ from ultralytics.utils import LOGGER, IterableSimpleNamespace, colorstr
18
+ from ultralytics.utils.checks import check_version
19
+ from ultralytics.utils.instance import Instances
20
+ from ultralytics.utils.metrics import bbox_ioa
21
+ from ultralytics.utils.ops import segment2box, xywh2xyxy, xyxyxyxy2xywhr
22
+ from ultralytics.utils.torch_utils import TORCHVISION_0_10, TORCHVISION_0_11, TORCHVISION_0_13
23
+
24
+ DEFAULT_MEAN = (0.0, 0.0, 0.0)
25
+ DEFAULT_STD = (1.0, 1.0, 1.0)
26
+
27
+
28
+ class BaseTransform:
29
+ """Base class for image transformations in the Ultralytics library.
30
+
31
+ This class serves as a foundation for implementing various image processing operations, designed to be compatible
32
+ with both classification and semantic segmentation tasks.
33
+
34
+ Methods:
35
+ apply_image: Apply image transformations to labels.
36
+ apply_instances: Apply transformations to object instances in labels.
37
+ apply_semantic: Apply semantic segmentation to an image.
38
+ __call__: Apply all label transformations to an image, instances, and semantic masks.
39
+
40
+ Examples:
41
+ >>> transform = BaseTransform()
42
+ >>> labels = {"image": np.array(...), "instances": [...], "semantic": np.array(...)}
43
+ >>> transformed_labels = transform(labels)
44
+ """
45
+
46
+ def __init__(self) -> None:
47
+ """Initialize the BaseTransform object.
48
+
49
+ This constructor sets up the base transformation object, which can be extended for specific image processing
50
+ tasks. It is designed to be compatible with both classification and semantic segmentation.
51
+ """
52
+ pass
53
+
54
+ def apply_image(self, labels):
55
+ """Apply image transformations to labels.
56
+
57
+ This method is intended to be overridden by subclasses to implement specific image transformation
58
+ logic. In its base form, it returns the input labels unchanged.
59
+
60
+ Args:
61
+ labels (Any): The input labels to be transformed. The exact type and structure of labels may vary depending
62
+ on the specific implementation.
63
+
64
+ Returns:
65
+ (Any): The transformed labels. In the base implementation, this is identical to the input.
66
+
67
+ Examples:
68
+ >>> transform = BaseTransform()
69
+ >>> original_labels = [1, 2, 3]
70
+ >>> transformed_labels = transform.apply_image(original_labels)
71
+ >>> print(transformed_labels)
72
+ [1, 2, 3]
73
+ """
74
+ pass
75
+
76
+ def apply_instances(self, labels):
77
+ """Apply transformations to object instances in labels.
78
+
79
+ This method is responsible for applying various transformations to object instances within the given
80
+ labels. It is designed to be overridden by subclasses to implement specific instance transformation
81
+ logic.
82
+
83
+ Args:
84
+ labels (dict): A dictionary containing label information, including object instances.
85
+
86
+ Returns:
87
+ (dict): The modified labels dictionary with transformed object instances.
88
+
89
+ Examples:
90
+ >>> transform = BaseTransform()
91
+ >>> labels = {"instances": Instances(xyxy=torch.rand(5, 4), cls=torch.randint(0, 80, (5,)))}
92
+ >>> transformed_labels = transform.apply_instances(labels)
93
+ """
94
+ pass
95
+
96
+ def apply_semantic(self, labels):
97
+ """Apply semantic segmentation transformations to an image.
98
+
99
+ This method is intended to be overridden by subclasses to implement specific semantic segmentation
100
+ transformations. In its base form, it does not perform any operations.
101
+
102
+ Args:
103
+ labels (Any): The input labels or semantic segmentation mask to be transformed.
104
+
105
+ Returns:
106
+ (Any): The transformed semantic segmentation mask or labels.
107
+
108
+ Examples:
109
+ >>> transform = BaseTransform()
110
+ >>> semantic_mask = np.zeros((100, 100), dtype=np.uint8)
111
+ >>> transformed_mask = transform.apply_semantic(semantic_mask)
112
+ """
113
+ pass
114
+
115
+ def __call__(self, labels):
116
+ """Apply all label transformations to an image, instances, and semantic masks.
117
+
118
+ This method orchestrates the application of various transformations defined in the BaseTransform class to the
119
+ input labels. It sequentially calls the apply_image and apply_instances methods to process the image and object
120
+ instances, respectively.
121
+
122
+ Args:
123
+ labels (dict): A dictionary containing image data and annotations. Expected keys include 'img' for the image
124
+ data, and 'instances' for object instances.
125
+
126
+ Returns:
127
+ (dict): The input labels dictionary with transformed image and instances.
128
+
129
+ Examples:
130
+ >>> transform = BaseTransform()
131
+ >>> labels = {"img": np.random.rand(640, 640, 3), "instances": []}
132
+ >>> transformed_labels = transform(labels)
133
+ """
134
+ self.apply_image(labels)
135
+ self.apply_instances(labels)
136
+ self.apply_semantic(labels)
137
+
138
+
139
+ class Compose:
140
+ """A class for composing multiple image transformations.
141
+
142
+ Attributes:
143
+ transforms (list[Callable]): A list of transformation functions to be applied sequentially.
144
+
145
+ Methods:
146
+ __call__: Apply a series of transformations to input data.
147
+ append: Append a new transform to the existing list of transforms.
148
+ insert: Insert a new transform at a specified index in the list of transforms.
149
+ __getitem__: Retrieve a specific transform or a set of transforms using indexing.
150
+ __setitem__: Set a specific transform or a set of transforms using indexing.
151
+ tolist: Convert the list of transforms to a standard Python list.
152
+
153
+ Examples:
154
+ >>> transforms = [RandomFlip(), RandomPerspective(30)]
155
+ >>> compose = Compose(transforms)
156
+ >>> transformed_data = compose(data)
157
+ >>> compose.append(CenterCrop((224, 224)))
158
+ >>> compose.insert(0, RandomFlip())
159
+ """
160
+
161
+ def __init__(self, transforms):
162
+ """Initialize the Compose object with a list of transforms.
163
+
164
+ Args:
165
+ transforms (list[Callable]): A list of callable transform objects to be applied sequentially.
166
+ """
167
+ self.transforms = transforms if isinstance(transforms, list) else [transforms]
168
+
169
+ def __call__(self, data):
170
+ """Apply a series of transformations to input data.
171
+
172
+ This method sequentially applies each transformation in the Compose object's transforms to the input data.
173
+
174
+ Args:
175
+ data (Any): The input data to be transformed. This can be of any type, depending on the transformations in
176
+ the list.
177
+
178
+ Returns:
179
+ (Any): The transformed data after applying all transformations in sequence.
180
+
181
+ Examples:
182
+ >>> transforms = [Transform1(), Transform2(), Transform3()]
183
+ >>> compose = Compose(transforms)
184
+ >>> transformed_data = compose(input_data)
185
+ """
186
+ for t in self.transforms:
187
+ data = t(data)
188
+ return data
189
+
190
+ def append(self, transform):
191
+ """Append a new transform to the existing list of transforms.
192
+
193
+ Args:
194
+ transform (BaseTransform): The transformation to be added to the composition.
195
+
196
+ Examples:
197
+ >>> compose = Compose([RandomFlip(), RandomPerspective()])
198
+ >>> compose.append(RandomHSV())
199
+ """
200
+ self.transforms.append(transform)
201
+
202
+ def insert(self, index, transform):
203
+ """Insert a new transform at a specified index in the existing list of transforms.
204
+
205
+ Args:
206
+ index (int): The index at which to insert the new transform.
207
+ transform (BaseTransform): The transform object to be inserted.
208
+
209
+ Examples:
210
+ >>> compose = Compose([Transform1(), Transform2()])
211
+ >>> compose.insert(1, Transform3())
212
+ >>> len(compose.transforms)
213
+ 3
214
+ """
215
+ self.transforms.insert(index, transform)
216
+
217
+ def __getitem__(self, index: list | int) -> Compose:
218
+ """Retrieve a specific transform or a set of transforms using indexing.
219
+
220
+ Args:
221
+ index (int | list[int]): Index or list of indices of the transforms to retrieve.
222
+
223
+ Returns:
224
+ (Compose): A new Compose object containing the selected transform(s).
225
+
226
+ Raises:
227
+ AssertionError: If the index is not of type int or list.
228
+
229
+ Examples:
230
+ >>> transforms = [RandomFlip(), RandomPerspective(10), RandomHSV(0.5, 0.5, 0.5)]
231
+ >>> compose = Compose(transforms)
232
+ >>> single_transform = compose[1] # Returns a Compose object with only RandomPerspective
233
+ >>> multiple_transforms = compose[0:2] # Returns a Compose object with RandomFlip and RandomPerspective
234
+ """
235
+ assert isinstance(index, (int, list)), f"The indices should be either list or int type but got {type(index)}"
236
+ return Compose([self.transforms[i] for i in index]) if isinstance(index, list) else self.transforms[index]
237
+
238
+ def __setitem__(self, index: list | int, value: list | int) -> None:
239
+ """Set one or more transforms in the composition using indexing.
240
+
241
+ Args:
242
+ index (int | list[int]): Index or list of indices to set transforms at.
243
+ value (Any | list[Any]): Transform or list of transforms to set at the specified index(es).
244
+
245
+ Raises:
246
+ AssertionError: If index type is invalid, value type doesn't match index type, or index is out of range.
247
+
248
+ Examples:
249
+ >>> compose = Compose([Transform1(), Transform2(), Transform3()])
250
+ >>> compose[1] = NewTransform() # Replace second transform
251
+ >>> compose[0:2] = [NewTransform1(), NewTransform2()] # Replace first two transforms
252
+ """
253
+ assert isinstance(index, (int, list)), f"The indices should be either list or int type but got {type(index)}"
254
+ if isinstance(index, list):
255
+ assert isinstance(value, list), (
256
+ f"The indices should be the same type as values, but got {type(index)} and {type(value)}"
257
+ )
258
+ if isinstance(index, int):
259
+ index, value = [index], [value]
260
+ for i, v in zip(index, value):
261
+ assert i < len(self.transforms), f"list index {i} out of range {len(self.transforms)}."
262
+ self.transforms[i] = v
263
+
264
+ def tolist(self):
265
+ """Convert the list of transforms to a standard Python list.
266
+
267
+ Returns:
268
+ (list): A list containing all the transform objects in the Compose instance.
269
+
270
+ Examples:
271
+ >>> transforms = [RandomFlip(), RandomPerspective(10), CenterCrop()]
272
+ >>> compose = Compose(transforms)
273
+ >>> transform_list = compose.tolist()
274
+ >>> print(len(transform_list))
275
+ 3
276
+ """
277
+ return self.transforms
278
+
279
+ def __repr__(self):
280
+ """Return a string representation of the Compose object.
281
+
282
+ Returns:
283
+ (str): A string representation of the Compose object, including the list of transforms.
284
+
285
+ Examples:
286
+ >>> transforms = [RandomFlip(), RandomPerspective(degrees=10, translate=0.1, scale=0.1)]
287
+ >>> compose = Compose(transforms)
288
+ >>> print(compose)
289
+ Compose([
290
+ RandomFlip(),
291
+ RandomPerspective(degrees=10, translate=0.1, scale=0.1)
292
+ ])
293
+ """
294
+ return f"{self.__class__.__name__}({', '.join([f'{t}' for t in self.transforms])})"
295
+
296
+
297
+ class BaseMixTransform:
298
+ """Base class for mix transformations like Cutmix, MixUp and Mosaic.
299
+
300
+ This class provides a foundation for implementing mix transformations on datasets. It handles the probability-based
301
+ application of transforms and manages the mixing of multiple images and labels.
302
+
303
+ Attributes:
304
+ dataset (Any): The dataset object containing images and labels.
305
+ pre_transform (Callable | None): Optional transform to apply before mixing.
306
+ p (float): Probability of applying the mix transformation.
307
+
308
+ Methods:
309
+ __call__: Apply the mix transformation to the input labels.
310
+ _mix_transform: Abstract method to be implemented by subclasses for specific mix operations.
311
+ get_indexes: Abstract method to get indexes of images to be mixed.
312
+ _update_label_text: Update label text for mixed images.
313
+
314
+ Examples:
315
+ >>> class CustomMixTransform(BaseMixTransform):
316
+ ... def _mix_transform(self, labels):
317
+ ... # Implement custom mix logic here
318
+ ... return labels
319
+ ...
320
+ ... def get_indexes(self):
321
+ ... return [random.randint(0, len(self.dataset) - 1) for _ in range(3)]
322
+ >>> dataset = YourDataset()
323
+ >>> transform = CustomMixTransform(dataset, p=0.5)
324
+ >>> mixed_labels = transform(original_labels)
325
+ """
326
+
327
+ def __init__(self, dataset, pre_transform=None, p=0.0) -> None:
328
+ """Initialize the BaseMixTransform object for mix transformations like CutMix, MixUp and Mosaic.
329
+
330
+ This class serves as a base for implementing mix transformations in image processing pipelines.
331
+
332
+ Args:
333
+ dataset (Any): The dataset object containing images and labels for mixing.
334
+ pre_transform (Callable | None): Optional transform to apply before mixing.
335
+ p (float): Probability of applying the mix transformation. Should be in the range [0.0, 1.0].
336
+ """
337
+ self.dataset = dataset
338
+ self.pre_transform = pre_transform
339
+ self.p = p
340
+
341
+ def __call__(self, labels: dict[str, Any]) -> dict[str, Any]:
342
+ """Apply pre-processing transforms and cutmix/mixup/mosaic transforms to labels data.
343
+
344
+ This method determines whether to apply the mix transform based on a probability factor. If applied, it selects
345
+ additional images, applies pre-transforms if specified, and then performs the mix transform.
346
+
347
+ Args:
348
+ labels (dict[str, Any]): A dictionary containing label data for an image.
349
+
350
+ Returns:
351
+ (dict[str, Any]): The transformed labels dictionary, which may include mixed data from other images.
352
+
353
+ Examples:
354
+ >>> transform = BaseMixTransform(dataset, pre_transform=None, p=0.5)
355
+ >>> result = transform({"image": img, "bboxes": boxes, "cls": classes})
356
+ """
357
+ if random.uniform(0, 1) > self.p:
358
+ return labels
359
+
360
+ # Get index of one or three other images
361
+ indexes = self.get_indexes()
362
+ if isinstance(indexes, int):
363
+ indexes = [indexes]
364
+
365
+ # Get images information will be used for Mosaic, CutMix or MixUp
366
+ mix_labels = [self.dataset.get_image_and_label(i) for i in indexes]
367
+
368
+ if self.pre_transform is not None:
369
+ for i, data in enumerate(mix_labels):
370
+ mix_labels[i] = self.pre_transform(data)
371
+ labels["mix_labels"] = mix_labels
372
+
373
+ # Update cls and texts
374
+ labels = self._update_label_text(labels)
375
+ # Mosaic, CutMix or MixUp
376
+ labels = self._mix_transform(labels)
377
+ labels.pop("mix_labels", None)
378
+ return labels
379
+
380
+ def _mix_transform(self, labels: dict[str, Any]):
381
+ """Apply CutMix, MixUp or Mosaic augmentation to the label dictionary.
382
+
383
+ This method should be implemented by subclasses to perform specific mix transformations like CutMix, MixUp or
384
+ Mosaic. It modifies the input label dictionary in-place with the augmented data.
385
+
386
+ Args:
387
+ labels (dict[str, Any]): A dictionary containing image and label data. Expected to have a 'mix_labels' key
388
+ with a list of additional image and label data for mixing.
389
+
390
+ Returns:
391
+ (dict[str, Any]): The modified labels dictionary with augmented data after applying the mix transform.
392
+
393
+ Examples:
394
+ >>> transform = BaseMixTransform(dataset)
395
+ >>> labels = {"image": img, "bboxes": boxes, "mix_labels": [{"image": img2, "bboxes": boxes2}]}
396
+ >>> augmented_labels = transform._mix_transform(labels)
397
+ """
398
+ raise NotImplementedError
399
+
400
+ def get_indexes(self):
401
+ """Get a list of shuffled indexes for mosaic augmentation.
402
+
403
+ Returns:
404
+ (list[int]): A list of shuffled indexes from the dataset.
405
+
406
+ Examples:
407
+ >>> transform = BaseMixTransform(dataset)
408
+ >>> indexes = transform.get_indexes()
409
+ >>> print(indexes) # [3, 18, 7, 2]
410
+ """
411
+ return random.randint(0, len(self.dataset) - 1)
412
+
413
+ @staticmethod
414
+ def _update_label_text(labels: dict[str, Any]) -> dict[str, Any]:
415
+ """Update label text and class IDs for mixed labels in image augmentation.
416
+
417
+ This method processes the 'texts' and 'cls' fields of the input labels dictionary and any mixed labels, creating
418
+ a unified set of text labels and updating class IDs accordingly.
419
+
420
+ Args:
421
+ labels (dict[str, Any]): A dictionary containing label information, including 'texts' and 'cls' fields, and
422
+ optionally a 'mix_labels' field with additional label dictionaries.
423
+
424
+ Returns:
425
+ (dict[str, Any]): The updated labels dictionary with unified text labels and updated class IDs.
426
+
427
+ Examples:
428
+ >>> labels = {
429
+ ... "texts": [["cat"], ["dog"]],
430
+ ... "cls": torch.tensor([[0], [1]]),
431
+ ... "mix_labels": [{"texts": [["bird"], ["fish"]], "cls": torch.tensor([[0], [1]])}],
432
+ ... }
433
+ >>> updated_labels = self._update_label_text(labels)
434
+ >>> print(updated_labels["texts"])
435
+ [['cat'], ['dog'], ['bird'], ['fish']]
436
+ >>> print(updated_labels["cls"])
437
+ tensor([[0],
438
+ [1]])
439
+ >>> print(updated_labels["mix_labels"][0]["cls"])
440
+ tensor([[2],
441
+ [3]])
442
+ """
443
+ if "texts" not in labels:
444
+ return labels
445
+
446
+ mix_texts = [*labels["texts"], *(item for x in labels["mix_labels"] for item in x["texts"])]
447
+ mix_texts = list({tuple(x) for x in mix_texts})
448
+ text2id = {text: i for i, text in enumerate(mix_texts)}
449
+
450
+ for label in [labels] + labels["mix_labels"]:
451
+ for i, cls in enumerate(label["cls"].squeeze(-1).tolist()):
452
+ text = label["texts"][int(cls)]
453
+ label["cls"][i] = text2id[tuple(text)]
454
+ label["texts"] = mix_texts
455
+ return labels
456
+
457
+
458
+ class Mosaic(BaseMixTransform):
459
+ """Mosaic augmentation for image datasets.
460
+
461
+ This class performs mosaic augmentation by combining multiple (4 or 9) images into a single mosaic image. The
462
+ augmentation is applied to a dataset with a given probability.
463
+
464
+ Attributes:
465
+ dataset: The dataset on which the mosaic augmentation is applied.
466
+ imgsz (int): Image size (height and width) after mosaic pipeline of a single image.
467
+ p (float): Probability of applying the mosaic augmentation. Must be in the range 0-1.
468
+ n (int): The grid size, either 4 (for 2x2) or 9 (for 3x3).
469
+ border (tuple[int, int]): Border size for width and height.
470
+
471
+ Methods:
472
+ get_indexes: Return a list of random indexes from the dataset.
473
+ _mix_transform: Apply mixup transformation to the input image and labels.
474
+ _mosaic3: Create a 1x3 image mosaic.
475
+ _mosaic4: Create a 2x2 image mosaic.
476
+ _mosaic9: Create a 3x3 image mosaic.
477
+ _update_labels: Update labels with padding.
478
+ _cat_labels: Concatenate labels and clips mosaic border instances.
479
+
480
+ Examples:
481
+ >>> from ultralytics.data.augment import Mosaic
482
+ >>> dataset = YourDataset(...) # Your image dataset
483
+ >>> mosaic_aug = Mosaic(dataset, imgsz=640, p=0.5, n=4)
484
+ >>> augmented_labels = mosaic_aug(original_labels)
485
+ """
486
+
487
+ def __init__(self, dataset, imgsz: int = 640, p: float = 1.0, n: int = 4):
488
+ """Initialize the Mosaic augmentation object.
489
+
490
+ This class performs mosaic augmentation by combining multiple (4 or 9) images into a single mosaic image. The
491
+ augmentation is applied to a dataset with a given probability.
492
+
493
+ Args:
494
+ dataset (Any): The dataset on which the mosaic augmentation is applied.
495
+ imgsz (int): Image size (height and width) after mosaic pipeline of a single image.
496
+ p (float): Probability of applying the mosaic augmentation. Must be in the range 0-1.
497
+ n (int): The grid size, either 4 (for 2x2) or 9 (for 3x3).
498
+ """
499
+ assert 0 <= p <= 1.0, f"The probability should be in range [0, 1], but got {p}."
500
+ assert n in {4, 9}, "grid must be equal to 4 or 9."
501
+ super().__init__(dataset=dataset, p=p)
502
+ self.imgsz = imgsz
503
+ self.border = (-imgsz // 2, -imgsz // 2) # width, height
504
+ self.n = n
505
+ self.buffer_enabled = self.dataset.cache != "ram"
506
+
507
+ def get_indexes(self):
508
+ """Return a list of random indexes from the dataset for mosaic augmentation.
509
+
510
+ This method selects random image indexes either from a buffer or from the entire dataset, depending on the
511
+ 'buffer' parameter. It is used to choose images for creating mosaic augmentations.
512
+
513
+ Returns:
514
+ (list[int]): A list of random image indexes. The length of the list is n-1, where n is the number of images
515
+ used in the mosaic (either 3 or 8, depending on whether n is 4 or 9).
516
+
517
+ Examples:
518
+ >>> mosaic = Mosaic(dataset, imgsz=640, p=1.0, n=4)
519
+ >>> indexes = mosaic.get_indexes()
520
+ >>> print(len(indexes)) # Output: 3
521
+ """
522
+ if self.buffer_enabled: # select images from buffer
523
+ return random.choices(list(self.dataset.buffer), k=self.n - 1)
524
+ else: # select any images
525
+ return [random.randint(0, len(self.dataset) - 1) for _ in range(self.n - 1)]
526
+
527
+ def _mix_transform(self, labels: dict[str, Any]) -> dict[str, Any]:
528
+ """Apply mosaic augmentation to the input image and labels.
529
+
530
+ This method combines multiple images (3, 4, or 9) into a single mosaic image based on the 'n' attribute. It
531
+ ensures that rectangular annotations are not present and that there are other images available for mosaic
532
+ augmentation.
533
+
534
+ Args:
535
+ labels (dict[str, Any]): A dictionary containing image data and annotations. Expected keys include:
536
+ - 'rect_shape': Should be None as rect and mosaic are mutually exclusive.
537
+ - 'mix_labels': A list of dictionaries containing data for other images to be used in the mosaic.
538
+
539
+ Returns:
540
+ (dict[str, Any]): A dictionary containing the mosaic-augmented image and updated annotations.
541
+
542
+ Raises:
543
+ AssertionError: If 'rect_shape' is not None or if 'mix_labels' is empty.
544
+
545
+ Examples:
546
+ >>> mosaic = Mosaic(dataset, imgsz=640, p=1.0, n=4)
547
+ >>> augmented_data = mosaic._mix_transform(labels)
548
+ """
549
+ assert labels.get("rect_shape") is None, "rect and mosaic are mutually exclusive."
550
+ assert len(labels.get("mix_labels", [])), "There are no other images for mosaic augment."
551
+ return (
552
+ self._mosaic3(labels) if self.n == 3 else self._mosaic4(labels) if self.n == 4 else self._mosaic9(labels)
553
+ ) # This code is modified for mosaic3 method.
554
+
555
+ def _mosaic3(self, labels: dict[str, Any]) -> dict[str, Any]:
556
+ """Create a 1x3 image mosaic by combining three images.
557
+
558
+ This method arranges three images in a horizontal layout, with the main image in the center and two additional
559
+ images on either side. It's part of the Mosaic augmentation technique used in object detection.
560
+
561
+ Args:
562
+ labels (dict[str, Any]): A dictionary containing image and label information for the main (center) image.
563
+ Must include 'img' key with the image array, and 'mix_labels' key with a list of two dictionaries
564
+ containing information for the side images.
565
+
566
+ Returns:
567
+ (dict[str, Any]): A dictionary with the mosaic image and updated labels. Keys include:
568
+ - 'img' (np.ndarray): The mosaic image array with shape (H, W, C).
569
+ - Other keys from the input labels, updated to reflect the new image dimensions.
570
+
571
+ Examples:
572
+ >>> mosaic = Mosaic(dataset, imgsz=640, p=1.0, n=3)
573
+ >>> labels = {
574
+ ... "img": np.random.rand(480, 640, 3),
575
+ ... "mix_labels": [{"img": np.random.rand(480, 640, 3)} for _ in range(2)],
576
+ ... }
577
+ >>> result = mosaic._mosaic3(labels)
578
+ >>> print(result["img"].shape)
579
+ (640, 640, 3)
580
+ """
581
+ mosaic_labels = []
582
+ s = self.imgsz
583
+ for i in range(3):
584
+ labels_patch = labels if i == 0 else labels["mix_labels"][i - 1]
585
+ # Load image
586
+ img = labels_patch["img"]
587
+ h, w = labels_patch.pop("resized_shape")
588
+
589
+ # Place img in img3
590
+ if i == 0: # center
591
+ img3 = np.full((s * 3, s * 3, img.shape[2]), 114, dtype=np.uint8) # base image with 3 tiles
592
+ h0, w0 = h, w
593
+ c = s, s, s + w, s + h # xmin, ymin, xmax, ymax (base) coordinates
594
+ elif i == 1: # right
595
+ c = s + w0, s, s + w0 + w, s + h
596
+ elif i == 2: # left
597
+ c = s - w, s + h0 - h, s, s + h0
598
+
599
+ padw, padh = c[:2]
600
+ x1, y1, x2, y2 = (max(x, 0) for x in c) # allocate coordinates
601
+
602
+ img3[y1:y2, x1:x2] = img[y1 - padh :, x1 - padw :] # img3[ymin:ymax, xmin:xmax]
603
+ # hp, wp = h, w # height, width previous for next iteration
604
+
605
+ # Labels assuming imgsz*2 mosaic size
606
+ labels_patch = self._update_labels(labels_patch, padw + self.border[0], padh + self.border[1])
607
+ mosaic_labels.append(labels_patch)
608
+ final_labels = self._cat_labels(mosaic_labels)
609
+
610
+ final_labels["img"] = img3[-self.border[0] : self.border[0], -self.border[1] : self.border[1]]
611
+ return final_labels
612
+
613
+ def _mosaic4(self, labels: dict[str, Any]) -> dict[str, Any]:
614
+ """Create a 2x2 image mosaic from four input images.
615
+
616
+ This method combines four images into a single mosaic image by placing them in a 2x2 grid. It also updates the
617
+ corresponding labels for each image in the mosaic.
618
+
619
+ Args:
620
+ labels (dict[str, Any]): A dictionary containing image data and labels for the base image (index 0) and
621
+ three additional images (indices 1-3) in the 'mix_labels' key.
622
+
623
+ Returns:
624
+ (dict[str, Any]): A dictionary containing the mosaic image and updated labels. The 'img' key contains the
625
+ mosaic image as a numpy array, and other keys contain the combined and adjusted labels for all
626
+ four images.
627
+
628
+ Examples:
629
+ >>> mosaic = Mosaic(dataset, imgsz=640, p=1.0, n=4)
630
+ >>> labels = {
631
+ ... "img": np.random.rand(480, 640, 3),
632
+ ... "mix_labels": [{"img": np.random.rand(480, 640, 3)} for _ in range(3)],
633
+ ... }
634
+ >>> result = mosaic._mosaic4(labels)
635
+ >>> assert result["img"].shape == (1280, 1280, 3)
636
+ """
637
+ mosaic_labels = []
638
+ s = self.imgsz
639
+ yc, xc = (int(random.uniform(-x, 2 * s + x)) for x in self.border) # mosaic center x, y
640
+ for i in range(4):
641
+ labels_patch = labels if i == 0 else labels["mix_labels"][i - 1]
642
+ # Load image
643
+ img = labels_patch["img"]
644
+ h, w = labels_patch.pop("resized_shape")
645
+
646
+ # Place img in img4
647
+ if i == 0: # top left
648
+ img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
649
+ x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image)
650
+ x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image)
651
+ elif i == 1: # top right
652
+ x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc
653
+ x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h
654
+ elif i == 2: # bottom left
655
+ x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h)
656
+ x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h)
657
+ elif i == 3: # bottom right
658
+ x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h)
659
+ x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)
660
+
661
+ img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax]
662
+ padw = x1a - x1b
663
+ padh = y1a - y1b
664
+
665
+ labels_patch = self._update_labels(labels_patch, padw, padh)
666
+ mosaic_labels.append(labels_patch)
667
+ final_labels = self._cat_labels(mosaic_labels)
668
+ final_labels["img"] = img4
669
+ return final_labels
670
+
671
+ def _mosaic9(self, labels: dict[str, Any]) -> dict[str, Any]:
672
+ """Create a 3x3 image mosaic from the input image and eight additional images.
673
+
674
+ This method combines nine images into a single mosaic image. The input image is placed at the center, and eight
675
+ additional images from the dataset are placed around it in a 3x3 grid pattern.
676
+
677
+ Args:
678
+ labels (dict[str, Any]): A dictionary containing the input image and its associated labels. It should have
679
+ the following keys:
680
+ - 'img' (np.ndarray): The input image.
681
+ - 'resized_shape' (tuple[int, int]): The shape of the resized image (height, width).
682
+ - 'mix_labels' (list[dict]): A list of dictionaries containing information for the additional
683
+ eight images, each with the same structure as the input labels.
684
+
685
+ Returns:
686
+ (dict[str, Any]): A dictionary containing the mosaic image and updated labels. It includes the following
687
+ keys:
688
+ - 'img' (np.ndarray): The final mosaic image.
689
+ - Other keys from the input labels, updated to reflect the new mosaic arrangement.
690
+
691
+ Examples:
692
+ >>> mosaic = Mosaic(dataset, imgsz=640, p=1.0, n=9)
693
+ >>> input_labels = dataset[0]
694
+ >>> mosaic_result = mosaic._mosaic9(input_labels)
695
+ >>> mosaic_image = mosaic_result["img"]
696
+ """
697
+ mosaic_labels = []
698
+ s = self.imgsz
699
+ hp, wp = -1, -1 # height, width previous
700
+ for i in range(9):
701
+ labels_patch = labels if i == 0 else labels["mix_labels"][i - 1]
702
+ # Load image
703
+ img = labels_patch["img"]
704
+ h, w = labels_patch.pop("resized_shape")
705
+
706
+ # Place img in img9
707
+ if i == 0: # center
708
+ img9 = np.full((s * 3, s * 3, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
709
+ h0, w0 = h, w
710
+ c = s, s, s + w, s + h # xmin, ymin, xmax, ymax (base) coordinates
711
+ elif i == 1: # top
712
+ c = s, s - h, s + w, s
713
+ elif i == 2: # top right
714
+ c = s + wp, s - h, s + wp + w, s
715
+ elif i == 3: # right
716
+ c = s + w0, s, s + w0 + w, s + h
717
+ elif i == 4: # bottom right
718
+ c = s + w0, s + hp, s + w0 + w, s + hp + h
719
+ elif i == 5: # bottom
720
+ c = s + w0 - w, s + h0, s + w0, s + h0 + h
721
+ elif i == 6: # bottom left
722
+ c = s + w0 - wp - w, s + h0, s + w0 - wp, s + h0 + h
723
+ elif i == 7: # left
724
+ c = s - w, s + h0 - h, s, s + h0
725
+ elif i == 8: # top left
726
+ c = s - w, s + h0 - hp - h, s, s + h0 - hp
727
+
728
+ padw, padh = c[:2]
729
+ x1, y1, x2, y2 = (max(x, 0) for x in c) # allocate coordinates
730
+
731
+ # Image
732
+ img9[y1:y2, x1:x2] = img[y1 - padh :, x1 - padw :] # img9[ymin:ymax, xmin:xmax]
733
+ hp, wp = h, w # height, width previous for next iteration
734
+
735
+ # Labels assuming imgsz*2 mosaic size
736
+ labels_patch = self._update_labels(labels_patch, padw + self.border[0], padh + self.border[1])
737
+ mosaic_labels.append(labels_patch)
738
+ final_labels = self._cat_labels(mosaic_labels)
739
+
740
+ final_labels["img"] = img9[-self.border[0] : self.border[0], -self.border[1] : self.border[1]]
741
+ return final_labels
742
+
743
+ @staticmethod
744
+ def _update_labels(labels, padw: int, padh: int) -> dict[str, Any]:
745
+ """Update label coordinates with padding values.
746
+
747
+ This method adjusts the bounding box coordinates of object instances in the labels by adding padding
748
+ values. It also denormalizes the coordinates if they were previously normalized.
749
+
750
+ Args:
751
+ labels (dict[str, Any]): A dictionary containing image and instance information.
752
+ padw (int): Padding width to be added to the x-coordinates.
753
+ padh (int): Padding height to be added to the y-coordinates.
754
+
755
+ Returns:
756
+ (dict): Updated labels dictionary with adjusted instance coordinates.
757
+
758
+ Examples:
759
+ >>> labels = {"img": np.zeros((100, 100, 3)), "instances": Instances(...)}
760
+ >>> padw, padh = 50, 50
761
+ >>> updated_labels = Mosaic._update_labels(labels, padw, padh)
762
+ """
763
+ nh, nw = labels["img"].shape[:2]
764
+ labels["instances"].convert_bbox(format="xyxy")
765
+ labels["instances"].denormalize(nw, nh)
766
+ labels["instances"].add_padding(padw, padh)
767
+ return labels
768
+
769
+ def _cat_labels(self, mosaic_labels: list[dict[str, Any]]) -> dict[str, Any]:
770
+ """Concatenate and process labels for mosaic augmentation.
771
+
772
+ This method combines labels from multiple images used in mosaic augmentation, clips instances to the mosaic
773
+ border, and removes zero-area boxes.
774
+
775
+ Args:
776
+ mosaic_labels (list[dict[str, Any]]): A list of label dictionaries for each image in the mosaic.
777
+
778
+ Returns:
779
+ (dict[str, Any]): A dictionary containing concatenated and processed labels for the mosaic image, including:
780
+ - im_file (str): File path of the first image in the mosaic.
781
+ - ori_shape (tuple[int, int]): Original shape of the first image.
782
+ - resized_shape (tuple[int, int]): Shape of the mosaic image (imgsz * 2, imgsz * 2).
783
+ - cls (np.ndarray): Concatenated class labels.
784
+ - instances (Instances): Concatenated instance annotations.
785
+ - mosaic_border (tuple[int, int]): Mosaic border size.
786
+ - texts (list[str], optional): Text labels if present in the original labels.
787
+
788
+ Examples:
789
+ >>> mosaic = Mosaic(dataset, imgsz=640)
790
+ >>> mosaic_labels = [{"cls": np.array([0, 1]), "instances": Instances(...)} for _ in range(4)]
791
+ >>> result = mosaic._cat_labels(mosaic_labels)
792
+ >>> print(result.keys())
793
+ dict_keys(['im_file', 'ori_shape', 'resized_shape', 'cls', 'instances', 'mosaic_border'])
794
+ """
795
+ if not mosaic_labels:
796
+ return {}
797
+ cls = []
798
+ instances = []
799
+ imgsz = self.imgsz * 2 # mosaic imgsz
800
+ for labels in mosaic_labels:
801
+ cls.append(labels["cls"])
802
+ instances.append(labels["instances"])
803
+ # Final labels
804
+ final_labels = {
805
+ "im_file": mosaic_labels[0]["im_file"],
806
+ "ori_shape": mosaic_labels[0]["ori_shape"],
807
+ "resized_shape": (imgsz, imgsz),
808
+ "cls": np.concatenate(cls, 0),
809
+ "instances": Instances.concatenate(instances, axis=0),
810
+ "mosaic_border": self.border,
811
+ }
812
+ final_labels["instances"].clip(imgsz, imgsz)
813
+ good = final_labels["instances"].remove_zero_area_boxes()
814
+ final_labels["cls"] = final_labels["cls"][good]
815
+ if "texts" in mosaic_labels[0]:
816
+ final_labels["texts"] = mosaic_labels[0]["texts"]
817
+ return final_labels
818
+
819
+
820
+ class MixUp(BaseMixTransform):
821
+ """Apply MixUp augmentation to image datasets.
822
+
823
+ This class implements the MixUp augmentation technique as described in the paper [mixup: Beyond Empirical Risk
824
+ Minimization](https://arxiv.org/abs/1710.09412). MixUp combines two images and their labels using a random weight.
825
+
826
+ Attributes:
827
+ dataset (Any): The dataset to which MixUp augmentation will be applied.
828
+ pre_transform (Callable | None): Optional transform to apply before MixUp.
829
+ p (float): Probability of applying MixUp augmentation.
830
+
831
+ Methods:
832
+ _mix_transform: Apply MixUp augmentation to the input labels.
833
+
834
+ Examples:
835
+ >>> from ultralytics.data.augment import MixUp
836
+ >>> dataset = YourDataset(...) # Your image dataset
837
+ >>> mixup = MixUp(dataset, p=0.5)
838
+ >>> augmented_labels = mixup(original_labels)
839
+ """
840
+
841
+ def __init__(self, dataset, pre_transform=None, p: float = 0.0) -> None:
842
+ """Initialize the MixUp augmentation object.
843
+
844
+ MixUp is an image augmentation technique that combines two images by taking a weighted sum of their pixel values
845
+ and labels. This implementation is designed for use with the Ultralytics YOLO framework.
846
+
847
+ Args:
848
+ dataset (Any): The dataset to which MixUp augmentation will be applied.
849
+ pre_transform (Callable | None): Optional transform to apply to images before MixUp.
850
+ p (float): Probability of applying MixUp augmentation to an image. Must be in the range [0, 1].
851
+ """
852
+ super().__init__(dataset=dataset, pre_transform=pre_transform, p=p)
853
+
854
+ def _mix_transform(self, labels: dict[str, Any]) -> dict[str, Any]:
855
+ """Apply MixUp augmentation to the input labels.
856
+
857
+ This method implements the MixUp augmentation technique as described in the paper "mixup: Beyond Empirical Risk
858
+ Minimization" (https://arxiv.org/abs/1710.09412).
859
+
860
+ Args:
861
+ labels (dict[str, Any]): A dictionary containing the original image and label information.
862
+
863
+ Returns:
864
+ (dict[str, Any]): A dictionary containing the mixed-up image and combined label information.
865
+
866
+ Examples:
867
+ >>> mixer = MixUp(dataset)
868
+ >>> mixed_labels = mixer._mix_transform(labels)
869
+ """
870
+ r = np.random.beta(32.0, 32.0) # mixup ratio, alpha=beta=32.0
871
+ labels2 = labels["mix_labels"][0]
872
+ labels["img"] = (labels["img"] * r + labels2["img"] * (1 - r)).astype(np.uint8)
873
+ labels["instances"] = Instances.concatenate([labels["instances"], labels2["instances"]], axis=0)
874
+ labels["cls"] = np.concatenate([labels["cls"], labels2["cls"]], 0)
875
+ return labels
876
+
877
+
878
+ class CutMix(BaseMixTransform):
879
+ """Apply CutMix augmentation to image datasets as described in the paper https://arxiv.org/abs/1905.04899.
880
+
881
+ CutMix combines two images by replacing a random rectangular region of one image with the corresponding region from
882
+ another image, and adjusts the labels proportionally to the area of the mixed region.
883
+
884
+ Attributes:
885
+ dataset (Any): The dataset to which CutMix augmentation will be applied.
886
+ pre_transform (Callable | None): Optional transform to apply before CutMix.
887
+ p (float): Probability of applying CutMix augmentation.
888
+ beta (float): Beta distribution parameter for sampling the mixing ratio.
889
+ num_areas (int): Number of areas to try to cut and mix.
890
+
891
+ Methods:
892
+ _mix_transform: Apply CutMix augmentation to the input labels.
893
+ _rand_bbox: Generate random bounding box coordinates for the cut region.
894
+
895
+ Examples:
896
+ >>> from ultralytics.data.augment import CutMix
897
+ >>> dataset = YourDataset(...) # Your image dataset
898
+ >>> cutmix = CutMix(dataset, p=0.5)
899
+ >>> augmented_labels = cutmix(original_labels)
900
+ """
901
+
902
+ def __init__(self, dataset, pre_transform=None, p: float = 0.0, beta: float = 1.0, num_areas: int = 3) -> None:
903
+ """Initialize the CutMix augmentation object.
904
+
905
+ Args:
906
+ dataset (Any): The dataset to which CutMix augmentation will be applied.
907
+ pre_transform (Callable | None): Optional transform to apply before CutMix.
908
+ p (float): Probability of applying CutMix augmentation.
909
+ beta (float): Beta distribution parameter for sampling the mixing ratio.
910
+ num_areas (int): Number of areas to try to cut and mix.
911
+ """
912
+ super().__init__(dataset=dataset, pre_transform=pre_transform, p=p)
913
+ self.beta = beta
914
+ self.num_areas = num_areas
915
+
916
+ def _rand_bbox(self, width: int, height: int) -> tuple[int, int, int, int]:
917
+ """Generate random bounding box coordinates for the cut region.
918
+
919
+ Args:
920
+ width (int): Width of the image.
921
+ height (int): Height of the image.
922
+
923
+ Returns:
924
+ (tuple[int]): (x1, y1, x2, y2) coordinates of the bounding box.
925
+ """
926
+ # Sample mixing ratio from Beta distribution
927
+ lam = np.random.beta(self.beta, self.beta)
928
+
929
+ cut_ratio = np.sqrt(1.0 - lam)
930
+ cut_w = int(width * cut_ratio)
931
+ cut_h = int(height * cut_ratio)
932
+
933
+ # Random center
934
+ cx = np.random.randint(width)
935
+ cy = np.random.randint(height)
936
+
937
+ # Bounding box coordinates
938
+ x1 = np.clip(cx - cut_w // 2, 0, width)
939
+ y1 = np.clip(cy - cut_h // 2, 0, height)
940
+ x2 = np.clip(cx + cut_w // 2, 0, width)
941
+ y2 = np.clip(cy + cut_h // 2, 0, height)
942
+
943
+ return x1, y1, x2, y2
944
+
945
+ def _mix_transform(self, labels: dict[str, Any]) -> dict[str, Any]:
946
+ """Apply CutMix augmentation to the input labels.
947
+
948
+ Args:
949
+ labels (dict[str, Any]): A dictionary containing the original image and label information.
950
+
951
+ Returns:
952
+ (dict[str, Any]): A dictionary containing the mixed image and adjusted labels.
953
+
954
+ Examples:
955
+ >>> cutter = CutMix(dataset)
956
+ >>> mixed_labels = cutter._mix_transform(labels)
957
+ """
958
+ # Get a random second image
959
+ h, w = labels["img"].shape[:2]
960
+
961
+ cut_areas = np.asarray([self._rand_bbox(w, h) for _ in range(self.num_areas)], dtype=np.float32)
962
+ ioa1 = bbox_ioa(cut_areas, labels["instances"].bboxes) # (self.num_areas, num_boxes)
963
+ idx = np.nonzero(ioa1.sum(axis=1) <= 0)[0]
964
+ if len(idx) == 0:
965
+ return labels
966
+
967
+ labels2 = labels.pop("mix_labels")[0]
968
+ area = cut_areas[np.random.choice(idx)] # randomly select one
969
+ ioa2 = bbox_ioa(area[None], labels2["instances"].bboxes).squeeze(0)
970
+ indexes2 = np.nonzero(ioa2 >= (0.01 if len(labels["instances"].segments) else 0.1))[0]
971
+ if len(indexes2) == 0:
972
+ return labels
973
+
974
+ instances2 = labels2["instances"][indexes2]
975
+ instances2.convert_bbox("xyxy")
976
+ instances2.denormalize(w, h)
977
+
978
+ # Apply CutMix
979
+ x1, y1, x2, y2 = area.astype(np.int32)
980
+ labels["img"][y1:y2, x1:x2] = labels2["img"][y1:y2, x1:x2]
981
+
982
+ # Restrain instances2 to the random bounding border
983
+ instances2.add_padding(-x1, -y1)
984
+ instances2.clip(x2 - x1, y2 - y1)
985
+ instances2.add_padding(x1, y1)
986
+
987
+ labels["cls"] = np.concatenate([labels["cls"], labels2["cls"][indexes2]], axis=0)
988
+ labels["instances"] = Instances.concatenate([labels["instances"], instances2], axis=0)
989
+ return labels
990
+
991
+
992
+ class RandomPerspective:
993
+ """Implement random perspective and affine transformations on images and corresponding annotations.
994
+
995
+ This class applies random rotations, translations, scaling, shearing, and perspective transformations to images and
996
+ their associated bounding boxes, segments, and keypoints. It can be used as part of an augmentation pipeline for
997
+ object detection and instance segmentation tasks.
998
+
999
+ Attributes:
1000
+ degrees (float): Maximum absolute degree range for random rotations.
1001
+ translate (float): Maximum translation as a fraction of the image size.
1002
+ scale (float): Scaling factor range, e.g., scale=0.1 means 0.9-1.1.
1003
+ shear (float): Maximum shear angle in degrees.
1004
+ perspective (float): Perspective distortion factor.
1005
+ border (tuple[int, int]): Mosaic border size as (x, y).
1006
+ pre_transform (Callable | None): Optional transform to apply before the random perspective.
1007
+
1008
+ Methods:
1009
+ affine_transform: Apply affine transformations to the input image.
1010
+ apply_bboxes: Transform bounding boxes using the affine matrix.
1011
+ apply_segments: Transform segments and generate new bounding boxes.
1012
+ apply_keypoints: Transform keypoints using the affine matrix.
1013
+ __call__: Apply the random perspective transformation to images and annotations.
1014
+ box_candidates: Filter transformed bounding boxes based on size and aspect ratio.
1015
+
1016
+ Examples:
1017
+ >>> transform = RandomPerspective(degrees=10, translate=0.1, scale=0.1, shear=10)
1018
+ >>> image = np.random.randint(0, 255, (640, 640, 3), dtype=np.uint8)
1019
+ >>> labels = {"img": image, "cls": np.array([0, 1]), "instances": Instances(...)}
1020
+ >>> result = transform(labels)
1021
+ >>> transformed_image = result["img"]
1022
+ >>> transformed_instances = result["instances"]
1023
+ """
1024
+
1025
+ def __init__(
1026
+ self,
1027
+ degrees: float = 0.0,
1028
+ translate: float = 0.1,
1029
+ scale: float = 0.5,
1030
+ shear: float = 0.0,
1031
+ perspective: float = 0.0,
1032
+ border: tuple[int, int] = (0, 0),
1033
+ pre_transform=None,
1034
+ ):
1035
+ """Initialize RandomPerspective object with transformation parameters.
1036
+
1037
+ This class implements random perspective and affine transformations on images and corresponding bounding boxes,
1038
+ segments, and keypoints. Transformations include rotation, translation, scaling, and shearing.
1039
+
1040
+ Args:
1041
+ degrees (float): Degree range for random rotations.
1042
+ translate (float): Fraction of total width and height for random translation.
1043
+ scale (float): Scaling factor interval, e.g., a scale factor of 0.5 allows a resize between 50%-150%.
1044
+ shear (float): Shear intensity (angle in degrees).
1045
+ perspective (float): Perspective distortion factor.
1046
+ border (tuple[int, int]): Tuple specifying mosaic border (top/bottom, left/right).
1047
+ pre_transform (Callable | None): Function/transform to apply to the image before starting the random
1048
+ transformation.
1049
+ """
1050
+ self.degrees = degrees
1051
+ self.translate = translate
1052
+ self.scale = scale
1053
+ self.shear = shear
1054
+ self.perspective = perspective
1055
+ self.border = border # mosaic border
1056
+ self.pre_transform = pre_transform
1057
+
1058
+ def affine_transform(self, img: np.ndarray, border: tuple[int, int]) -> tuple[np.ndarray, np.ndarray, float]:
1059
+ """Apply a sequence of affine transformations centered around the image center.
1060
+
1061
+ This function performs a series of geometric transformations on the input image, including translation,
1062
+ perspective change, rotation, scaling, and shearing. The transformations are applied in a specific order to
1063
+ maintain consistency.
1064
+
1065
+ Args:
1066
+ img (np.ndarray): Input image to be transformed.
1067
+ border (tuple[int, int]): Border dimensions for the transformed image.
1068
+
1069
+ Returns:
1070
+ img (np.ndarray): Transformed image.
1071
+ M (np.ndarray): 3x3 transformation matrix.
1072
+ s (float): Scale factor applied during the transformation.
1073
+
1074
+ Examples:
1075
+ >>> import numpy as np
1076
+ >>> img = np.random.rand(100, 100, 3)
1077
+ >>> border = (10, 10)
1078
+ >>> transformed_img, matrix, scale = affine_transform(img, border)
1079
+ """
1080
+ # Center
1081
+ C = np.eye(3, dtype=np.float32)
1082
+
1083
+ C[0, 2] = -img.shape[1] / 2 # x translation (pixels)
1084
+ C[1, 2] = -img.shape[0] / 2 # y translation (pixels)
1085
+
1086
+ # Perspective
1087
+ P = np.eye(3, dtype=np.float32)
1088
+ P[2, 0] = random.uniform(-self.perspective, self.perspective) # x perspective (about y)
1089
+ P[2, 1] = random.uniform(-self.perspective, self.perspective) # y perspective (about x)
1090
+
1091
+ # Rotation and Scale
1092
+ R = np.eye(3, dtype=np.float32)
1093
+ a = random.uniform(-self.degrees, self.degrees)
1094
+ # a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations
1095
+ s = random.uniform(1 - self.scale, 1 + self.scale)
1096
+ # s = 2 ** random.uniform(-scale, scale)
1097
+ R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)
1098
+
1099
+ # Shear
1100
+ S = np.eye(3, dtype=np.float32)
1101
+ S[0, 1] = math.tan(random.uniform(-self.shear, self.shear) * math.pi / 180) # x shear (deg)
1102
+ S[1, 0] = math.tan(random.uniform(-self.shear, self.shear) * math.pi / 180) # y shear (deg)
1103
+
1104
+ # Translation
1105
+ T = np.eye(3, dtype=np.float32)
1106
+ T[0, 2] = random.uniform(0.5 - self.translate, 0.5 + self.translate) * self.size[0] # x translation (pixels)
1107
+ T[1, 2] = random.uniform(0.5 - self.translate, 0.5 + self.translate) * self.size[1] # y translation (pixels)
1108
+
1109
+ # Combined rotation matrix
1110
+ M = T @ S @ R @ P @ C # order of operations (right to left) is IMPORTANT
1111
+ # Affine image
1112
+ if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any(): # image changed
1113
+ if self.perspective:
1114
+ img = cv2.warpPerspective(img, M, dsize=self.size, borderValue=(114, 114, 114))
1115
+ else: # affine
1116
+ img = cv2.warpAffine(img, M[:2], dsize=self.size, borderValue=(114, 114, 114))
1117
+ if img.ndim == 2:
1118
+ img = img[..., None]
1119
+ return img, M, s
1120
+
1121
+ def apply_bboxes(self, bboxes: np.ndarray, M: np.ndarray) -> np.ndarray:
1122
+ """Apply affine transformation to bounding boxes.
1123
+
1124
+ This function applies an affine transformation to a set of bounding boxes using the provided transformation
1125
+ matrix.
1126
+
1127
+ Args:
1128
+ bboxes (np.ndarray): Bounding boxes in xyxy format with shape (N, 4), where N is the number of bounding
1129
+ boxes.
1130
+ M (np.ndarray): Affine transformation matrix with shape (3, 3).
1131
+
1132
+ Returns:
1133
+ (np.ndarray): Transformed bounding boxes in xyxy format with shape (N, 4).
1134
+
1135
+ Examples:
1136
+ >>> bboxes = torch.tensor([[10, 10, 20, 20], [30, 30, 40, 40]])
1137
+ >>> M = torch.eye(3)
1138
+ >>> transformed_bboxes = apply_bboxes(bboxes, M)
1139
+ """
1140
+ n = len(bboxes)
1141
+ if n == 0:
1142
+ return bboxes
1143
+
1144
+ xy = np.ones((n * 4, 3), dtype=bboxes.dtype)
1145
+ xy[:, :2] = bboxes[:, [0, 1, 2, 3, 0, 3, 2, 1]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1
1146
+ xy = xy @ M.T # transform
1147
+ xy = (xy[:, :2] / xy[:, 2:3] if self.perspective else xy[:, :2]).reshape(n, 8) # perspective rescale or affine
1148
+
1149
+ # Create new boxes
1150
+ x = xy[:, [0, 2, 4, 6]]
1151
+ y = xy[:, [1, 3, 5, 7]]
1152
+ return np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1)), dtype=bboxes.dtype).reshape(4, n).T
1153
+
1154
+ def apply_segments(self, segments: np.ndarray, M: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
1155
+ """Apply affine transformations to segments and generate new bounding boxes.
1156
+
1157
+ This function applies affine transformations to input segments and generates new bounding boxes based on the
1158
+ transformed segments. It clips the transformed segments to fit within the new bounding boxes.
1159
+
1160
+ Args:
1161
+ segments (np.ndarray): Input segments with shape (N, M, 2), where N is the number of segments and M is the
1162
+ number of points in each segment.
1163
+ M (np.ndarray): Affine transformation matrix with shape (3, 3).
1164
+
1165
+ Returns:
1166
+ bboxes (np.ndarray): New bounding boxes with shape (N, 4) in xyxy format.
1167
+ segments (np.ndarray): Transformed and clipped segments with shape (N, M, 2).
1168
+
1169
+ Examples:
1170
+ >>> segments = np.random.rand(10, 500, 2) # 10 segments with 500 points each
1171
+ >>> M = np.eye(3) # Identity transformation matrix
1172
+ >>> new_bboxes, new_segments = apply_segments(segments, M)
1173
+ """
1174
+ n, num = segments.shape[:2]
1175
+ if n == 0:
1176
+ return [], segments
1177
+
1178
+ xy = np.ones((n * num, 3), dtype=segments.dtype)
1179
+ segments = segments.reshape(-1, 2)
1180
+ xy[:, :2] = segments
1181
+ xy = xy @ M.T # transform
1182
+ xy = xy[:, :2] / xy[:, 2:3]
1183
+ segments = xy.reshape(n, -1, 2)
1184
+ bboxes = np.stack([segment2box(xy, self.size[0], self.size[1]) for xy in segments], 0)
1185
+ segments[..., 0] = segments[..., 0].clip(bboxes[:, 0:1], bboxes[:, 2:3])
1186
+ segments[..., 1] = segments[..., 1].clip(bboxes[:, 1:2], bboxes[:, 3:4])
1187
+ return bboxes, segments
1188
+
1189
+ def apply_keypoints(self, keypoints: np.ndarray, M: np.ndarray) -> np.ndarray:
1190
+ """Apply affine transformation to keypoints.
1191
+
1192
+ This method transforms the input keypoints using the provided affine transformation matrix. It handles
1193
+ perspective rescaling if necessary and updates the visibility of keypoints that fall outside the image
1194
+ boundaries after transformation.
1195
+
1196
+ Args:
1197
+ keypoints (np.ndarray): Array of keypoints with shape (N, 17, 3), where N is the number of instances, 17 is
1198
+ the number of keypoints per instance, and 3 represents (x, y, visibility).
1199
+ M (np.ndarray): 3x3 affine transformation matrix.
1200
+
1201
+ Returns:
1202
+ (np.ndarray): Transformed keypoints array with the same shape as input (N, 17, 3).
1203
+
1204
+ Examples:
1205
+ >>> random_perspective = RandomPerspective()
1206
+ >>> keypoints = np.random.rand(5, 17, 3) # 5 instances, 17 keypoints each
1207
+ >>> M = np.eye(3) # Identity transformation
1208
+ >>> transformed_keypoints = random_perspective.apply_keypoints(keypoints, M)
1209
+ """
1210
+ n, nkpt = keypoints.shape[:2]
1211
+ if n == 0:
1212
+ return keypoints
1213
+ xy = np.ones((n * nkpt, 3), dtype=keypoints.dtype)
1214
+ visible = keypoints[..., 2].reshape(n * nkpt, 1)
1215
+ xy[:, :2] = keypoints[..., :2].reshape(n * nkpt, 2)
1216
+ xy = xy @ M.T # transform
1217
+ xy = xy[:, :2] / xy[:, 2:3] # perspective rescale or affine
1218
+ out_mask = (xy[:, 0] < 0) | (xy[:, 1] < 0) | (xy[:, 0] > self.size[0]) | (xy[:, 1] > self.size[1])
1219
+ visible[out_mask] = 0
1220
+ return np.concatenate([xy, visible], axis=-1).reshape(n, nkpt, 3)
1221
+
1222
+ def __call__(self, labels: dict[str, Any]) -> dict[str, Any]:
1223
+ """Apply random perspective and affine transformations to an image and its associated labels.
1224
+
1225
+ This method performs a series of transformations including rotation, translation, scaling, shearing, and
1226
+ perspective distortion on the input image and adjusts the corresponding bounding boxes, segments, and keypoints
1227
+ accordingly.
1228
+
1229
+ Args:
1230
+ labels (dict[str, Any]): A dictionary containing image data and annotations.
1231
+
1232
+ Returns:
1233
+ (dict[str, Any]): Transformed labels dictionary containing:
1234
+ - 'img' (np.ndarray): The transformed image.
1235
+ - 'cls' (np.ndarray): Updated class labels.
1236
+ - 'instances' (Instances): Updated object instances.
1237
+ - 'resized_shape' (tuple[int, int]): New image shape after transformation.
1238
+
1239
+ Examples:
1240
+ >>> transform = RandomPerspective()
1241
+ >>> image = np.random.randint(0, 255, (640, 640, 3), dtype=np.uint8)
1242
+ >>> labels = {
1243
+ ... "img": image,
1244
+ ... "cls": np.array([0, 1, 2]),
1245
+ ... "instances": Instances(bboxes=np.array([[10, 10, 50, 50], [100, 100, 150, 150]])),
1246
+ ... }
1247
+ >>> result = transform(labels)
1248
+ >>> assert result["img"].shape[:2] == result["resized_shape"]
1249
+
1250
+ Notes:
1251
+ 'labels' arg must include:
1252
+ - 'img' (np.ndarray): The input image.
1253
+ - 'cls' (np.ndarray): Class labels.
1254
+ - 'instances' (Instances): Object instances with bounding boxes, segments, and keypoints.
1255
+ May include:
1256
+ - 'mosaic_border' (tuple[int, int]): Border size for mosaic augmentation.
1257
+ """
1258
+ if self.pre_transform and "mosaic_border" not in labels:
1259
+ labels = self.pre_transform(labels)
1260
+ labels.pop("ratio_pad", None) # do not need ratio pad
1261
+
1262
+ img = labels["img"]
1263
+ cls = labels["cls"]
1264
+ instances = labels.pop("instances")
1265
+ # Make sure the coord formats are right
1266
+ instances.convert_bbox(format="xyxy")
1267
+ instances.denormalize(*img.shape[:2][::-1])
1268
+
1269
+ border = labels.pop("mosaic_border", self.border)
1270
+ self.size = img.shape[1] + border[1] * 2, img.shape[0] + border[0] * 2 # w, h
1271
+ # M is affine matrix
1272
+ # Scale for func:`box_candidates`
1273
+ img, M, scale = self.affine_transform(img, border)
1274
+
1275
+ bboxes = self.apply_bboxes(instances.bboxes, M)
1276
+
1277
+ segments = instances.segments
1278
+ keypoints = instances.keypoints
1279
+ # Update bboxes if there are segments.
1280
+ if len(segments):
1281
+ bboxes, segments = self.apply_segments(segments, M)
1282
+
1283
+ if keypoints is not None:
1284
+ keypoints = self.apply_keypoints(keypoints, M)
1285
+ new_instances = Instances(bboxes, segments, keypoints, bbox_format="xyxy", normalized=False)
1286
+ # Clip
1287
+ new_instances.clip(*self.size)
1288
+
1289
+ # Filter instances
1290
+ instances.scale(scale_w=scale, scale_h=scale, bbox_only=True)
1291
+ # Make the bboxes have the same scale with new_bboxes
1292
+ i = self.box_candidates(
1293
+ box1=instances.bboxes.T, box2=new_instances.bboxes.T, area_thr=0.01 if len(segments) else 0.10
1294
+ )
1295
+ labels["instances"] = new_instances[i]
1296
+ labels["cls"] = cls[i]
1297
+ labels["img"] = img
1298
+ labels["resized_shape"] = img.shape[:2]
1299
+ return labels
1300
+
1301
+ @staticmethod
1302
+ def box_candidates(
1303
+ box1: np.ndarray,
1304
+ box2: np.ndarray,
1305
+ wh_thr: int = 2,
1306
+ ar_thr: int = 100,
1307
+ area_thr: float = 0.1,
1308
+ eps: float = 1e-16,
1309
+ ) -> np.ndarray:
1310
+ """Compute candidate boxes for further processing based on size and aspect ratio criteria.
1311
+
1312
+ This method compares boxes before and after augmentation to determine if they meet specified thresholds for
1313
+ width, height, aspect ratio, and area. It's used to filter out boxes that have been overly distorted or reduced
1314
+ by the augmentation process.
1315
+
1316
+ Args:
1317
+ box1 (np.ndarray): Original boxes before augmentation, shape (4, N) where n is the number of boxes. Format
1318
+ is [x1, y1, x2, y2] in absolute coordinates.
1319
+ box2 (np.ndarray): Augmented boxes after transformation, shape (4, N). Format is [x1, y1, x2, y2] in
1320
+ absolute coordinates.
1321
+ wh_thr (int): Width and height threshold in pixels. Boxes smaller than this in either dimension are
1322
+ rejected.
1323
+ ar_thr (int): Aspect ratio threshold. Boxes with an aspect ratio greater than this value are rejected.
1324
+ area_thr (float): Area ratio threshold. Boxes with an area ratio (new/old) less than this value are
1325
+ rejected.
1326
+ eps (float): Small epsilon value to prevent division by zero.
1327
+
1328
+ Returns:
1329
+ (np.ndarray): Boolean array of shape (n) indicating which boxes are candidates. True values correspond to
1330
+ boxes that meet all criteria.
1331
+
1332
+ Examples:
1333
+ >>> random_perspective = RandomPerspective()
1334
+ >>> box1 = np.array([[0, 0, 100, 100], [0, 0, 50, 50]]).T
1335
+ >>> box2 = np.array([[10, 10, 90, 90], [5, 5, 45, 45]]).T
1336
+ >>> candidates = random_perspective.box_candidates(box1, box2)
1337
+ >>> print(candidates)
1338
+ [True True]
1339
+ """
1340
+ w1, h1 = box1[2] - box1[0], box1[3] - box1[1]
1341
+ w2, h2 = box2[2] - box2[0], box2[3] - box2[1]
1342
+ ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps)) # aspect ratio
1343
+ return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr) # candidates
1344
+
1345
+
1346
+ class RandomHSV:
1347
+ """Randomly adjust the Hue, Saturation, and Value (HSV) channels of an image.
1348
+
1349
+ This class applies random HSV augmentation to images within predefined limits set by hgain, sgain, and vgain.
1350
+
1351
+ Attributes:
1352
+ hgain (float): Maximum variation for hue. Range is typically [0, 1].
1353
+ sgain (float): Maximum variation for saturation. Range is typically [0, 1].
1354
+ vgain (float): Maximum variation for value. Range is typically [0, 1].
1355
+
1356
+ Methods:
1357
+ __call__: Apply random HSV augmentation to an image.
1358
+
1359
+ Examples:
1360
+ >>> import numpy as np
1361
+ >>> from ultralytics.data.augment import RandomHSV
1362
+ >>> augmenter = RandomHSV(hgain=0.5, sgain=0.5, vgain=0.5)
1363
+ >>> image = np.random.randint(0, 255, (100, 100, 3), dtype=np.uint8)
1364
+ >>> labels = {"img": image}
1365
+ >>> augmenter(labels)
1366
+ >>> augmented_image = augmented_labels["img"]
1367
+ """
1368
+
1369
+ def __init__(self, hgain: float = 0.5, sgain: float = 0.5, vgain: float = 0.5) -> None:
1370
+ """Initialize the RandomHSV object for random HSV (Hue, Saturation, Value) augmentation.
1371
+
1372
+ This class applies random adjustments to the HSV channels of an image within specified limits.
1373
+
1374
+ Args:
1375
+ hgain (float): Maximum variation for hue. Should be in the range [0, 1].
1376
+ sgain (float): Maximum variation for saturation. Should be in the range [0, 1].
1377
+ vgain (float): Maximum variation for value. Should be in the range [0, 1].
1378
+ """
1379
+ self.hgain = hgain
1380
+ self.sgain = sgain
1381
+ self.vgain = vgain
1382
+
1383
+ def __call__(self, labels: dict[str, Any]) -> dict[str, Any]:
1384
+ """Apply random HSV augmentation to an image within predefined limits.
1385
+
1386
+ This method modifies the input image by randomly adjusting its Hue, Saturation, and Value (HSV) channels. The
1387
+ adjustments are made within the limits set by hgain, sgain, and vgain during initialization.
1388
+
1389
+ Args:
1390
+ labels (dict[str, Any]): A dictionary containing image data and metadata. Must include an 'img' key with the
1391
+ image as a numpy array.
1392
+
1393
+ Returns:
1394
+ (dict[str, Any]): A dictionary containing the mixed image and adjusted labels.
1395
+
1396
+ Examples:
1397
+ >>> hsv_augmenter = RandomHSV(hgain=0.5, sgain=0.5, vgain=0.5)
1398
+ >>> labels = {"img": np.random.randint(0, 255, (100, 100, 3), dtype=np.uint8)}
1399
+ >>> labels = hsv_augmenter(labels)
1400
+ >>> augmented_img = labels["img"]
1401
+ """
1402
+ img = labels["img"]
1403
+ if img.shape[-1] != 3: # only apply to RGB images
1404
+ return labels
1405
+ if self.hgain or self.sgain or self.vgain:
1406
+ dtype = img.dtype # uint8
1407
+
1408
+ r = np.random.uniform(-1, 1, 3) * [self.hgain, self.sgain, self.vgain] # random gains
1409
+ x = np.arange(0, 256, dtype=r.dtype)
1410
+ # lut_hue = ((x * (r[0] + 1)) % 180).astype(dtype) # original hue implementation from ultralytics<=8.3.78
1411
+ lut_hue = ((x + r[0] * 180) % 180).astype(dtype)
1412
+ lut_sat = np.clip(x * (r[1] + 1), 0, 255).astype(dtype)
1413
+ lut_val = np.clip(x * (r[2] + 1), 0, 255).astype(dtype)
1414
+ lut_sat[0] = 0 # prevent pure white changing color, introduced in 8.3.79
1415
+
1416
+ hue, sat, val = cv2.split(cv2.cvtColor(img, cv2.COLOR_BGR2HSV))
1417
+ im_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val)))
1418
+ cv2.cvtColor(im_hsv, cv2.COLOR_HSV2BGR, dst=img) # no return needed
1419
+ return labels
1420
+
1421
+
1422
+ class RandomFlip:
1423
+ """Apply a random horizontal or vertical flip to an image with a given probability.
1424
+
1425
+ This class performs random image flipping and updates corresponding instance annotations such as bounding boxes and
1426
+ keypoints.
1427
+
1428
+ Attributes:
1429
+ p (float): Probability of applying the flip. Must be between 0 and 1.
1430
+ direction (str): Direction of flip, either 'horizontal' or 'vertical'.
1431
+ flip_idx (array-like): Index mapping for flipping keypoints, if applicable.
1432
+
1433
+ Methods:
1434
+ __call__: Apply the random flip transformation to an image and its annotations.
1435
+
1436
+ Examples:
1437
+ >>> transform = RandomFlip(p=0.5, direction="horizontal")
1438
+ >>> result = transform({"img": image, "instances": instances})
1439
+ >>> flipped_image = result["img"]
1440
+ >>> flipped_instances = result["instances"]
1441
+ """
1442
+
1443
+ def __init__(self, p: float = 0.5, direction: str = "horizontal", flip_idx: list[int] | None = None) -> None:
1444
+ """Initialize the RandomFlip class with probability and direction.
1445
+
1446
+ This class applies a random horizontal or vertical flip to an image with a given probability. It also updates
1447
+ any instances (bounding boxes, keypoints, etc.) accordingly.
1448
+
1449
+ Args:
1450
+ p (float): The probability of applying the flip. Must be between 0 and 1.
1451
+ direction (str): The direction to apply the flip. Must be 'horizontal' or 'vertical'.
1452
+ flip_idx (list[int] | None): Index mapping for flipping keypoints, if any.
1453
+
1454
+ Raises:
1455
+ AssertionError: If direction is not 'horizontal' or 'vertical', or if p is not between 0 and 1.
1456
+ """
1457
+ assert direction in {"horizontal", "vertical"}, f"Support direction `horizontal` or `vertical`, got {direction}"
1458
+ assert 0 <= p <= 1.0, f"The probability should be in range [0, 1], but got {p}."
1459
+
1460
+ self.p = p
1461
+ self.direction = direction
1462
+ self.flip_idx = flip_idx
1463
+
1464
+ def __call__(self, labels: dict[str, Any]) -> dict[str, Any]:
1465
+ """Apply random flip to an image and update any instances like bounding boxes or keypoints accordingly.
1466
+
1467
+ This method randomly flips the input image either horizontally or vertically based on the initialized
1468
+ probability and direction. It also updates the corresponding instances (bounding boxes, keypoints) to match the
1469
+ flipped image.
1470
+
1471
+ Args:
1472
+ labels (dict[str, Any]): A dictionary containing the following keys:
1473
+ - 'img' (np.ndarray): The image to be flipped.
1474
+ - 'instances' (ultralytics.utils.instance.Instances): Object containing boxes and optionally keypoints.
1475
+
1476
+ Returns:
1477
+ (dict[str, Any]): The same dictionary with the flipped image and updated instances:
1478
+ - 'img' (np.ndarray): The flipped image.
1479
+ - 'instances' (ultralytics.utils.instance.Instances): Updated instances matching the flipped image.
1480
+
1481
+ Examples:
1482
+ >>> labels = {"img": np.random.rand(640, 640, 3), "instances": Instances(...)}
1483
+ >>> random_flip = RandomFlip(p=0.5, direction="horizontal")
1484
+ >>> flipped_labels = random_flip(labels)
1485
+ """
1486
+ img = labels["img"]
1487
+ instances = labels.pop("instances")
1488
+ instances.convert_bbox(format="xywh")
1489
+ h, w = img.shape[:2]
1490
+ h = 1 if instances.normalized else h
1491
+ w = 1 if instances.normalized else w
1492
+
1493
+ # WARNING: two separate if and calls to random.random() intentional for reproducibility with older versions
1494
+ if self.direction == "vertical" and random.random() < self.p:
1495
+ img = np.flipud(img)
1496
+ instances.flipud(h)
1497
+ if self.flip_idx is not None and instances.keypoints is not None:
1498
+ instances.keypoints = np.ascontiguousarray(instances.keypoints[:, self.flip_idx, :])
1499
+ if self.direction == "horizontal" and random.random() < self.p:
1500
+ img = np.fliplr(img)
1501
+ instances.fliplr(w)
1502
+ if self.flip_idx is not None and instances.keypoints is not None:
1503
+ instances.keypoints = np.ascontiguousarray(instances.keypoints[:, self.flip_idx, :])
1504
+ labels["img"] = np.ascontiguousarray(img)
1505
+ labels["instances"] = instances
1506
+ return labels
1507
+
1508
+
1509
+ class LetterBox:
1510
+ """Resize image and padding for detection, instance segmentation, pose.
1511
+
1512
+ This class resizes and pads images to a specified shape while preserving aspect ratio. It also updates corresponding
1513
+ labels and bounding boxes.
1514
+
1515
+ Attributes:
1516
+ new_shape (tuple): Target shape (height, width) for resizing.
1517
+ auto (bool): Whether to use minimum rectangle.
1518
+ scale_fill (bool): Whether to stretch the image to new_shape.
1519
+ scaleup (bool): Whether to allow scaling up. If False, only scale down.
1520
+ stride (int): Stride for rounding padding.
1521
+ center (bool): Whether to center the image or align to top-left.
1522
+
1523
+ Methods:
1524
+ __call__: Resize and pad image, update labels and bounding boxes.
1525
+
1526
+ Examples:
1527
+ >>> transform = LetterBox(new_shape=(640, 640))
1528
+ >>> result = transform(labels)
1529
+ >>> resized_img = result["img"]
1530
+ >>> updated_instances = result["instances"]
1531
+ """
1532
+
1533
+ def __init__(
1534
+ self,
1535
+ new_shape: tuple[int, int] = (640, 640),
1536
+ auto: bool = False,
1537
+ scale_fill: bool = False,
1538
+ scaleup: bool = True,
1539
+ center: bool = True,
1540
+ stride: int = 32,
1541
+ padding_value: int = 114,
1542
+ interpolation: int = cv2.INTER_LINEAR,
1543
+ ):
1544
+ """Initialize LetterBox object for resizing and padding images.
1545
+
1546
+ This class is designed to resize and pad images for object detection, instance segmentation, and pose estimation
1547
+ tasks. It supports various resizing modes including auto-sizing, scale-fill, and letterboxing.
1548
+
1549
+ Args:
1550
+ new_shape (tuple[int, int]): Target size (height, width) for the resized image.
1551
+ auto (bool): If True, use minimum rectangle to resize. If False, use new_shape directly.
1552
+ scale_fill (bool): If True, stretch the image to new_shape without padding.
1553
+ scaleup (bool): If True, allow scaling up. If False, only scale down.
1554
+ center (bool): If True, center the placed image. If False, place image in top-left corner.
1555
+ stride (int): Stride of the model (e.g., 32 for YOLOv5).
1556
+ padding_value (int): Value for padding the image. Default is 114.
1557
+ interpolation (int): Interpolation method for resizing. Default is cv2.INTER_LINEAR.
1558
+ """
1559
+ self.new_shape = new_shape
1560
+ self.auto = auto
1561
+ self.scale_fill = scale_fill
1562
+ self.scaleup = scaleup
1563
+ self.stride = stride
1564
+ self.center = center # Put the image in the middle or top-left
1565
+ self.padding_value = padding_value
1566
+ self.interpolation = interpolation
1567
+
1568
+ def __call__(self, labels: dict[str, Any] | None = None, image: np.ndarray = None) -> dict[str, Any] | np.ndarray:
1569
+ """Resize and pad an image for object detection, instance segmentation, or pose estimation tasks.
1570
+
1571
+ This method applies letterboxing to the input image, which involves resizing the image while maintaining its
1572
+ aspect ratio and adding padding to fit the new shape. It also updates any associated labels accordingly.
1573
+
1574
+ Args:
1575
+ labels (dict[str, Any] | None): A dictionary containing image data and associated labels, or empty dict if
1576
+ None.
1577
+ image (np.ndarray | None): The input image as a numpy array. If None, the image is taken from 'labels'.
1578
+
1579
+ Returns:
1580
+ (dict[str, Any] | np.ndarray): If 'labels' is provided, returns an updated dictionary with the resized and
1581
+ padded image, updated labels, and additional metadata. If 'labels' is empty, returns the resized and
1582
+ padded image only.
1583
+
1584
+ Examples:
1585
+ >>> letterbox = LetterBox(new_shape=(640, 640))
1586
+ >>> result = letterbox(labels={"img": np.zeros((480, 640, 3)), "instances": Instances(...)})
1587
+ >>> resized_img = result["img"]
1588
+ >>> updated_instances = result["instances"]
1589
+ """
1590
+ if labels is None:
1591
+ labels = {}
1592
+ img = labels.get("img") if image is None else image
1593
+ shape = img.shape[:2] # current shape [height, width]
1594
+ new_shape = labels.pop("rect_shape", self.new_shape)
1595
+ if isinstance(new_shape, int):
1596
+ new_shape = (new_shape, new_shape)
1597
+
1598
+ # Scale ratio (new / old)
1599
+ r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
1600
+ if not self.scaleup: # only scale down, do not scale up (for better val mAP)
1601
+ r = min(r, 1.0)
1602
+
1603
+ # Compute padding
1604
+ ratio = r, r # width, height ratios
1605
+ new_unpad = round(shape[1] * r), round(shape[0] * r)
1606
+ dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding
1607
+ if self.auto: # minimum rectangle
1608
+ dw, dh = np.mod(dw, self.stride), np.mod(dh, self.stride) # wh padding
1609
+ elif self.scale_fill: # stretch
1610
+ dw, dh = 0.0, 0.0
1611
+ new_unpad = (new_shape[1], new_shape[0])
1612
+ ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios
1613
+
1614
+ if self.center:
1615
+ dw /= 2 # divide padding into 2 sides
1616
+ dh /= 2
1617
+
1618
+ if shape[::-1] != new_unpad: # resize
1619
+ img = cv2.resize(img, new_unpad, interpolation=self.interpolation)
1620
+ if img.ndim == 2:
1621
+ img = img[..., None]
1622
+
1623
+ top, bottom = round(dh - 0.1) if self.center else 0, round(dh + 0.1)
1624
+ left, right = round(dw - 0.1) if self.center else 0, round(dw + 0.1)
1625
+ h, w, c = img.shape
1626
+ if c == 3:
1627
+ img = cv2.copyMakeBorder(
1628
+ img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=(self.padding_value,) * 3
1629
+ )
1630
+ else: # multispectral
1631
+ pad_img = np.full((h + top + bottom, w + left + right, c), fill_value=self.padding_value, dtype=img.dtype)
1632
+ pad_img[top : top + h, left : left + w] = img
1633
+ img = pad_img
1634
+
1635
+ if labels.get("ratio_pad"):
1636
+ labels["ratio_pad"] = (labels["ratio_pad"], (left, top)) # for evaluation
1637
+
1638
+ if len(labels):
1639
+ labels = self._update_labels(labels, ratio, left, top)
1640
+ labels["img"] = img
1641
+ labels["resized_shape"] = new_shape
1642
+ return labels
1643
+ else:
1644
+ return img
1645
+
1646
+ @staticmethod
1647
+ def _update_labels(labels: dict[str, Any], ratio: tuple[float, float], padw: float, padh: float) -> dict[str, Any]:
1648
+ """Update labels after applying letterboxing to an image.
1649
+
1650
+ This method modifies the bounding box coordinates of instances in the labels to account for resizing and padding
1651
+ applied during letterboxing.
1652
+
1653
+ Args:
1654
+ labels (dict[str, Any]): A dictionary containing image labels and instances.
1655
+ ratio (tuple[float, float]): Scaling ratios (width, height) applied to the image.
1656
+ padw (float): Padding width added to the image.
1657
+ padh (float): Padding height added to the image.
1658
+
1659
+ Returns:
1660
+ (dict[str, Any]): Updated labels dictionary with modified instance coordinates.
1661
+
1662
+ Examples:
1663
+ >>> letterbox = LetterBox(new_shape=(640, 640))
1664
+ >>> labels = {"instances": Instances(...)}
1665
+ >>> ratio = (0.5, 0.5)
1666
+ >>> padw, padh = 10, 20
1667
+ >>> updated_labels = letterbox._update_labels(labels, ratio, padw, padh)
1668
+ """
1669
+ labels["instances"].convert_bbox(format="xyxy")
1670
+ labels["instances"].denormalize(*labels["img"].shape[:2][::-1])
1671
+ labels["instances"].scale(*ratio)
1672
+ labels["instances"].add_padding(padw, padh)
1673
+ return labels
1674
+
1675
+
1676
+ class CopyPaste(BaseMixTransform):
1677
+ """CopyPaste class for applying Copy-Paste augmentation to image datasets.
1678
+
1679
+ This class implements the Copy-Paste augmentation technique as described in the paper "Simple Copy-Paste is a Strong
1680
+ Data Augmentation Method for Instance Segmentation" (https://arxiv.org/abs/2012.07177). It combines objects from
1681
+ different images to create new training samples.
1682
+
1683
+ Attributes:
1684
+ dataset (Any): The dataset to which Copy-Paste augmentation will be applied.
1685
+ pre_transform (Callable | None): Optional transform to apply before Copy-Paste.
1686
+ p (float): Probability of applying Copy-Paste augmentation.
1687
+
1688
+ Methods:
1689
+ _mix_transform: Apply Copy-Paste augmentation to the input labels.
1690
+ __call__: Apply the Copy-Paste transformation to images and annotations.
1691
+
1692
+ Examples:
1693
+ >>> from ultralytics.data.augment import CopyPaste
1694
+ >>> dataset = YourDataset(...) # Your image dataset
1695
+ >>> copypaste = CopyPaste(dataset, p=0.5)
1696
+ >>> augmented_labels = copypaste(original_labels)
1697
+ """
1698
+
1699
+ def __init__(self, dataset=None, pre_transform=None, p: float = 0.5, mode: str = "flip") -> None:
1700
+ """Initialize CopyPaste object with dataset, pre_transform, and probability of applying CopyPaste."""
1701
+ super().__init__(dataset=dataset, pre_transform=pre_transform, p=p)
1702
+ assert mode in {"flip", "mixup"}, f"Expected `mode` to be `flip` or `mixup`, but got {mode}."
1703
+ self.mode = mode
1704
+
1705
+ def _mix_transform(self, labels: dict[str, Any]) -> dict[str, Any]:
1706
+ """Apply Copy-Paste augmentation to combine objects from another image into the current image."""
1707
+ labels2 = labels["mix_labels"][0]
1708
+ return self._transform(labels, labels2)
1709
+
1710
+ def __call__(self, labels: dict[str, Any]) -> dict[str, Any]:
1711
+ """Apply Copy-Paste augmentation to an image and its labels."""
1712
+ if len(labels["instances"].segments) == 0 or self.p == 0:
1713
+ return labels
1714
+ if self.mode == "flip":
1715
+ return self._transform(labels)
1716
+
1717
+ # Get index of one or three other images
1718
+ indexes = self.get_indexes()
1719
+ if isinstance(indexes, int):
1720
+ indexes = [indexes]
1721
+
1722
+ # Get images information will be used for Mosaic or MixUp
1723
+ mix_labels = [self.dataset.get_image_and_label(i) for i in indexes]
1724
+
1725
+ if self.pre_transform is not None:
1726
+ for i, data in enumerate(mix_labels):
1727
+ mix_labels[i] = self.pre_transform(data)
1728
+ labels["mix_labels"] = mix_labels
1729
+
1730
+ # Update cls and texts
1731
+ labels = self._update_label_text(labels)
1732
+ # Mosaic or MixUp
1733
+ labels = self._mix_transform(labels)
1734
+ labels.pop("mix_labels", None)
1735
+ return labels
1736
+
1737
+ def _transform(self, labels1: dict[str, Any], labels2: dict[str, Any] = {}) -> dict[str, Any]:
1738
+ """Apply Copy-Paste augmentation to combine objects from another image into the current image."""
1739
+ im = labels1["img"]
1740
+ if "mosaic_border" not in labels1:
1741
+ im = im.copy() # avoid modifying original non-mosaic image
1742
+ cls = labels1["cls"]
1743
+ h, w = im.shape[:2]
1744
+ instances = labels1.pop("instances")
1745
+ instances.convert_bbox(format="xyxy")
1746
+ instances.denormalize(w, h)
1747
+
1748
+ im_new = np.zeros(im.shape, np.uint8)
1749
+ instances2 = labels2.pop("instances", None)
1750
+ if instances2 is None:
1751
+ instances2 = deepcopy(instances)
1752
+ instances2.fliplr(w)
1753
+ ioa = bbox_ioa(instances2.bboxes, instances.bboxes) # intersection over area, (N, M)
1754
+ indexes = np.nonzero((ioa < 0.30).all(1))[0] # (N, )
1755
+ n = len(indexes)
1756
+ sorted_idx = np.argsort(ioa.max(1)[indexes])
1757
+ indexes = indexes[sorted_idx]
1758
+ for j in indexes[: round(self.p * n)]:
1759
+ cls = np.concatenate((cls, labels2.get("cls", cls)[[j]]), axis=0)
1760
+ instances = Instances.concatenate((instances, instances2[[j]]), axis=0)
1761
+ cv2.drawContours(im_new, instances2.segments[[j]].astype(np.int32), -1, (1, 1, 1), cv2.FILLED)
1762
+
1763
+ result = labels2.get("img", cv2.flip(im, 1)) # augment segments
1764
+ if result.ndim == 2: # cv2.flip would eliminate the last dimension for grayscale images
1765
+ result = result[..., None]
1766
+ i = im_new.astype(bool)
1767
+ im[i] = result[i]
1768
+
1769
+ labels1["img"] = im
1770
+ labels1["cls"] = cls
1771
+ labels1["instances"] = instances
1772
+ return labels1
1773
+
1774
+
1775
+ class Albumentations:
1776
+ """Albumentations transformations for image augmentation.
1777
+
1778
+ This class applies various image transformations using the Albumentations library. It includes operations such as
1779
+ Blur, Median Blur, conversion to grayscale, Contrast Limited Adaptive Histogram Equalization (CLAHE), random changes
1780
+ in brightness and contrast, RandomGamma, and image quality reduction through compression.
1781
+
1782
+ Attributes:
1783
+ p (float): Probability of applying the transformations.
1784
+ transform (albumentations.Compose): Composed Albumentations transforms.
1785
+ contains_spatial (bool): Indicates if the transforms include spatial operations.
1786
+
1787
+ Methods:
1788
+ __call__: Apply the Albumentations transformations to the input labels.
1789
+
1790
+ Examples:
1791
+ >>> transform = Albumentations(p=0.5)
1792
+ >>> augmented_labels = transform(labels)
1793
+
1794
+ Notes:
1795
+ - Requires Albumentations version 1.0.3 or higher.
1796
+ - Spatial transforms are handled differently to ensure bbox compatibility.
1797
+ - Some transforms are applied with very low probability (0.01) by default.
1798
+ """
1799
+
1800
+ def __init__(self, p: float = 1.0, transforms: list | None = None) -> None:
1801
+ """Initialize the Albumentations transform object for YOLO bbox formatted parameters.
1802
+
1803
+ This class applies various image augmentations using the Albumentations library, including Blur, Median Blur,
1804
+ conversion to grayscale, Contrast Limited Adaptive Histogram Equalization, random changes of brightness and
1805
+ contrast, RandomGamma, and image quality reduction through compression.
1806
+
1807
+ Args:
1808
+ p (float): Probability of applying the augmentations. Must be between 0 and 1.
1809
+ transforms (list, optional): List of custom Albumentations transforms. If None, uses default transforms.
1810
+
1811
+ Raises:
1812
+ ImportError: If the Albumentations package is not installed.
1813
+ Exception: For any other errors during initialization.
1814
+ """
1815
+ self.p = p
1816
+ self.transform = None
1817
+ prefix = colorstr("albumentations: ")
1818
+
1819
+ try:
1820
+ import os
1821
+
1822
+ os.environ["NO_ALBUMENTATIONS_UPDATE"] = "1" # suppress Albumentations upgrade message
1823
+ import albumentations as A
1824
+
1825
+ check_version(A.__version__, "1.0.3", hard=True) # version requirement
1826
+
1827
+ # List of possible spatial transforms
1828
+ spatial_transforms = {
1829
+ "Affine",
1830
+ "BBoxSafeRandomCrop",
1831
+ "CenterCrop",
1832
+ "CoarseDropout",
1833
+ "Crop",
1834
+ "CropAndPad",
1835
+ "CropNonEmptyMaskIfExists",
1836
+ "D4",
1837
+ "ElasticTransform",
1838
+ "Flip",
1839
+ "GridDistortion",
1840
+ "GridDropout",
1841
+ "HorizontalFlip",
1842
+ "Lambda",
1843
+ "LongestMaxSize",
1844
+ "MaskDropout",
1845
+ "MixUp",
1846
+ "Morphological",
1847
+ "NoOp",
1848
+ "OpticalDistortion",
1849
+ "PadIfNeeded",
1850
+ "Perspective",
1851
+ "PiecewiseAffine",
1852
+ "PixelDropout",
1853
+ "RandomCrop",
1854
+ "RandomCropFromBorders",
1855
+ "RandomGridShuffle",
1856
+ "RandomResizedCrop",
1857
+ "RandomRotate90",
1858
+ "RandomScale",
1859
+ "RandomSizedBBoxSafeCrop",
1860
+ "RandomSizedCrop",
1861
+ "Resize",
1862
+ "Rotate",
1863
+ "SafeRotate",
1864
+ "ShiftScaleRotate",
1865
+ "SmallestMaxSize",
1866
+ "Transpose",
1867
+ "VerticalFlip",
1868
+ "XYMasking",
1869
+ } # from https://albumentations.ai/docs/getting_started/transforms_and_targets/#spatial-level-transforms
1870
+
1871
+ # Transforms, use custom transforms if provided, otherwise use defaults
1872
+ T = (
1873
+ [
1874
+ A.Blur(p=0.01),
1875
+ A.MedianBlur(p=0.01),
1876
+ A.ToGray(p=0.01),
1877
+ A.CLAHE(p=0.01),
1878
+ A.RandomBrightnessContrast(p=0.0),
1879
+ A.RandomGamma(p=0.0),
1880
+ A.ImageCompression(quality_range=(75, 100), p=0.0),
1881
+ ]
1882
+ if transforms is None
1883
+ else transforms
1884
+ )
1885
+
1886
+ # Compose transforms
1887
+ self.contains_spatial = any(transform.__class__.__name__ in spatial_transforms for transform in T)
1888
+ self.transform = (
1889
+ A.Compose(T, bbox_params=A.BboxParams(format="yolo", label_fields=["class_labels"]))
1890
+ if self.contains_spatial
1891
+ else A.Compose(T)
1892
+ )
1893
+ if hasattr(self.transform, "set_random_seed"):
1894
+ # Required for deterministic transforms in albumentations>=1.4.21
1895
+ self.transform.set_random_seed(torch.initial_seed())
1896
+ LOGGER.info(prefix + ", ".join(f"{x}".replace("always_apply=False, ", "") for x in T if x.p))
1897
+ except ImportError: # package not installed, skip
1898
+ pass
1899
+ except Exception as e:
1900
+ LOGGER.info(f"{prefix}{e}")
1901
+
1902
+ def __call__(self, labels: dict[str, Any]) -> dict[str, Any]:
1903
+ """Apply Albumentations transformations to input labels.
1904
+
1905
+ This method applies a series of image augmentations using the Albumentations library. It can perform both
1906
+ spatial and non-spatial transformations on the input image and its corresponding labels.
1907
+
1908
+ Args:
1909
+ labels (dict[str, Any]): A dictionary containing image data and annotations. Expected keys are:
1910
+ - 'img': np.ndarray representing the image
1911
+ - 'cls': np.ndarray of class labels
1912
+ - 'instances': object containing bounding boxes and other instance information
1913
+
1914
+ Returns:
1915
+ (dict[str, Any]): The input dictionary with augmented image and updated annotations.
1916
+
1917
+ Examples:
1918
+ >>> transform = Albumentations(p=0.5)
1919
+ >>> labels = {
1920
+ ... "img": np.random.rand(640, 640, 3),
1921
+ ... "cls": np.array([0, 1]),
1922
+ ... "instances": Instances(bboxes=np.array([[0, 0, 1, 1], [0.5, 0.5, 0.8, 0.8]])),
1923
+ ... }
1924
+ >>> augmented = transform(labels)
1925
+ >>> assert augmented["img"].shape == (640, 640, 3)
1926
+
1927
+ Notes:
1928
+ - The method applies transformations with probability self.p.
1929
+ - Spatial transforms update bounding boxes, while non-spatial transforms only modify the image.
1930
+ - Requires the Albumentations library to be installed.
1931
+ """
1932
+ if self.transform is None or random.random() > self.p:
1933
+ return labels
1934
+
1935
+ im = labels["img"]
1936
+ if im.shape[2] != 3: # Only apply Albumentation on 3-channel images
1937
+ return labels
1938
+
1939
+ if self.contains_spatial:
1940
+ cls = labels["cls"]
1941
+ if len(cls):
1942
+ labels["instances"].convert_bbox("xywh")
1943
+ labels["instances"].normalize(*im.shape[:2][::-1])
1944
+ bboxes = labels["instances"].bboxes
1945
+ # TODO: add supports of segments and keypoints
1946
+ new = self.transform(image=im, bboxes=bboxes, class_labels=cls) # transformed
1947
+ if len(new["class_labels"]) > 0: # skip update if no bbox in new im
1948
+ labels["img"] = new["image"]
1949
+ labels["cls"] = np.array(new["class_labels"]).reshape(-1, 1)
1950
+ bboxes = np.array(new["bboxes"], dtype=np.float32)
1951
+ labels["instances"].update(bboxes=bboxes)
1952
+ else:
1953
+ labels["img"] = self.transform(image=labels["img"])["image"] # transformed
1954
+
1955
+ return labels
1956
+
1957
+
1958
+ class Format:
1959
+ """A class for formatting image annotations for object detection, instance segmentation, and pose estimation tasks.
1960
+
1961
+ This class standardizes image and instance annotations to be used by the `collate_fn` in PyTorch DataLoader.
1962
+
1963
+ Attributes:
1964
+ bbox_format (str): Format for bounding boxes. Options are 'xywh' or 'xyxy'.
1965
+ normalize (bool): Whether to normalize bounding boxes.
1966
+ return_mask (bool): Whether to return instance masks for segmentation.
1967
+ return_keypoint (bool): Whether to return keypoints for pose estimation.
1968
+ return_obb (bool): Whether to return oriented bounding boxes.
1969
+ mask_ratio (int): Downsample ratio for masks.
1970
+ mask_overlap (bool): Whether to overlap masks.
1971
+ batch_idx (bool): Whether to keep batch indexes.
1972
+ bgr (float): The probability to return BGR images.
1973
+
1974
+ Methods:
1975
+ __call__: Format labels dictionary with image, classes, bounding boxes, and optionally masks and keypoints.
1976
+ _format_img: Convert image from Numpy array to PyTorch tensor.
1977
+ _format_segments: Convert polygon points to bitmap masks.
1978
+
1979
+ Examples:
1980
+ >>> formatter = Format(bbox_format="xywh", normalize=True, return_mask=True)
1981
+ >>> formatted_labels = formatter(labels)
1982
+ >>> img = formatted_labels["img"]
1983
+ >>> bboxes = formatted_labels["bboxes"]
1984
+ >>> masks = formatted_labels["masks"]
1985
+ """
1986
+
1987
+ def __init__(
1988
+ self,
1989
+ bbox_format: str = "xywh",
1990
+ normalize: bool = True,
1991
+ return_mask: bool = False,
1992
+ return_keypoint: bool = False,
1993
+ return_obb: bool = False,
1994
+ mask_ratio: int = 4,
1995
+ mask_overlap: bool = True,
1996
+ batch_idx: bool = True,
1997
+ bgr: float = 0.0,
1998
+ ):
1999
+ """Initialize the Format class with given parameters for image and instance annotation formatting.
2000
+
2001
+ This class standardizes image and instance annotations for object detection, instance segmentation, and pose
2002
+ estimation tasks, preparing them for use in PyTorch DataLoader's `collate_fn`.
2003
+
2004
+ Args:
2005
+ bbox_format (str): Format for bounding boxes. Options are 'xywh', 'xyxy', etc.
2006
+ normalize (bool): Whether to normalize bounding boxes to [0,1].
2007
+ return_mask (bool): If True, returns instance masks for segmentation tasks.
2008
+ return_keypoint (bool): If True, returns keypoints for pose estimation tasks.
2009
+ return_obb (bool): If True, returns oriented bounding boxes.
2010
+ mask_ratio (int): Downsample ratio for masks.
2011
+ mask_overlap (bool): If True, allows mask overlap.
2012
+ batch_idx (bool): If True, keeps batch indexes.
2013
+ bgr (float): Probability of returning BGR images instead of RGB.
2014
+ """
2015
+ self.bbox_format = bbox_format
2016
+ self.normalize = normalize
2017
+ self.return_mask = return_mask # set False when training detection only
2018
+ self.return_keypoint = return_keypoint
2019
+ self.return_obb = return_obb
2020
+ self.mask_ratio = mask_ratio
2021
+ self.mask_overlap = mask_overlap
2022
+ self.batch_idx = batch_idx # keep the batch indexes
2023
+ self.bgr = bgr
2024
+
2025
+ def __call__(self, labels: dict[str, Any]) -> dict[str, Any]:
2026
+ """Format image annotations for object detection, instance segmentation, and pose estimation tasks.
2027
+
2028
+ This method standardizes the image and instance annotations to be used by the `collate_fn` in PyTorch
2029
+ DataLoader. It processes the input labels dictionary, converting annotations to the specified format and
2030
+ applying normalization if required.
2031
+
2032
+ Args:
2033
+ labels (dict[str, Any]): A dictionary containing image and annotation data with the following keys:
2034
+ - 'img': The input image as a numpy array.
2035
+ - 'cls': Class labels for instances.
2036
+ - 'instances': An Instances object containing bounding boxes, segments, and keypoints.
2037
+
2038
+ Returns:
2039
+ (dict[str, Any]): A dictionary with formatted data, including:
2040
+ - 'img': Formatted image tensor.
2041
+ - 'cls': Class label's tensor.
2042
+ - 'bboxes': Bounding boxes tensor in the specified format.
2043
+ - 'masks': Instance masks tensor (if return_mask is True).
2044
+ - 'keypoints': Keypoints tensor (if return_keypoint is True).
2045
+ - 'batch_idx': Batch index tensor (if batch_idx is True).
2046
+
2047
+ Examples:
2048
+ >>> formatter = Format(bbox_format="xywh", normalize=True, return_mask=True)
2049
+ >>> labels = {"img": np.random.rand(640, 640, 3), "cls": np.array([0, 1]), "instances": Instances(...)}
2050
+ >>> formatted_labels = formatter(labels)
2051
+ >>> print(formatted_labels.keys())
2052
+ """
2053
+ img = labels.pop("img")
2054
+ h, w = img.shape[:2]
2055
+ cls = labels.pop("cls")
2056
+ instances = labels.pop("instances")
2057
+ instances.convert_bbox(format=self.bbox_format)
2058
+ instances.denormalize(w, h)
2059
+ nl = len(instances)
2060
+
2061
+ if self.return_mask:
2062
+ if nl:
2063
+ masks, instances, cls = self._format_segments(instances, cls, w, h)
2064
+ masks = torch.from_numpy(masks)
2065
+ else:
2066
+ masks = torch.zeros(
2067
+ 1 if self.mask_overlap else nl, img.shape[0] // self.mask_ratio, img.shape[1] // self.mask_ratio
2068
+ )
2069
+ labels["masks"] = masks
2070
+ labels["img"] = self._format_img(img)
2071
+ labels["cls"] = torch.from_numpy(cls) if nl else torch.zeros(nl, 1)
2072
+ labels["bboxes"] = torch.from_numpy(instances.bboxes) if nl else torch.zeros((nl, 4))
2073
+ if self.return_keypoint:
2074
+ labels["keypoints"] = (
2075
+ torch.empty(0, 3) if instances.keypoints is None else torch.from_numpy(instances.keypoints)
2076
+ )
2077
+ if self.normalize:
2078
+ labels["keypoints"][..., 0] /= w
2079
+ labels["keypoints"][..., 1] /= h
2080
+ if self.return_obb:
2081
+ labels["bboxes"] = (
2082
+ xyxyxyxy2xywhr(torch.from_numpy(instances.segments)) if len(instances.segments) else torch.zeros((0, 5))
2083
+ )
2084
+ # NOTE: need to normalize obb in xywhr format for width-height consistency
2085
+ if self.normalize:
2086
+ labels["bboxes"][:, [0, 2]] /= w
2087
+ labels["bboxes"][:, [1, 3]] /= h
2088
+ # Then we can use collate_fn
2089
+ if self.batch_idx:
2090
+ labels["batch_idx"] = torch.zeros(nl)
2091
+ return labels
2092
+
2093
+ def _format_img(self, img: np.ndarray) -> torch.Tensor:
2094
+ """Format an image for YOLO from a Numpy array to a PyTorch tensor.
2095
+
2096
+ This function performs the following operations:
2097
+ 1. Ensures the image has 3 dimensions (adds a channel dimension if needed).
2098
+ 2. Transposes the image from HWC to CHW format.
2099
+ 3. Optionally flips the color channels from RGB to BGR.
2100
+ 4. Converts the image to a contiguous array.
2101
+ 5. Converts the Numpy array to a PyTorch tensor.
2102
+
2103
+ Args:
2104
+ img (np.ndarray): Input image as a Numpy array with shape (H, W, C) or (H, W).
2105
+
2106
+ Returns:
2107
+ (torch.Tensor): Formatted image as a PyTorch tensor with shape (C, H, W).
2108
+
2109
+ Examples:
2110
+ >>> import numpy as np
2111
+ >>> img = np.random.rand(100, 100, 3)
2112
+ >>> formatted_img = self._format_img(img)
2113
+ >>> print(formatted_img.shape)
2114
+ torch.Size([3, 100, 100])
2115
+ """
2116
+ if len(img.shape) < 3:
2117
+ img = img[..., None]
2118
+ img = img.transpose(2, 0, 1)
2119
+ img = np.ascontiguousarray(img[::-1] if random.uniform(0, 1) > self.bgr and img.shape[0] == 3 else img)
2120
+ img = torch.from_numpy(img)
2121
+ return img
2122
+
2123
+ def _format_segments(
2124
+ self, instances: Instances, cls: np.ndarray, w: int, h: int
2125
+ ) -> tuple[np.ndarray, Instances, np.ndarray]:
2126
+ """Convert polygon segments to bitmap masks.
2127
+
2128
+ Args:
2129
+ instances (Instances): Object containing segment information.
2130
+ cls (np.ndarray): Class labels for each instance.
2131
+ w (int): Width of the image.
2132
+ h (int): Height of the image.
2133
+
2134
+ Returns:
2135
+ masks (np.ndarray): Bitmap masks with shape (N, H, W) or (1, H, W) if mask_overlap is True.
2136
+ instances (Instances): Updated instances object with sorted segments if mask_overlap is True.
2137
+ cls (np.ndarray): Updated class labels, sorted if mask_overlap is True.
2138
+
2139
+ Notes:
2140
+ - If self.mask_overlap is True, masks are overlapped and sorted by area.
2141
+ - If self.mask_overlap is False, each mask is represented separately.
2142
+ - Masks are downsampled according to self.mask_ratio.
2143
+ """
2144
+ segments = instances.segments
2145
+ if self.mask_overlap:
2146
+ masks, sorted_idx = polygons2masks_overlap((h, w), segments, downsample_ratio=self.mask_ratio)
2147
+ masks = masks[None] # (640, 640) -> (1, 640, 640)
2148
+ instances = instances[sorted_idx]
2149
+ cls = cls[sorted_idx]
2150
+ else:
2151
+ masks = polygons2masks((h, w), segments, color=1, downsample_ratio=self.mask_ratio)
2152
+
2153
+ return masks, instances, cls
2154
+
2155
+
2156
+ class LoadVisualPrompt:
2157
+ """Create visual prompts from bounding boxes or masks for model input."""
2158
+
2159
+ def __init__(self, scale_factor: float = 1 / 8) -> None:
2160
+ """Initialize the LoadVisualPrompt with a scale factor.
2161
+
2162
+ Args:
2163
+ scale_factor (float): Factor to scale the input image dimensions.
2164
+ """
2165
+ self.scale_factor = scale_factor
2166
+
2167
+ @staticmethod
2168
+ def make_mask(boxes: torch.Tensor, h: int, w: int) -> torch.Tensor:
2169
+ """Create binary masks from bounding boxes.
2170
+
2171
+ Args:
2172
+ boxes (torch.Tensor): Bounding boxes in xyxy format, shape: (N, 4).
2173
+ h (int): Height of the mask.
2174
+ w (int): Width of the mask.
2175
+
2176
+ Returns:
2177
+ (torch.Tensor): Binary masks with shape (N, h, w).
2178
+ """
2179
+ x1, y1, x2, y2 = torch.chunk(boxes[:, :, None], 4, 1) # x1 shape(n,1,1)
2180
+ r = torch.arange(w)[None, None, :] # rows shape(1,1,w)
2181
+ c = torch.arange(h)[None, :, None] # cols shape(1,h,1)
2182
+
2183
+ return (r >= x1) * (r < x2) * (c >= y1) * (c < y2)
2184
+
2185
+ def __call__(self, labels: dict[str, Any]) -> dict[str, Any]:
2186
+ """Process labels to create visual prompts.
2187
+
2188
+ Args:
2189
+ labels (dict[str, Any]): Dictionary containing image data and annotations.
2190
+
2191
+ Returns:
2192
+ (dict[str, Any]): Updated labels with visual prompts added.
2193
+ """
2194
+ imgsz = labels["img"].shape[1:]
2195
+ bboxes, masks = None, None
2196
+ if "bboxes" in labels:
2197
+ bboxes = labels["bboxes"]
2198
+ bboxes = xywh2xyxy(bboxes) * torch.tensor(imgsz)[[1, 0, 1, 0]] # denormalize boxes
2199
+
2200
+ cls = labels["cls"].squeeze(-1).to(torch.int)
2201
+ visuals = self.get_visuals(cls, imgsz, bboxes=bboxes, masks=masks)
2202
+ labels["visuals"] = visuals
2203
+ return labels
2204
+
2205
+ def get_visuals(
2206
+ self,
2207
+ category: int | np.ndarray | torch.Tensor,
2208
+ shape: tuple[int, int],
2209
+ bboxes: np.ndarray | torch.Tensor = None,
2210
+ masks: np.ndarray | torch.Tensor = None,
2211
+ ) -> torch.Tensor:
2212
+ """Generate visual masks based on bounding boxes or masks.
2213
+
2214
+ Args:
2215
+ category (int | np.ndarray | torch.Tensor): The category labels for the objects.
2216
+ shape (tuple[int, int]): The shape of the image (height, width).
2217
+ bboxes (np.ndarray | torch.Tensor, optional): Bounding boxes for the objects, xyxy format.
2218
+ masks (np.ndarray | torch.Tensor, optional): Masks for the objects.
2219
+
2220
+ Returns:
2221
+ (torch.Tensor): A tensor containing the visual masks for each category.
2222
+
2223
+ Raises:
2224
+ ValueError: If neither bboxes nor masks are provided.
2225
+ """
2226
+ masksz = (int(shape[0] * self.scale_factor), int(shape[1] * self.scale_factor))
2227
+ if bboxes is not None:
2228
+ if isinstance(bboxes, np.ndarray):
2229
+ bboxes = torch.from_numpy(bboxes)
2230
+ bboxes *= self.scale_factor
2231
+ masks = self.make_mask(bboxes, *masksz).float()
2232
+ elif masks is not None:
2233
+ if isinstance(masks, np.ndarray):
2234
+ masks = torch.from_numpy(masks) # (N, H, W)
2235
+ masks = F.interpolate(masks.unsqueeze(1), masksz, mode="nearest").squeeze(1).float()
2236
+ else:
2237
+ raise ValueError("LoadVisualPrompt must have bboxes or masks in the label")
2238
+ if not isinstance(category, torch.Tensor):
2239
+ category = torch.tensor(category, dtype=torch.int)
2240
+ cls_unique, inverse_indices = torch.unique(category, sorted=True, return_inverse=True)
2241
+ # NOTE: `cls` indices from RandomLoadText should be continuous.
2242
+ # if len(cls_unique):
2243
+ # assert len(cls_unique) == cls_unique[-1] + 1, (
2244
+ # f"Expected a continuous range of class indices, but got {cls_unique}"
2245
+ # )
2246
+ visuals = torch.zeros(cls_unique.shape[0], *masksz)
2247
+ for idx, mask in zip(inverse_indices, masks):
2248
+ visuals[idx] = torch.logical_or(visuals[idx], mask)
2249
+ return visuals
2250
+
2251
+
2252
+ class RandomLoadText:
2253
+ """Randomly sample positive and negative texts and update class indices accordingly.
2254
+
2255
+ This class is responsible for sampling texts from a given set of class texts, including both positive (present in
2256
+ the image) and negative (not present in the image) samples. It updates the class indices to reflect the sampled
2257
+ texts and can optionally pad the text list to a fixed length.
2258
+
2259
+ Attributes:
2260
+ prompt_format (str): Format string for text prompts.
2261
+ neg_samples (tuple[int, int]): Range for randomly sampling negative texts.
2262
+ max_samples (int): Maximum number of different text samples in one image.
2263
+ padding (bool): Whether to pad texts to max_samples.
2264
+ padding_value (str): The text used for padding when padding is True.
2265
+
2266
+ Methods:
2267
+ __call__: Process the input labels and return updated classes and texts.
2268
+
2269
+ Examples:
2270
+ >>> loader = RandomLoadText(prompt_format="Object: {}", neg_samples=(5, 10), max_samples=20)
2271
+ >>> labels = {"cls": [0, 1, 2], "texts": [["cat"], ["dog"], ["bird"]], "instances": [...]}
2272
+ >>> updated_labels = loader(labels)
2273
+ >>> print(updated_labels["texts"])
2274
+ ['Object: cat', 'Object: dog', 'Object: bird', 'Object: elephant', 'Object: car']
2275
+ """
2276
+
2277
+ def __init__(
2278
+ self,
2279
+ prompt_format: str = "{}",
2280
+ neg_samples: tuple[int, int] = (80, 80),
2281
+ max_samples: int = 80,
2282
+ padding: bool = False,
2283
+ padding_value: list[str] = [""],
2284
+ ) -> None:
2285
+ """Initialize the RandomLoadText class for randomly sampling positive and negative texts.
2286
+
2287
+ This class is designed to randomly sample positive texts and negative texts, and update the class indices
2288
+ accordingly to the number of samples. It can be used for text-based object detection tasks.
2289
+
2290
+ Args:
2291
+ prompt_format (str): Format string for the prompt. The format string should contain a single pair of curly
2292
+ braces {} where the text will be inserted.
2293
+ neg_samples (tuple[int, int]): A range to randomly sample negative texts. The first integer specifies the
2294
+ minimum number of negative samples, and the second integer specifies the maximum.
2295
+ max_samples (int): The maximum number of different text samples in one image.
2296
+ padding (bool): Whether to pad texts to max_samples. If True, the number of texts will always be equal to
2297
+ max_samples.
2298
+ padding_value (str): The padding text to use when padding is True.
2299
+ """
2300
+ self.prompt_format = prompt_format
2301
+ self.neg_samples = neg_samples
2302
+ self.max_samples = max_samples
2303
+ self.padding = padding
2304
+ self.padding_value = padding_value
2305
+
2306
+ def __call__(self, labels: dict[str, Any]) -> dict[str, Any]:
2307
+ """Randomly sample positive and negative texts and update class indices accordingly.
2308
+
2309
+ This method samples positive texts based on the existing class labels in the image, and randomly selects
2310
+ negative texts from the remaining classes. It then updates the class indices to match the new sampled text
2311
+ order.
2312
+
2313
+ Args:
2314
+ labels (dict[str, Any]): A dictionary containing image labels and metadata. Must include 'texts' and 'cls'
2315
+ keys.
2316
+
2317
+ Returns:
2318
+ (dict[str, Any]): Updated labels dictionary with new 'cls' and 'texts' entries.
2319
+
2320
+ Examples:
2321
+ >>> loader = RandomLoadText(prompt_format="A photo of {}", neg_samples=(5, 10), max_samples=20)
2322
+ >>> labels = {"cls": np.array([[0], [1], [2]]), "texts": [["dog"], ["cat"], ["bird"]]}
2323
+ >>> updated_labels = loader(labels)
2324
+ """
2325
+ assert "texts" in labels, "No texts found in labels."
2326
+ class_texts = labels["texts"]
2327
+ num_classes = len(class_texts)
2328
+ cls = np.asarray(labels.pop("cls"), dtype=int)
2329
+ pos_labels = np.unique(cls).tolist()
2330
+
2331
+ if len(pos_labels) > self.max_samples:
2332
+ pos_labels = random.sample(pos_labels, k=self.max_samples)
2333
+
2334
+ neg_samples = min(min(num_classes, self.max_samples) - len(pos_labels), random.randint(*self.neg_samples))
2335
+ neg_labels = [i for i in range(num_classes) if i not in pos_labels]
2336
+ neg_labels = random.sample(neg_labels, k=neg_samples)
2337
+
2338
+ sampled_labels = pos_labels + neg_labels
2339
+ # Randomness
2340
+ # random.shuffle(sampled_labels)
2341
+
2342
+ label2ids = {label: i for i, label in enumerate(sampled_labels)}
2343
+ valid_idx = np.zeros(len(labels["instances"]), dtype=bool)
2344
+ new_cls = []
2345
+ for i, label in enumerate(cls.squeeze(-1).tolist()):
2346
+ if label not in label2ids:
2347
+ continue
2348
+ valid_idx[i] = True
2349
+ new_cls.append([label2ids[label]])
2350
+ labels["instances"] = labels["instances"][valid_idx]
2351
+ labels["cls"] = np.array(new_cls)
2352
+
2353
+ # Randomly select one prompt when there's more than one prompts
2354
+ texts = []
2355
+ for label in sampled_labels:
2356
+ prompts = class_texts[label]
2357
+ assert len(prompts) > 0
2358
+ prompt = self.prompt_format.format(prompts[random.randrange(len(prompts))])
2359
+ texts.append(prompt)
2360
+
2361
+ if self.padding:
2362
+ valid_labels = len(pos_labels) + len(neg_labels)
2363
+ num_padding = self.max_samples - valid_labels
2364
+ if num_padding > 0:
2365
+ texts += random.choices(self.padding_value, k=num_padding)
2366
+
2367
+ assert len(texts) == self.max_samples
2368
+ labels["texts"] = texts
2369
+ return labels
2370
+
2371
+
2372
+ def v8_transforms(dataset, imgsz: int, hyp: IterableSimpleNamespace, stretch: bool = False):
2373
+ """Apply a series of image transformations for training.
2374
+
2375
+ This function creates a composition of image augmentation techniques to prepare images for YOLO training. It
2376
+ includes operations such as mosaic, copy-paste, random perspective, mixup, and various color adjustments.
2377
+
2378
+ Args:
2379
+ dataset (Dataset): The dataset object containing image data and annotations.
2380
+ imgsz (int): The target image size for resizing.
2381
+ hyp (IterableSimpleNamespace): A dictionary of hyperparameters controlling various aspects of the
2382
+ transformations.
2383
+ stretch (bool): If True, applies stretching to the image. If False, uses LetterBox resizing.
2384
+
2385
+ Returns:
2386
+ (Compose): A composition of image transformations to be applied to the dataset.
2387
+
2388
+ Examples:
2389
+ >>> from ultralytics.data.dataset import YOLODataset
2390
+ >>> from ultralytics.utils import IterableSimpleNamespace
2391
+ >>> dataset = YOLODataset(img_path="path/to/images", imgsz=640)
2392
+ >>> hyp = IterableSimpleNamespace(mosaic=1.0, copy_paste=0.5, degrees=10.0, translate=0.2, scale=0.9)
2393
+ >>> transforms = v8_transforms(dataset, imgsz=640, hyp=hyp)
2394
+ >>> augmented_data = transforms(dataset[0])
2395
+
2396
+ >>> # With custom albumentations
2397
+ >>> import albumentations as A
2398
+ >>> augmentations = [A.Blur(p=0.01), A.CLAHE(p=0.01)]
2399
+ >>> hyp.augmentations = augmentations
2400
+ >>> transforms = v8_transforms(dataset, imgsz=640, hyp=hyp)
2401
+ """
2402
+ mosaic = Mosaic(dataset, imgsz=imgsz, p=hyp.mosaic)
2403
+ affine = RandomPerspective(
2404
+ degrees=hyp.degrees,
2405
+ translate=hyp.translate,
2406
+ scale=hyp.scale,
2407
+ shear=hyp.shear,
2408
+ perspective=hyp.perspective,
2409
+ pre_transform=None if stretch else LetterBox(new_shape=(imgsz, imgsz)),
2410
+ )
2411
+
2412
+ pre_transform = Compose([mosaic, affine])
2413
+ if hyp.copy_paste_mode == "flip":
2414
+ pre_transform.insert(1, CopyPaste(p=hyp.copy_paste, mode=hyp.copy_paste_mode))
2415
+ else:
2416
+ pre_transform.append(
2417
+ CopyPaste(
2418
+ dataset,
2419
+ pre_transform=Compose([Mosaic(dataset, imgsz=imgsz, p=hyp.mosaic), affine]),
2420
+ p=hyp.copy_paste,
2421
+ mode=hyp.copy_paste_mode,
2422
+ )
2423
+ )
2424
+ flip_idx = dataset.data.get("flip_idx", []) # for keypoints augmentation
2425
+ if dataset.use_keypoints:
2426
+ kpt_shape = dataset.data.get("kpt_shape", None)
2427
+ if len(flip_idx) == 0 and (hyp.fliplr > 0.0 or hyp.flipud > 0.0):
2428
+ hyp.fliplr = hyp.flipud = 0.0 # both fliplr and flipud require flip_idx
2429
+ LOGGER.warning("No 'flip_idx' array defined in data.yaml, disabling 'fliplr' and 'flipud' augmentations.")
2430
+ elif flip_idx and (len(flip_idx) != kpt_shape[0]):
2431
+ raise ValueError(f"data.yaml flip_idx={flip_idx} length must be equal to kpt_shape[0]={kpt_shape[0]}")
2432
+
2433
+ return Compose(
2434
+ [
2435
+ pre_transform,
2436
+ MixUp(dataset, pre_transform=pre_transform, p=hyp.mixup),
2437
+ CutMix(dataset, pre_transform=pre_transform, p=hyp.cutmix),
2438
+ Albumentations(p=1.0, transforms=getattr(hyp, "augmentations", None)),
2439
+ RandomHSV(hgain=hyp.hsv_h, sgain=hyp.hsv_s, vgain=hyp.hsv_v),
2440
+ RandomFlip(direction="vertical", p=hyp.flipud, flip_idx=flip_idx),
2441
+ RandomFlip(direction="horizontal", p=hyp.fliplr, flip_idx=flip_idx),
2442
+ ]
2443
+ ) # transforms
2444
+
2445
+
2446
+ # Classification augmentations -----------------------------------------------------------------------------------------
2447
+ def classify_transforms(
2448
+ size: tuple[int, int] | int = 224,
2449
+ mean: tuple[float, float, float] = DEFAULT_MEAN,
2450
+ std: tuple[float, float, float] = DEFAULT_STD,
2451
+ interpolation: str = "BILINEAR",
2452
+ crop_fraction: float | None = None,
2453
+ ):
2454
+ """Create a composition of image transforms for classification tasks.
2455
+
2456
+ This function generates a sequence of torchvision transforms suitable for preprocessing images for classification
2457
+ models during evaluation or inference. The transforms include resizing, center cropping, conversion to tensor, and
2458
+ normalization.
2459
+
2460
+ Args:
2461
+ size (int | tuple): The target size for the transformed image. If an int, it defines the shortest edge. If a
2462
+ tuple, it defines (height, width).
2463
+ mean (tuple[float, float, float]): Mean values for each RGB channel used in normalization.
2464
+ std (tuple[float, float, float]): Standard deviation values for each RGB channel used in normalization.
2465
+ interpolation (str): Interpolation method of either 'NEAREST', 'BILINEAR' or 'BICUBIC'.
2466
+ crop_fraction (float): Deprecated, will be removed in a future version.
2467
+
2468
+ Returns:
2469
+ (torchvision.transforms.Compose): A composition of torchvision transforms.
2470
+
2471
+ Examples:
2472
+ >>> transforms = classify_transforms(size=224)
2473
+ >>> img = Image.open("path/to/image.jpg")
2474
+ >>> transformed_img = transforms(img)
2475
+ """
2476
+ import torchvision.transforms as T # scope for faster 'import ultralytics'
2477
+
2478
+ scale_size = size if isinstance(size, (tuple, list)) and len(size) == 2 else (size, size)
2479
+
2480
+ if crop_fraction:
2481
+ raise DeprecationWarning(
2482
+ "'crop_fraction' arg of classify_transforms is deprecated, will be removed in a future version."
2483
+ )
2484
+
2485
+ # Aspect ratio is preserved, crops center within image, no borders are added, image is lost
2486
+ if scale_size[0] == scale_size[1]:
2487
+ # Simple case, use torchvision built-in Resize with the shortest edge mode (scalar size arg)
2488
+ tfl = [T.Resize(scale_size[0], interpolation=getattr(T.InterpolationMode, interpolation))]
2489
+ else:
2490
+ # Resize the shortest edge to matching target dim for non-square target
2491
+ tfl = [T.Resize(scale_size)]
2492
+ tfl += [T.CenterCrop(size), T.ToTensor(), T.Normalize(mean=torch.tensor(mean), std=torch.tensor(std))]
2493
+ return T.Compose(tfl)
2494
+
2495
+
2496
+ # Classification training augmentations --------------------------------------------------------------------------------
2497
+ def classify_augmentations(
2498
+ size: int = 224,
2499
+ mean: tuple[float, float, float] = DEFAULT_MEAN,
2500
+ std: tuple[float, float, float] = DEFAULT_STD,
2501
+ scale: tuple[float, float] | None = None,
2502
+ ratio: tuple[float, float] | None = None,
2503
+ hflip: float = 0.5,
2504
+ vflip: float = 0.0,
2505
+ auto_augment: str | None = None,
2506
+ hsv_h: float = 0.015, # image HSV-Hue augmentation (fraction)
2507
+ hsv_s: float = 0.4, # image HSV-Saturation augmentation (fraction)
2508
+ hsv_v: float = 0.4, # image HSV-Value augmentation (fraction)
2509
+ force_color_jitter: bool = False,
2510
+ erasing: float = 0.0,
2511
+ interpolation: str = "BILINEAR",
2512
+ ):
2513
+ """Create a composition of image augmentation transforms for classification tasks.
2514
+
2515
+ This function generates a set of image transformations suitable for training classification models. It includes
2516
+ options for resizing, flipping, color jittering, auto augmentation, and random erasing.
2517
+
2518
+ Args:
2519
+ size (int): Target size for the image after transformations.
2520
+ mean (tuple[float, float, float]): Mean values for each RGB channel used in normalization.
2521
+ std (tuple[float, float, float]): Standard deviation values for each RGB channel used in normalization.
2522
+ scale (tuple[float, float] | None): Range of size of the origin size cropped.
2523
+ ratio (tuple[float, float] | None): Range of aspect ratio of the origin aspect ratio cropped.
2524
+ hflip (float): Probability of horizontal flip.
2525
+ vflip (float): Probability of vertical flip.
2526
+ auto_augment (str | None): Auto augmentation policy. Can be 'randaugment', 'augmix', 'autoaugment' or None.
2527
+ hsv_h (float): Image HSV-Hue augmentation factor.
2528
+ hsv_s (float): Image HSV-Saturation augmentation factor.
2529
+ hsv_v (float): Image HSV-Value augmentation factor.
2530
+ force_color_jitter (bool): Whether to apply color jitter even if auto augment is enabled.
2531
+ erasing (float): Probability of random erasing.
2532
+ interpolation (str): Interpolation method of either 'NEAREST', 'BILINEAR' or 'BICUBIC'.
2533
+
2534
+ Returns:
2535
+ (torchvision.transforms.Compose): A composition of image augmentation transforms.
2536
+
2537
+ Examples:
2538
+ >>> transforms = classify_augmentations(size=224, auto_augment="randaugment")
2539
+ >>> augmented_image = transforms(original_image)
2540
+ """
2541
+ # Transforms to apply if Albumentations not installed
2542
+ import torchvision.transforms as T # scope for faster 'import ultralytics'
2543
+
2544
+ if not isinstance(size, int):
2545
+ raise TypeError(f"classify_augmentations() size {size} must be integer, not (list, tuple)")
2546
+ scale = tuple(scale or (0.08, 1.0)) # default imagenet scale range
2547
+ ratio = tuple(ratio or (3.0 / 4.0, 4.0 / 3.0)) # default imagenet ratio range
2548
+ interpolation = getattr(T.InterpolationMode, interpolation)
2549
+ primary_tfl = [T.RandomResizedCrop(size, scale=scale, ratio=ratio, interpolation=interpolation)]
2550
+ if hflip > 0.0:
2551
+ primary_tfl.append(T.RandomHorizontalFlip(p=hflip))
2552
+ if vflip > 0.0:
2553
+ primary_tfl.append(T.RandomVerticalFlip(p=vflip))
2554
+
2555
+ secondary_tfl = []
2556
+ disable_color_jitter = False
2557
+ if auto_augment:
2558
+ assert isinstance(auto_augment, str), f"Provided argument should be string, but got type {type(auto_augment)}"
2559
+ # color jitter is typically disabled if AA/RA on,
2560
+ # this allows override without breaking old hparm cfgs
2561
+ disable_color_jitter = not force_color_jitter
2562
+
2563
+ if auto_augment == "randaugment":
2564
+ if TORCHVISION_0_11:
2565
+ secondary_tfl.append(T.RandAugment(interpolation=interpolation))
2566
+ else:
2567
+ LOGGER.warning('"auto_augment=randaugment" requires torchvision >= 0.11.0. Disabling it.')
2568
+
2569
+ elif auto_augment == "augmix":
2570
+ if TORCHVISION_0_13:
2571
+ secondary_tfl.append(T.AugMix(interpolation=interpolation))
2572
+ else:
2573
+ LOGGER.warning('"auto_augment=augmix" requires torchvision >= 0.13.0. Disabling it.')
2574
+
2575
+ elif auto_augment == "autoaugment":
2576
+ if TORCHVISION_0_10:
2577
+ secondary_tfl.append(T.AutoAugment(interpolation=interpolation))
2578
+ else:
2579
+ LOGGER.warning('"auto_augment=autoaugment" requires torchvision >= 0.10.0. Disabling it.')
2580
+
2581
+ else:
2582
+ raise ValueError(
2583
+ f'Invalid auto_augment policy: {auto_augment}. Should be one of "randaugment", '
2584
+ f'"augmix", "autoaugment" or None'
2585
+ )
2586
+
2587
+ if not disable_color_jitter:
2588
+ secondary_tfl.append(T.ColorJitter(brightness=hsv_v, contrast=hsv_v, saturation=hsv_s, hue=hsv_h))
2589
+
2590
+ final_tfl = [
2591
+ T.ToTensor(),
2592
+ T.Normalize(mean=torch.tensor(mean), std=torch.tensor(std)),
2593
+ T.RandomErasing(p=erasing, inplace=True),
2594
+ ]
2595
+
2596
+ return T.Compose(primary_tfl + secondary_tfl + final_tfl)
2597
+
2598
+
2599
+ # NOTE: keep this class for backward compatibility
2600
+ class ClassifyLetterBox:
2601
+ """A class for resizing and padding images for classification tasks.
2602
+
2603
+ This class is designed to be part of a transformation pipeline, e.g., T.Compose([LetterBox(size), ToTensor()]). It
2604
+ resizes and pads images to a specified size while maintaining the original aspect ratio.
2605
+
2606
+ Attributes:
2607
+ h (int): Target height of the image.
2608
+ w (int): Target width of the image.
2609
+ auto (bool): If True, automatically calculates the short side using stride.
2610
+ stride (int): The stride value, used when 'auto' is True.
2611
+
2612
+ Methods:
2613
+ __call__: Apply the letterbox transformation to an input image.
2614
+
2615
+ Examples:
2616
+ >>> transform = ClassifyLetterBox(size=(640, 640), auto=False, stride=32)
2617
+ >>> img = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8)
2618
+ >>> result = transform(img)
2619
+ >>> print(result.shape)
2620
+ (640, 640, 3)
2621
+ """
2622
+
2623
+ def __init__(self, size: int | tuple[int, int] = (640, 640), auto: bool = False, stride: int = 32):
2624
+ """Initialize the ClassifyLetterBox object for image preprocessing.
2625
+
2626
+ This class is designed to be part of a transformation pipeline for image classification tasks. It resizes and
2627
+ pads images to a specified size while maintaining the original aspect ratio.
2628
+
2629
+ Args:
2630
+ size (int | tuple[int, int]): Target size for the letterboxed image. If an int, a square image of (size,
2631
+ size) is created. If a tuple, it should be (height, width).
2632
+ auto (bool): If True, automatically calculates the short side based on stride.
2633
+ stride (int): The stride value, used when 'auto' is True.
2634
+ """
2635
+ super().__init__()
2636
+ self.h, self.w = (size, size) if isinstance(size, int) else size
2637
+ self.auto = auto # pass max size integer, automatically solve for short side using stride
2638
+ self.stride = stride # used with auto
2639
+
2640
+ def __call__(self, im: np.ndarray) -> np.ndarray:
2641
+ """Resize and pad an image using the letterbox method.
2642
+
2643
+ This method resizes the input image to fit within the specified dimensions while maintaining its aspect ratio,
2644
+ then pads the resized image to match the target size.
2645
+
2646
+ Args:
2647
+ im (np.ndarray): Input image as a numpy array with shape (H, W, C).
2648
+
2649
+ Returns:
2650
+ (np.ndarray): Resized and padded image as a numpy array with shape (hs, ws, 3), where hs and ws are the
2651
+ target height and width respectively.
2652
+
2653
+ Examples:
2654
+ >>> letterbox = ClassifyLetterBox(size=(640, 640))
2655
+ >>> image = np.random.randint(0, 255, (720, 1280, 3), dtype=np.uint8)
2656
+ >>> resized_image = letterbox(image)
2657
+ >>> print(resized_image.shape)
2658
+ (640, 640, 3)
2659
+ """
2660
+ imh, imw = im.shape[:2]
2661
+ r = min(self.h / imh, self.w / imw) # ratio of new/old dimensions
2662
+ h, w = round(imh * r), round(imw * r) # resized image dimensions
2663
+
2664
+ # Calculate padding dimensions
2665
+ hs, ws = (math.ceil(x / self.stride) * self.stride for x in (h, w)) if self.auto else (self.h, self.w)
2666
+ top, left = round((hs - h) / 2 - 0.1), round((ws - w) / 2 - 0.1)
2667
+
2668
+ # Create padded image
2669
+ im_out = np.full((hs, ws, 3), 114, dtype=im.dtype)
2670
+ im_out[top : top + h, left : left + w] = cv2.resize(im, (w, h), interpolation=cv2.INTER_LINEAR)
2671
+ return im_out
2672
+
2673
+
2674
+ # NOTE: keep this class for backward compatibility
2675
+ class CenterCrop:
2676
+ """Apply center cropping to images for classification tasks.
2677
+
2678
+ This class performs center cropping on input images, resizing them to a specified size while maintaining the aspect
2679
+ ratio. It is designed to be part of a transformation pipeline, e.g., T.Compose([CenterCrop(size), ToTensor()]).
2680
+
2681
+ Attributes:
2682
+ h (int): Target height of the cropped image.
2683
+ w (int): Target width of the cropped image.
2684
+
2685
+ Methods:
2686
+ __call__: Apply the center crop transformation to an input image.
2687
+
2688
+ Examples:
2689
+ >>> transform = CenterCrop(640)
2690
+ >>> image = np.random.randint(0, 255, (1080, 1920, 3), dtype=np.uint8)
2691
+ >>> cropped_image = transform(image)
2692
+ >>> print(cropped_image.shape)
2693
+ (640, 640, 3)
2694
+ """
2695
+
2696
+ def __init__(self, size: int | tuple[int, int] = (640, 640)):
2697
+ """Initialize the CenterCrop object for image preprocessing.
2698
+
2699
+ This class is designed to be part of a transformation pipeline, e.g., T.Compose([CenterCrop(size), ToTensor()]).
2700
+ It performs a center crop on input images to a specified size.
2701
+
2702
+ Args:
2703
+ size (int | tuple[int, int]): The desired output size of the crop. If size is an int, a square crop (size,
2704
+ size) is made. If size is a sequence like (h, w), it is used as the output size.
2705
+
2706
+ Returns:
2707
+ (None): This method initializes the object and does not return anything.
2708
+ """
2709
+ super().__init__()
2710
+ self.h, self.w = (size, size) if isinstance(size, int) else size
2711
+
2712
+ def __call__(self, im: Image.Image | np.ndarray) -> np.ndarray:
2713
+ """Apply center cropping to an input image.
2714
+
2715
+ This method resizes and crops the center of the image using a letterbox method. It maintains the aspect ratio of
2716
+ the original image while fitting it into the specified dimensions.
2717
+
2718
+ Args:
2719
+ im (np.ndarray | PIL.Image.Image): The input image as a numpy array of shape (H, W, C) or a PIL Image
2720
+ object.
2721
+
2722
+ Returns:
2723
+ (np.ndarray): The center-cropped and resized image as a numpy array of shape (self.h, self.w, C).
2724
+
2725
+ Examples:
2726
+ >>> transform = CenterCrop(size=224)
2727
+ >>> image = np.random.randint(0, 255, (640, 480, 3), dtype=np.uint8)
2728
+ >>> cropped_image = transform(image)
2729
+ >>> assert cropped_image.shape == (224, 224, 3)
2730
+ """
2731
+ if isinstance(im, Image.Image): # convert from PIL to numpy array if required
2732
+ im = np.asarray(im)
2733
+ imh, imw = im.shape[:2]
2734
+ m = min(imh, imw) # min dimension
2735
+ top, left = (imh - m) // 2, (imw - m) // 2
2736
+ return cv2.resize(im[top : top + m, left : left + m], (self.w, self.h), interpolation=cv2.INTER_LINEAR)
2737
+
2738
+
2739
+ # NOTE: keep this class for backward compatibility
2740
+ class ToTensor:
2741
+ """Convert an image from a numpy array to a PyTorch tensor.
2742
+
2743
+ This class is designed to be part of a transformation pipeline, e.g., T.Compose([LetterBox(size), ToTensor()]).
2744
+
2745
+ Attributes:
2746
+ half (bool): If True, converts the image to half precision (float16).
2747
+
2748
+ Methods:
2749
+ __call__: Apply the tensor conversion to an input image.
2750
+
2751
+ Examples:
2752
+ >>> transform = ToTensor(half=True)
2753
+ >>> img = np.random.randint(0, 255, (640, 640, 3), dtype=np.uint8)
2754
+ >>> tensor_img = transform(img)
2755
+ >>> print(tensor_img.shape, tensor_img.dtype)
2756
+ torch.Size([3, 640, 640]) torch.float16
2757
+
2758
+ Notes:
2759
+ The input image is expected to be in BGR format with shape (H, W, C).
2760
+ The output tensor will be in RGB format with shape (C, H, W), normalized to [0, 1].
2761
+ """
2762
+
2763
+ def __init__(self, half: bool = False):
2764
+ """Initialize the ToTensor object for converting images to PyTorch tensors.
2765
+
2766
+ This class is designed to be used as part of a transformation pipeline for image preprocessing in the
2767
+ Ultralytics YOLO framework. It converts numpy arrays or PIL Images to PyTorch tensors, with an option for
2768
+ half-precision (float16) conversion.
2769
+
2770
+ Args:
2771
+ half (bool): If True, converts the tensor to half precision (float16).
2772
+ """
2773
+ super().__init__()
2774
+ self.half = half
2775
+
2776
+ def __call__(self, im: np.ndarray) -> torch.Tensor:
2777
+ """Transform an image from a numpy array to a PyTorch tensor.
2778
+
2779
+ This method converts the input image from a numpy array to a PyTorch tensor, applying optional half-precision
2780
+ conversion and normalization. The image is transposed from HWC to CHW format and the color channels are reversed
2781
+ from BGR to RGB.
2782
+
2783
+ Args:
2784
+ im (np.ndarray): Input image as a numpy array with shape (H, W, C) in RGB order.
2785
+
2786
+ Returns:
2787
+ (torch.Tensor): The transformed image as a PyTorch tensor in float32 or float16, normalized to [0, 1] with
2788
+ shape (C, H, W) in RGB order.
2789
+
2790
+ Examples:
2791
+ >>> transform = ToTensor(half=True)
2792
+ >>> img = np.random.randint(0, 255, (640, 640, 3), dtype=np.uint8)
2793
+ >>> tensor_img = transform(img)
2794
+ >>> print(tensor_img.shape, tensor_img.dtype)
2795
+ torch.Size([3, 640, 640]) torch.float16
2796
+ """
2797
+ im = np.ascontiguousarray(im.transpose((2, 0, 1))) # HWC to CHW -> contiguous
2798
+ im = torch.from_numpy(im) # to torch
2799
+ im = im.half() if self.half else im.float() # uint8 to fp16/32
2800
+ im /= 255.0 # 0-255 to 0.0-1.0
2801
+ return im