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