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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (299) hide show
  1. dgenerate_ultralytics_headless-8.3.253.dist-info/METADATA +405 -0
  2. dgenerate_ultralytics_headless-8.3.253.dist-info/RECORD +299 -0
  3. dgenerate_ultralytics_headless-8.3.253.dist-info/WHEEL +5 -0
  4. dgenerate_ultralytics_headless-8.3.253.dist-info/entry_points.txt +3 -0
  5. dgenerate_ultralytics_headless-8.3.253.dist-info/licenses/LICENSE +661 -0
  6. dgenerate_ultralytics_headless-8.3.253.dist-info/top_level.txt +1 -0
  7. tests/__init__.py +23 -0
  8. tests/conftest.py +59 -0
  9. tests/test_cli.py +131 -0
  10. tests/test_cuda.py +216 -0
  11. tests/test_engine.py +157 -0
  12. tests/test_exports.py +309 -0
  13. tests/test_integrations.py +151 -0
  14. tests/test_python.py +777 -0
  15. tests/test_solutions.py +371 -0
  16. ultralytics/__init__.py +48 -0
  17. ultralytics/assets/bus.jpg +0 -0
  18. ultralytics/assets/zidane.jpg +0 -0
  19. ultralytics/cfg/__init__.py +1028 -0
  20. ultralytics/cfg/datasets/Argoverse.yaml +78 -0
  21. ultralytics/cfg/datasets/DOTAv1.5.yaml +37 -0
  22. ultralytics/cfg/datasets/DOTAv1.yaml +36 -0
  23. ultralytics/cfg/datasets/GlobalWheat2020.yaml +68 -0
  24. ultralytics/cfg/datasets/HomeObjects-3K.yaml +32 -0
  25. ultralytics/cfg/datasets/ImageNet.yaml +2025 -0
  26. ultralytics/cfg/datasets/Objects365.yaml +447 -0
  27. ultralytics/cfg/datasets/SKU-110K.yaml +58 -0
  28. ultralytics/cfg/datasets/TT100K.yaml +346 -0
  29. ultralytics/cfg/datasets/VOC.yaml +102 -0
  30. ultralytics/cfg/datasets/VisDrone.yaml +87 -0
  31. ultralytics/cfg/datasets/african-wildlife.yaml +25 -0
  32. ultralytics/cfg/datasets/brain-tumor.yaml +22 -0
  33. ultralytics/cfg/datasets/carparts-seg.yaml +44 -0
  34. ultralytics/cfg/datasets/coco-pose.yaml +64 -0
  35. ultralytics/cfg/datasets/coco.yaml +118 -0
  36. ultralytics/cfg/datasets/coco128-seg.yaml +101 -0
  37. ultralytics/cfg/datasets/coco128.yaml +101 -0
  38. ultralytics/cfg/datasets/coco8-grayscale.yaml +103 -0
  39. ultralytics/cfg/datasets/coco8-multispectral.yaml +104 -0
  40. ultralytics/cfg/datasets/coco8-pose.yaml +47 -0
  41. ultralytics/cfg/datasets/coco8-seg.yaml +101 -0
  42. ultralytics/cfg/datasets/coco8.yaml +101 -0
  43. ultralytics/cfg/datasets/construction-ppe.yaml +32 -0
  44. ultralytics/cfg/datasets/crack-seg.yaml +22 -0
  45. ultralytics/cfg/datasets/dog-pose.yaml +52 -0
  46. ultralytics/cfg/datasets/dota8-multispectral.yaml +38 -0
  47. ultralytics/cfg/datasets/dota8.yaml +35 -0
  48. ultralytics/cfg/datasets/hand-keypoints.yaml +50 -0
  49. ultralytics/cfg/datasets/kitti.yaml +27 -0
  50. ultralytics/cfg/datasets/lvis.yaml +1240 -0
  51. ultralytics/cfg/datasets/medical-pills.yaml +21 -0
  52. ultralytics/cfg/datasets/open-images-v7.yaml +663 -0
  53. ultralytics/cfg/datasets/package-seg.yaml +22 -0
  54. ultralytics/cfg/datasets/signature.yaml +21 -0
  55. ultralytics/cfg/datasets/tiger-pose.yaml +41 -0
  56. ultralytics/cfg/datasets/xView.yaml +155 -0
  57. ultralytics/cfg/default.yaml +130 -0
  58. ultralytics/cfg/models/11/yolo11-cls-resnet18.yaml +17 -0
  59. ultralytics/cfg/models/11/yolo11-cls.yaml +33 -0
  60. ultralytics/cfg/models/11/yolo11-obb.yaml +50 -0
  61. ultralytics/cfg/models/11/yolo11-pose.yaml +51 -0
  62. ultralytics/cfg/models/11/yolo11-seg.yaml +50 -0
  63. ultralytics/cfg/models/11/yolo11.yaml +50 -0
  64. ultralytics/cfg/models/11/yoloe-11-seg.yaml +48 -0
  65. ultralytics/cfg/models/11/yoloe-11.yaml +48 -0
  66. ultralytics/cfg/models/12/yolo12-cls.yaml +32 -0
  67. ultralytics/cfg/models/12/yolo12-obb.yaml +48 -0
  68. ultralytics/cfg/models/12/yolo12-pose.yaml +49 -0
  69. ultralytics/cfg/models/12/yolo12-seg.yaml +48 -0
  70. ultralytics/cfg/models/12/yolo12.yaml +48 -0
  71. ultralytics/cfg/models/rt-detr/rtdetr-l.yaml +53 -0
  72. ultralytics/cfg/models/rt-detr/rtdetr-resnet101.yaml +45 -0
  73. ultralytics/cfg/models/rt-detr/rtdetr-resnet50.yaml +45 -0
  74. ultralytics/cfg/models/rt-detr/rtdetr-x.yaml +57 -0
  75. ultralytics/cfg/models/v10/yolov10b.yaml +45 -0
  76. ultralytics/cfg/models/v10/yolov10l.yaml +45 -0
  77. ultralytics/cfg/models/v10/yolov10m.yaml +45 -0
  78. ultralytics/cfg/models/v10/yolov10n.yaml +45 -0
  79. ultralytics/cfg/models/v10/yolov10s.yaml +45 -0
  80. ultralytics/cfg/models/v10/yolov10x.yaml +45 -0
  81. ultralytics/cfg/models/v3/yolov3-spp.yaml +49 -0
  82. ultralytics/cfg/models/v3/yolov3-tiny.yaml +40 -0
  83. ultralytics/cfg/models/v3/yolov3.yaml +49 -0
  84. ultralytics/cfg/models/v5/yolov5-p6.yaml +62 -0
  85. ultralytics/cfg/models/v5/yolov5.yaml +51 -0
  86. ultralytics/cfg/models/v6/yolov6.yaml +56 -0
  87. ultralytics/cfg/models/v8/yoloe-v8-seg.yaml +48 -0
  88. ultralytics/cfg/models/v8/yoloe-v8.yaml +48 -0
  89. ultralytics/cfg/models/v8/yolov8-cls-resnet101.yaml +28 -0
  90. ultralytics/cfg/models/v8/yolov8-cls-resnet50.yaml +28 -0
  91. ultralytics/cfg/models/v8/yolov8-cls.yaml +32 -0
  92. ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml +58 -0
  93. ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml +60 -0
  94. ultralytics/cfg/models/v8/yolov8-ghost.yaml +50 -0
  95. ultralytics/cfg/models/v8/yolov8-obb.yaml +49 -0
  96. ultralytics/cfg/models/v8/yolov8-p2.yaml +57 -0
  97. ultralytics/cfg/models/v8/yolov8-p6.yaml +59 -0
  98. ultralytics/cfg/models/v8/yolov8-pose-p6.yaml +60 -0
  99. ultralytics/cfg/models/v8/yolov8-pose.yaml +50 -0
  100. ultralytics/cfg/models/v8/yolov8-rtdetr.yaml +49 -0
  101. ultralytics/cfg/models/v8/yolov8-seg-p6.yaml +59 -0
  102. ultralytics/cfg/models/v8/yolov8-seg.yaml +49 -0
  103. ultralytics/cfg/models/v8/yolov8-world.yaml +51 -0
  104. ultralytics/cfg/models/v8/yolov8-worldv2.yaml +49 -0
  105. ultralytics/cfg/models/v8/yolov8.yaml +49 -0
  106. ultralytics/cfg/models/v9/yolov9c-seg.yaml +41 -0
  107. ultralytics/cfg/models/v9/yolov9c.yaml +41 -0
  108. ultralytics/cfg/models/v9/yolov9e-seg.yaml +64 -0
  109. ultralytics/cfg/models/v9/yolov9e.yaml +64 -0
  110. ultralytics/cfg/models/v9/yolov9m.yaml +41 -0
  111. ultralytics/cfg/models/v9/yolov9s.yaml +41 -0
  112. ultralytics/cfg/models/v9/yolov9t.yaml +41 -0
  113. ultralytics/cfg/trackers/botsort.yaml +21 -0
  114. ultralytics/cfg/trackers/bytetrack.yaml +12 -0
  115. ultralytics/data/__init__.py +26 -0
  116. ultralytics/data/annotator.py +66 -0
  117. ultralytics/data/augment.py +2801 -0
  118. ultralytics/data/base.py +435 -0
  119. ultralytics/data/build.py +437 -0
  120. ultralytics/data/converter.py +855 -0
  121. ultralytics/data/dataset.py +834 -0
  122. ultralytics/data/loaders.py +704 -0
  123. ultralytics/data/scripts/download_weights.sh +18 -0
  124. ultralytics/data/scripts/get_coco.sh +61 -0
  125. ultralytics/data/scripts/get_coco128.sh +18 -0
  126. ultralytics/data/scripts/get_imagenet.sh +52 -0
  127. ultralytics/data/split.py +138 -0
  128. ultralytics/data/split_dota.py +344 -0
  129. ultralytics/data/utils.py +798 -0
  130. ultralytics/engine/__init__.py +1 -0
  131. ultralytics/engine/exporter.py +1580 -0
  132. ultralytics/engine/model.py +1125 -0
  133. ultralytics/engine/predictor.py +508 -0
  134. ultralytics/engine/results.py +1522 -0
  135. ultralytics/engine/trainer.py +977 -0
  136. ultralytics/engine/tuner.py +449 -0
  137. ultralytics/engine/validator.py +387 -0
  138. ultralytics/hub/__init__.py +166 -0
  139. ultralytics/hub/auth.py +151 -0
  140. ultralytics/hub/google/__init__.py +174 -0
  141. ultralytics/hub/session.py +422 -0
  142. ultralytics/hub/utils.py +162 -0
  143. ultralytics/models/__init__.py +9 -0
  144. ultralytics/models/fastsam/__init__.py +7 -0
  145. ultralytics/models/fastsam/model.py +79 -0
  146. ultralytics/models/fastsam/predict.py +169 -0
  147. ultralytics/models/fastsam/utils.py +23 -0
  148. ultralytics/models/fastsam/val.py +38 -0
  149. ultralytics/models/nas/__init__.py +7 -0
  150. ultralytics/models/nas/model.py +98 -0
  151. ultralytics/models/nas/predict.py +56 -0
  152. ultralytics/models/nas/val.py +38 -0
  153. ultralytics/models/rtdetr/__init__.py +7 -0
  154. ultralytics/models/rtdetr/model.py +63 -0
  155. ultralytics/models/rtdetr/predict.py +88 -0
  156. ultralytics/models/rtdetr/train.py +89 -0
  157. ultralytics/models/rtdetr/val.py +216 -0
  158. ultralytics/models/sam/__init__.py +25 -0
  159. ultralytics/models/sam/amg.py +275 -0
  160. ultralytics/models/sam/build.py +365 -0
  161. ultralytics/models/sam/build_sam3.py +377 -0
  162. ultralytics/models/sam/model.py +169 -0
  163. ultralytics/models/sam/modules/__init__.py +1 -0
  164. ultralytics/models/sam/modules/blocks.py +1067 -0
  165. ultralytics/models/sam/modules/decoders.py +495 -0
  166. ultralytics/models/sam/modules/encoders.py +794 -0
  167. ultralytics/models/sam/modules/memory_attention.py +298 -0
  168. ultralytics/models/sam/modules/sam.py +1160 -0
  169. ultralytics/models/sam/modules/tiny_encoder.py +979 -0
  170. ultralytics/models/sam/modules/transformer.py +344 -0
  171. ultralytics/models/sam/modules/utils.py +512 -0
  172. ultralytics/models/sam/predict.py +3940 -0
  173. ultralytics/models/sam/sam3/__init__.py +3 -0
  174. ultralytics/models/sam/sam3/decoder.py +546 -0
  175. ultralytics/models/sam/sam3/encoder.py +529 -0
  176. ultralytics/models/sam/sam3/geometry_encoders.py +415 -0
  177. ultralytics/models/sam/sam3/maskformer_segmentation.py +286 -0
  178. ultralytics/models/sam/sam3/model_misc.py +199 -0
  179. ultralytics/models/sam/sam3/necks.py +129 -0
  180. ultralytics/models/sam/sam3/sam3_image.py +339 -0
  181. ultralytics/models/sam/sam3/text_encoder_ve.py +307 -0
  182. ultralytics/models/sam/sam3/vitdet.py +547 -0
  183. ultralytics/models/sam/sam3/vl_combiner.py +160 -0
  184. ultralytics/models/utils/__init__.py +1 -0
  185. ultralytics/models/utils/loss.py +466 -0
  186. ultralytics/models/utils/ops.py +315 -0
  187. ultralytics/models/yolo/__init__.py +7 -0
  188. ultralytics/models/yolo/classify/__init__.py +7 -0
  189. ultralytics/models/yolo/classify/predict.py +90 -0
  190. ultralytics/models/yolo/classify/train.py +202 -0
  191. ultralytics/models/yolo/classify/val.py +216 -0
  192. ultralytics/models/yolo/detect/__init__.py +7 -0
  193. ultralytics/models/yolo/detect/predict.py +122 -0
  194. ultralytics/models/yolo/detect/train.py +227 -0
  195. ultralytics/models/yolo/detect/val.py +507 -0
  196. ultralytics/models/yolo/model.py +430 -0
  197. ultralytics/models/yolo/obb/__init__.py +7 -0
  198. ultralytics/models/yolo/obb/predict.py +56 -0
  199. ultralytics/models/yolo/obb/train.py +79 -0
  200. ultralytics/models/yolo/obb/val.py +302 -0
  201. ultralytics/models/yolo/pose/__init__.py +7 -0
  202. ultralytics/models/yolo/pose/predict.py +65 -0
  203. ultralytics/models/yolo/pose/train.py +110 -0
  204. ultralytics/models/yolo/pose/val.py +248 -0
  205. ultralytics/models/yolo/segment/__init__.py +7 -0
  206. ultralytics/models/yolo/segment/predict.py +109 -0
  207. ultralytics/models/yolo/segment/train.py +69 -0
  208. ultralytics/models/yolo/segment/val.py +307 -0
  209. ultralytics/models/yolo/world/__init__.py +5 -0
  210. ultralytics/models/yolo/world/train.py +173 -0
  211. ultralytics/models/yolo/world/train_world.py +178 -0
  212. ultralytics/models/yolo/yoloe/__init__.py +22 -0
  213. ultralytics/models/yolo/yoloe/predict.py +162 -0
  214. ultralytics/models/yolo/yoloe/train.py +287 -0
  215. ultralytics/models/yolo/yoloe/train_seg.py +122 -0
  216. ultralytics/models/yolo/yoloe/val.py +206 -0
  217. ultralytics/nn/__init__.py +27 -0
  218. ultralytics/nn/autobackend.py +964 -0
  219. ultralytics/nn/modules/__init__.py +182 -0
  220. ultralytics/nn/modules/activation.py +54 -0
  221. ultralytics/nn/modules/block.py +1947 -0
  222. ultralytics/nn/modules/conv.py +669 -0
  223. ultralytics/nn/modules/head.py +1183 -0
  224. ultralytics/nn/modules/transformer.py +793 -0
  225. ultralytics/nn/modules/utils.py +159 -0
  226. ultralytics/nn/tasks.py +1768 -0
  227. ultralytics/nn/text_model.py +356 -0
  228. ultralytics/py.typed +1 -0
  229. ultralytics/solutions/__init__.py +41 -0
  230. ultralytics/solutions/ai_gym.py +108 -0
  231. ultralytics/solutions/analytics.py +264 -0
  232. ultralytics/solutions/config.py +107 -0
  233. ultralytics/solutions/distance_calculation.py +123 -0
  234. ultralytics/solutions/heatmap.py +125 -0
  235. ultralytics/solutions/instance_segmentation.py +86 -0
  236. ultralytics/solutions/object_blurrer.py +89 -0
  237. ultralytics/solutions/object_counter.py +190 -0
  238. ultralytics/solutions/object_cropper.py +87 -0
  239. ultralytics/solutions/parking_management.py +280 -0
  240. ultralytics/solutions/queue_management.py +93 -0
  241. ultralytics/solutions/region_counter.py +133 -0
  242. ultralytics/solutions/security_alarm.py +151 -0
  243. ultralytics/solutions/similarity_search.py +219 -0
  244. ultralytics/solutions/solutions.py +828 -0
  245. ultralytics/solutions/speed_estimation.py +114 -0
  246. ultralytics/solutions/streamlit_inference.py +260 -0
  247. ultralytics/solutions/templates/similarity-search.html +156 -0
  248. ultralytics/solutions/trackzone.py +88 -0
  249. ultralytics/solutions/vision_eye.py +67 -0
  250. ultralytics/trackers/__init__.py +7 -0
  251. ultralytics/trackers/basetrack.py +115 -0
  252. ultralytics/trackers/bot_sort.py +257 -0
  253. ultralytics/trackers/byte_tracker.py +469 -0
  254. ultralytics/trackers/track.py +116 -0
  255. ultralytics/trackers/utils/__init__.py +1 -0
  256. ultralytics/trackers/utils/gmc.py +339 -0
  257. ultralytics/trackers/utils/kalman_filter.py +482 -0
  258. ultralytics/trackers/utils/matching.py +154 -0
  259. ultralytics/utils/__init__.py +1450 -0
  260. ultralytics/utils/autobatch.py +118 -0
  261. ultralytics/utils/autodevice.py +205 -0
  262. ultralytics/utils/benchmarks.py +728 -0
  263. ultralytics/utils/callbacks/__init__.py +5 -0
  264. ultralytics/utils/callbacks/base.py +233 -0
  265. ultralytics/utils/callbacks/clearml.py +146 -0
  266. ultralytics/utils/callbacks/comet.py +625 -0
  267. ultralytics/utils/callbacks/dvc.py +197 -0
  268. ultralytics/utils/callbacks/hub.py +110 -0
  269. ultralytics/utils/callbacks/mlflow.py +134 -0
  270. ultralytics/utils/callbacks/neptune.py +126 -0
  271. ultralytics/utils/callbacks/platform.py +453 -0
  272. ultralytics/utils/callbacks/raytune.py +42 -0
  273. ultralytics/utils/callbacks/tensorboard.py +123 -0
  274. ultralytics/utils/callbacks/wb.py +188 -0
  275. ultralytics/utils/checks.py +1020 -0
  276. ultralytics/utils/cpu.py +85 -0
  277. ultralytics/utils/dist.py +123 -0
  278. ultralytics/utils/downloads.py +529 -0
  279. ultralytics/utils/errors.py +35 -0
  280. ultralytics/utils/events.py +113 -0
  281. ultralytics/utils/export/__init__.py +7 -0
  282. ultralytics/utils/export/engine.py +237 -0
  283. ultralytics/utils/export/imx.py +325 -0
  284. ultralytics/utils/export/tensorflow.py +231 -0
  285. ultralytics/utils/files.py +219 -0
  286. ultralytics/utils/git.py +137 -0
  287. ultralytics/utils/instance.py +484 -0
  288. ultralytics/utils/logger.py +506 -0
  289. ultralytics/utils/loss.py +849 -0
  290. ultralytics/utils/metrics.py +1563 -0
  291. ultralytics/utils/nms.py +337 -0
  292. ultralytics/utils/ops.py +664 -0
  293. ultralytics/utils/patches.py +201 -0
  294. ultralytics/utils/plotting.py +1047 -0
  295. ultralytics/utils/tal.py +404 -0
  296. ultralytics/utils/torch_utils.py +984 -0
  297. ultralytics/utils/tqdm.py +443 -0
  298. ultralytics/utils/triton.py +112 -0
  299. ultralytics/utils/tuner.py +168 -0
@@ -0,0 +1,834 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections import defaultdict
7
+ from itertools import repeat
8
+ from multiprocessing.pool import ThreadPool
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ import cv2
13
+ import numpy as np
14
+ import torch
15
+ from PIL import Image
16
+ from torch.utils.data import ConcatDataset
17
+
18
+ from ultralytics.utils import LOCAL_RANK, LOGGER, NUM_THREADS, TQDM, colorstr
19
+ from ultralytics.utils.instance import Instances
20
+ from ultralytics.utils.ops import resample_segments, segments2boxes
21
+ from ultralytics.utils.torch_utils import TORCHVISION_0_18
22
+
23
+ from .augment import (
24
+ Compose,
25
+ Format,
26
+ LetterBox,
27
+ RandomLoadText,
28
+ classify_augmentations,
29
+ classify_transforms,
30
+ v8_transforms,
31
+ )
32
+ from .base import BaseDataset
33
+ from .converter import merge_multi_segment
34
+ from .utils import (
35
+ HELP_URL,
36
+ check_file_speeds,
37
+ get_hash,
38
+ img2label_paths,
39
+ load_dataset_cache_file,
40
+ save_dataset_cache_file,
41
+ verify_image,
42
+ verify_image_label,
43
+ )
44
+
45
+ # Ultralytics dataset *.cache version, >= 1.0.0 for Ultralytics YOLO models
46
+ DATASET_CACHE_VERSION = "1.0.3"
47
+
48
+
49
+ class YOLODataset(BaseDataset):
50
+ """Dataset class for loading object detection and/or segmentation labels in YOLO format.
51
+
52
+ This class supports loading data for object detection, segmentation, pose estimation, and oriented bounding box
53
+ (OBB) tasks using the YOLO format.
54
+
55
+ Attributes:
56
+ use_segments (bool): Indicates if segmentation masks should be used.
57
+ use_keypoints (bool): Indicates if keypoints should be used for pose estimation.
58
+ use_obb (bool): Indicates if oriented bounding boxes should be used.
59
+ data (dict): Dataset configuration dictionary.
60
+
61
+ Methods:
62
+ cache_labels: Cache dataset labels, check images and read shapes.
63
+ get_labels: Return dictionary of labels for YOLO training.
64
+ build_transforms: Build and append transforms to the list.
65
+ close_mosaic: Set mosaic, copy_paste and mixup options to 0.0 and build transformations.
66
+ update_labels_info: Update label format for different tasks.
67
+ collate_fn: Collate data samples into batches.
68
+
69
+ Examples:
70
+ >>> dataset = YOLODataset(img_path="path/to/images", data={"names": {0: "person"}}, task="detect")
71
+ >>> dataset.get_labels()
72
+ """
73
+
74
+ def __init__(self, *args, data: dict | None = None, task: str = "detect", **kwargs):
75
+ """Initialize the YOLODataset.
76
+
77
+ Args:
78
+ data (dict, optional): Dataset configuration dictionary.
79
+ task (str): Task type, one of 'detect', 'segment', 'pose', or 'obb'.
80
+ *args (Any): Additional positional arguments for the parent class.
81
+ **kwargs (Any): Additional keyword arguments for the parent class.
82
+ """
83
+ self.use_segments = task == "segment"
84
+ self.use_keypoints = task == "pose"
85
+ self.use_obb = task == "obb"
86
+ self.data = data
87
+ assert not (self.use_segments and self.use_keypoints), "Can not use both segments and keypoints."
88
+ super().__init__(*args, channels=self.data.get("channels", 3), **kwargs)
89
+
90
+ def cache_labels(self, path: Path = Path("./labels.cache")) -> dict:
91
+ """Cache dataset labels, check images and read shapes.
92
+
93
+ Args:
94
+ path (Path): Path where to save the cache file.
95
+
96
+ Returns:
97
+ (dict): Dictionary containing cached labels and related information.
98
+ """
99
+ x = {"labels": []}
100
+ nm, nf, ne, nc, msgs = 0, 0, 0, 0, [] # number missing, found, empty, corrupt, messages
101
+ desc = f"{self.prefix}Scanning {path.parent / path.stem}..."
102
+ total = len(self.im_files)
103
+ nkpt, ndim = self.data.get("kpt_shape", (0, 0))
104
+ if self.use_keypoints and (nkpt <= 0 or ndim not in {2, 3}):
105
+ raise ValueError(
106
+ "'kpt_shape' in data.yaml missing or incorrect. Should be a list with [number of "
107
+ "keypoints, number of dims (2 for x,y or 3 for x,y,visible)], i.e. 'kpt_shape: [17, 3]'"
108
+ )
109
+ with ThreadPool(NUM_THREADS) as pool:
110
+ results = pool.imap(
111
+ func=verify_image_label,
112
+ iterable=zip(
113
+ self.im_files,
114
+ self.label_files,
115
+ repeat(self.prefix),
116
+ repeat(self.use_keypoints),
117
+ repeat(len(self.data["names"])),
118
+ repeat(nkpt),
119
+ repeat(ndim),
120
+ repeat(self.single_cls),
121
+ ),
122
+ )
123
+ pbar = TQDM(results, desc=desc, total=total)
124
+ for im_file, lb, shape, segments, keypoint, nm_f, nf_f, ne_f, nc_f, msg in pbar:
125
+ nm += nm_f
126
+ nf += nf_f
127
+ ne += ne_f
128
+ nc += nc_f
129
+ if im_file:
130
+ x["labels"].append(
131
+ {
132
+ "im_file": im_file,
133
+ "shape": shape,
134
+ "cls": lb[:, 0:1], # n, 1
135
+ "bboxes": lb[:, 1:], # n, 4
136
+ "segments": segments,
137
+ "keypoints": keypoint,
138
+ "normalized": True,
139
+ "bbox_format": "xywh",
140
+ }
141
+ )
142
+ if msg:
143
+ msgs.append(msg)
144
+ pbar.desc = f"{desc} {nf} images, {nm + ne} backgrounds, {nc} corrupt"
145
+ pbar.close()
146
+
147
+ if msgs:
148
+ LOGGER.info("\n".join(msgs))
149
+ if nf == 0:
150
+ LOGGER.warning(f"{self.prefix}No labels found in {path}. {HELP_URL}")
151
+ x["hash"] = get_hash(self.label_files + self.im_files)
152
+ x["results"] = nf, nm, ne, nc, len(self.im_files)
153
+ x["msgs"] = msgs # warnings
154
+ save_dataset_cache_file(self.prefix, path, x, DATASET_CACHE_VERSION)
155
+ return x
156
+
157
+ def get_labels(self) -> list[dict]:
158
+ """Return dictionary of labels for YOLO training.
159
+
160
+ This method loads labels from disk or cache, verifies their integrity, and prepares them for training.
161
+
162
+ Returns:
163
+ (list[dict]): List of label dictionaries, each containing information about an image and its annotations.
164
+ """
165
+ self.label_files = img2label_paths(self.im_files)
166
+ cache_path = Path(self.label_files[0]).parent.with_suffix(".cache")
167
+ try:
168
+ cache, exists = load_dataset_cache_file(cache_path), True # attempt to load a *.cache file
169
+ assert cache["version"] == DATASET_CACHE_VERSION # matches current version
170
+ assert cache["hash"] == get_hash(self.label_files + self.im_files) # identical hash
171
+ except (FileNotFoundError, AssertionError, AttributeError, ModuleNotFoundError):
172
+ cache, exists = self.cache_labels(cache_path), False # run cache ops
173
+
174
+ # Display cache
175
+ nf, nm, ne, nc, n = cache.pop("results") # found, missing, empty, corrupt, total
176
+ if exists and LOCAL_RANK in {-1, 0}:
177
+ d = f"Scanning {cache_path}... {nf} images, {nm + ne} backgrounds, {nc} corrupt"
178
+ TQDM(None, desc=self.prefix + d, total=n, initial=n) # display results
179
+ if cache["msgs"]:
180
+ LOGGER.info("\n".join(cache["msgs"])) # display warnings
181
+
182
+ # Read cache
183
+ [cache.pop(k) for k in ("hash", "version", "msgs")] # remove items
184
+ labels = cache["labels"]
185
+ if not labels:
186
+ raise RuntimeError(
187
+ f"No valid images found in {cache_path}. Images with incorrectly formatted labels are ignored. {HELP_URL}"
188
+ )
189
+ self.im_files = [lb["im_file"] for lb in labels] # update im_files
190
+
191
+ # Check if the dataset is all boxes or all segments
192
+ lengths = ((len(lb["cls"]), len(lb["bboxes"]), len(lb["segments"])) for lb in labels)
193
+ len_cls, len_boxes, len_segments = (sum(x) for x in zip(*lengths))
194
+ if len_segments and len_boxes != len_segments:
195
+ LOGGER.warning(
196
+ f"Box and segment counts should be equal, but got len(segments) = {len_segments}, "
197
+ f"len(boxes) = {len_boxes}. To resolve this only boxes will be used and all segments will be removed. "
198
+ "To avoid this please supply either a detect or segment dataset, not a detect-segment mixed dataset."
199
+ )
200
+ for lb in labels:
201
+ lb["segments"] = []
202
+ if len_cls == 0:
203
+ LOGGER.warning(f"Labels are missing or empty in {cache_path}, training may not work correctly. {HELP_URL}")
204
+ return labels
205
+
206
+ def build_transforms(self, hyp: dict | None = None) -> Compose:
207
+ """Build and append transforms to the list.
208
+
209
+ Args:
210
+ hyp (dict, optional): Hyperparameters for transforms.
211
+
212
+ Returns:
213
+ (Compose): Composed transforms.
214
+ """
215
+ if self.augment:
216
+ hyp.mosaic = hyp.mosaic if self.augment and not self.rect else 0.0
217
+ hyp.mixup = hyp.mixup if self.augment and not self.rect else 0.0
218
+ hyp.cutmix = hyp.cutmix if self.augment and not self.rect else 0.0
219
+ transforms = v8_transforms(self, self.imgsz, hyp)
220
+ else:
221
+ transforms = Compose([LetterBox(new_shape=(self.imgsz, self.imgsz), scaleup=False)])
222
+ transforms.append(
223
+ Format(
224
+ bbox_format="xywh",
225
+ normalize=True,
226
+ return_mask=self.use_segments,
227
+ return_keypoint=self.use_keypoints,
228
+ return_obb=self.use_obb,
229
+ batch_idx=True,
230
+ mask_ratio=hyp.mask_ratio,
231
+ mask_overlap=hyp.overlap_mask,
232
+ bgr=hyp.bgr if self.augment else 0.0, # only affect training.
233
+ )
234
+ )
235
+ return transforms
236
+
237
+ def close_mosaic(self, hyp: dict) -> None:
238
+ """Disable mosaic, copy_paste, mixup and cutmix augmentations by setting their probabilities to 0.0.
239
+
240
+ Args:
241
+ hyp (dict): Hyperparameters for transforms.
242
+ """
243
+ hyp.mosaic = 0.0
244
+ hyp.copy_paste = 0.0
245
+ hyp.mixup = 0.0
246
+ hyp.cutmix = 0.0
247
+ self.transforms = self.build_transforms(hyp)
248
+
249
+ def update_labels_info(self, label: dict) -> dict:
250
+ """Update label format for different tasks.
251
+
252
+ Args:
253
+ label (dict): Label dictionary containing bboxes, segments, keypoints, etc.
254
+
255
+ Returns:
256
+ (dict): Updated label dictionary with instances.
257
+
258
+ Notes:
259
+ cls is not with bboxes now, classification and semantic segmentation need an independent cls label
260
+ Can also support classification and semantic segmentation by adding or removing dict keys there.
261
+ """
262
+ bboxes = label.pop("bboxes")
263
+ segments = label.pop("segments", [])
264
+ keypoints = label.pop("keypoints", None)
265
+ bbox_format = label.pop("bbox_format")
266
+ normalized = label.pop("normalized")
267
+
268
+ # NOTE: do NOT resample oriented boxes
269
+ segment_resamples = 100 if self.use_obb else 1000
270
+ if len(segments) > 0:
271
+ # make sure segments interpolate correctly if original length is greater than segment_resamples
272
+ max_len = max(len(s) for s in segments)
273
+ segment_resamples = (max_len + 1) if segment_resamples < max_len else segment_resamples
274
+ # list[np.array(segment_resamples, 2)] * num_samples
275
+ segments = np.stack(resample_segments(segments, n=segment_resamples), axis=0)
276
+ else:
277
+ segments = np.zeros((0, segment_resamples, 2), dtype=np.float32)
278
+ label["instances"] = Instances(bboxes, segments, keypoints, bbox_format=bbox_format, normalized=normalized)
279
+ return label
280
+
281
+ @staticmethod
282
+ def collate_fn(batch: list[dict]) -> dict:
283
+ """Collate data samples into batches.
284
+
285
+ Args:
286
+ batch (list[dict]): List of dictionaries containing sample data.
287
+
288
+ Returns:
289
+ (dict): Collated batch with stacked tensors.
290
+ """
291
+ new_batch = {}
292
+ batch = [dict(sorted(b.items())) for b in batch] # make sure the keys are in the same order
293
+ keys = batch[0].keys()
294
+ values = list(zip(*[list(b.values()) for b in batch]))
295
+ for i, k in enumerate(keys):
296
+ value = values[i]
297
+ if k in {"img", "text_feats"}:
298
+ value = torch.stack(value, 0)
299
+ elif k == "visuals":
300
+ value = torch.nn.utils.rnn.pad_sequence(value, batch_first=True)
301
+ if k in {"masks", "keypoints", "bboxes", "cls", "segments", "obb"}:
302
+ value = torch.cat(value, 0)
303
+ new_batch[k] = value
304
+ new_batch["batch_idx"] = list(new_batch["batch_idx"])
305
+ for i in range(len(new_batch["batch_idx"])):
306
+ new_batch["batch_idx"][i] += i # add target image index for build_targets()
307
+ new_batch["batch_idx"] = torch.cat(new_batch["batch_idx"], 0)
308
+ return new_batch
309
+
310
+
311
+ class YOLOMultiModalDataset(YOLODataset):
312
+ """Dataset class for loading object detection and/or segmentation labels in YOLO format with multi-modal support.
313
+
314
+ This class extends YOLODataset to add text information for multi-modal model training, enabling models to process
315
+ both image and text data.
316
+
317
+ Methods:
318
+ update_labels_info: Add text information for multi-modal model training.
319
+ build_transforms: Enhance data transformations with text augmentation.
320
+
321
+ Examples:
322
+ >>> dataset = YOLOMultiModalDataset(img_path="path/to/images", data={"names": {0: "person"}}, task="detect")
323
+ >>> batch = next(iter(dataset))
324
+ >>> print(batch.keys()) # Should include 'texts'
325
+ """
326
+
327
+ def __init__(self, *args, data: dict | None = None, task: str = "detect", **kwargs):
328
+ """Initialize a YOLOMultiModalDataset.
329
+
330
+ Args:
331
+ data (dict, optional): Dataset configuration dictionary.
332
+ task (str): Task type, one of 'detect', 'segment', 'pose', or 'obb'.
333
+ *args (Any): Additional positional arguments for the parent class.
334
+ **kwargs (Any): Additional keyword arguments for the parent class.
335
+ """
336
+ super().__init__(*args, data=data, task=task, **kwargs)
337
+
338
+ def update_labels_info(self, label: dict) -> dict:
339
+ """Add text information for multi-modal model training.
340
+
341
+ Args:
342
+ label (dict): Label dictionary containing bboxes, segments, keypoints, etc.
343
+
344
+ Returns:
345
+ (dict): Updated label dictionary with instances and texts.
346
+ """
347
+ labels = super().update_labels_info(label)
348
+ # NOTE: some categories are concatenated with its synonyms by `/`.
349
+ # NOTE: and `RandomLoadText` would randomly select one of them if there are multiple words.
350
+ labels["texts"] = [v.split("/") for _, v in self.data["names"].items()]
351
+
352
+ return labels
353
+
354
+ def build_transforms(self, hyp: dict | None = None) -> Compose:
355
+ """Enhance data transformations with optional text augmentation for multi-modal training.
356
+
357
+ Args:
358
+ hyp (dict, optional): Hyperparameters for transforms.
359
+
360
+ Returns:
361
+ (Compose): Composed transforms including text augmentation if applicable.
362
+ """
363
+ transforms = super().build_transforms(hyp)
364
+ if self.augment:
365
+ # NOTE: hard-coded the args for now.
366
+ # NOTE: this implementation is different from official yoloe,
367
+ # the strategy of selecting negative is restricted in one dataset,
368
+ # while official pre-saved neg embeddings from all datasets at once.
369
+ transform = RandomLoadText(
370
+ max_samples=min(self.data["nc"], 80),
371
+ padding=True,
372
+ padding_value=self._get_neg_texts(self.category_freq),
373
+ )
374
+ transforms.insert(-1, transform)
375
+ return transforms
376
+
377
+ @property
378
+ def category_names(self):
379
+ """Return category names for the dataset.
380
+
381
+ Returns:
382
+ (set[str]): List of class names.
383
+ """
384
+ names = self.data["names"].values()
385
+ return {n.strip() for name in names for n in name.split("/")} # category names
386
+
387
+ @property
388
+ def category_freq(self):
389
+ """Return frequency of each category in the dataset."""
390
+ texts = [v.split("/") for v in self.data["names"].values()]
391
+ category_freq = defaultdict(int)
392
+ for label in self.labels:
393
+ for c in label["cls"].squeeze(-1): # to check
394
+ text = texts[int(c)]
395
+ for t in text:
396
+ t = t.strip()
397
+ category_freq[t] += 1
398
+ return category_freq
399
+
400
+ @staticmethod
401
+ def _get_neg_texts(category_freq: dict, threshold: int = 100) -> list[str]:
402
+ """Get negative text samples based on frequency threshold."""
403
+ threshold = min(max(category_freq.values()), 100)
404
+ return [k for k, v in category_freq.items() if v >= threshold]
405
+
406
+
407
+ class GroundingDataset(YOLODataset):
408
+ """Dataset class for object detection tasks using annotations from a JSON file in grounding format.
409
+
410
+ This dataset is designed for grounding tasks where annotations are provided in a JSON file rather than the standard
411
+ YOLO format text files.
412
+
413
+ Attributes:
414
+ json_file (str): Path to the JSON file containing annotations.
415
+
416
+ Methods:
417
+ get_img_files: Return empty list as image files are read in get_labels.
418
+ get_labels: Load annotations from a JSON file and prepare them for training.
419
+ build_transforms: Configure augmentations for training with optional text loading.
420
+
421
+ Examples:
422
+ >>> dataset = GroundingDataset(img_path="path/to/images", json_file="annotations.json", task="detect")
423
+ >>> len(dataset) # Number of valid images with annotations
424
+ """
425
+
426
+ def __init__(self, *args, task: str = "detect", json_file: str = "", max_samples: int = 80, **kwargs):
427
+ """Initialize a GroundingDataset for object detection.
428
+
429
+ Args:
430
+ json_file (str): Path to the JSON file containing annotations.
431
+ task (str): Must be 'detect' or 'segment' for GroundingDataset.
432
+ max_samples (int): Maximum number of samples to load for text augmentation.
433
+ *args (Any): Additional positional arguments for the parent class.
434
+ **kwargs (Any): Additional keyword arguments for the parent class.
435
+ """
436
+ assert task in {"detect", "segment"}, "GroundingDataset currently only supports `detect` and `segment` tasks"
437
+ self.json_file = json_file
438
+ self.max_samples = max_samples
439
+ super().__init__(*args, task=task, data={"channels": 3}, **kwargs)
440
+
441
+ def get_img_files(self, img_path: str) -> list:
442
+ """The image files would be read in `get_labels` function, return empty list here.
443
+
444
+ Args:
445
+ img_path (str): Path to the directory containing images.
446
+
447
+ Returns:
448
+ (list): Empty list as image files are read in get_labels.
449
+ """
450
+ return []
451
+
452
+ def verify_labels(self, labels: list[dict[str, Any]]) -> None:
453
+ """Verify the number of instances in the dataset matches expected counts.
454
+
455
+ This method checks if the total number of bounding box instances in the provided labels matches the expected
456
+ count for known datasets. It performs validation against a predefined set of datasets with known instance
457
+ counts.
458
+
459
+ Args:
460
+ labels (list[dict[str, Any]]): List of label dictionaries, where each dictionary contains dataset
461
+ annotations. Each label dict must have a 'bboxes' key with a numpy array or tensor containing bounding
462
+ box coordinates.
463
+
464
+ Raises:
465
+ AssertionError: If the actual instance count doesn't match the expected count for a recognized dataset.
466
+
467
+ Notes:
468
+ For unrecognized datasets (those not in the predefined expected_counts),
469
+ a warning is logged and verification is skipped.
470
+ """
471
+ expected_counts = {
472
+ "final_mixed_train_no_coco_segm": 3662412,
473
+ "final_mixed_train_no_coco": 3681235,
474
+ "final_flickr_separateGT_train_segm": 638214,
475
+ "final_flickr_separateGT_train": 640704,
476
+ }
477
+
478
+ instance_count = sum(label["bboxes"].shape[0] for label in labels)
479
+ for data_name, count in expected_counts.items():
480
+ if data_name in self.json_file:
481
+ assert instance_count == count, f"'{self.json_file}' has {instance_count} instances, expected {count}."
482
+ return
483
+ LOGGER.warning(f"Skipping instance count verification for unrecognized dataset '{self.json_file}'")
484
+
485
+ def cache_labels(self, path: Path = Path("./labels.cache")) -> dict[str, Any]:
486
+ """Load annotations from a JSON file, filter, and normalize bounding boxes for each image.
487
+
488
+ Args:
489
+ path (Path): Path where to save the cache file.
490
+
491
+ Returns:
492
+ (dict[str, Any]): Dictionary containing cached labels and related information.
493
+ """
494
+ x = {"labels": []}
495
+ LOGGER.info("Loading annotation file...")
496
+ with open(self.json_file) as f:
497
+ annotations = json.load(f)
498
+ images = {f"{x['id']:d}": x for x in annotations["images"]}
499
+ img_to_anns = defaultdict(list)
500
+ for ann in annotations["annotations"]:
501
+ img_to_anns[ann["image_id"]].append(ann)
502
+ for img_id, anns in TQDM(img_to_anns.items(), desc=f"Reading annotations {self.json_file}"):
503
+ img = images[f"{img_id:d}"]
504
+ h, w, f = img["height"], img["width"], img["file_name"]
505
+ im_file = Path(self.img_path) / f
506
+ if not im_file.exists():
507
+ continue
508
+ self.im_files.append(str(im_file))
509
+ bboxes = []
510
+ segments = []
511
+ cat2id = {}
512
+ texts = []
513
+ for ann in anns:
514
+ if ann["iscrowd"]:
515
+ continue
516
+ box = np.array(ann["bbox"], dtype=np.float32)
517
+ box[:2] += box[2:] / 2
518
+ box[[0, 2]] /= float(w)
519
+ box[[1, 3]] /= float(h)
520
+ if box[2] <= 0 or box[3] <= 0:
521
+ continue
522
+
523
+ caption = img["caption"]
524
+ cat_name = " ".join([caption[t[0] : t[1]] for t in ann["tokens_positive"]]).lower().strip()
525
+ if not cat_name:
526
+ continue
527
+
528
+ if cat_name not in cat2id:
529
+ cat2id[cat_name] = len(cat2id)
530
+ texts.append([cat_name])
531
+ cls = cat2id[cat_name] # class
532
+ box = [cls, *box.tolist()]
533
+ if box not in bboxes:
534
+ bboxes.append(box)
535
+ if ann.get("segmentation") is not None:
536
+ if len(ann["segmentation"]) == 0:
537
+ segments.append(box)
538
+ continue
539
+ elif len(ann["segmentation"]) > 1:
540
+ s = merge_multi_segment(ann["segmentation"])
541
+ s = (np.concatenate(s, axis=0) / np.array([w, h], dtype=np.float32)).reshape(-1).tolist()
542
+ else:
543
+ s = [j for i in ann["segmentation"] for j in i] # all segments concatenated
544
+ s = (
545
+ (np.array(s, dtype=np.float32).reshape(-1, 2) / np.array([w, h], dtype=np.float32))
546
+ .reshape(-1)
547
+ .tolist()
548
+ )
549
+ s = [cls, *s]
550
+ segments.append(s)
551
+ lb = np.array(bboxes, dtype=np.float32) if len(bboxes) else np.zeros((0, 5), dtype=np.float32)
552
+
553
+ if segments:
554
+ classes = np.array([x[0] for x in segments], dtype=np.float32)
555
+ segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in segments] # (cls, xy1...)
556
+ lb = np.concatenate((classes.reshape(-1, 1), segments2boxes(segments)), 1) # (cls, xywh)
557
+ lb = np.array(lb, dtype=np.float32)
558
+
559
+ x["labels"].append(
560
+ {
561
+ "im_file": im_file,
562
+ "shape": (h, w),
563
+ "cls": lb[:, 0:1], # n, 1
564
+ "bboxes": lb[:, 1:], # n, 4
565
+ "segments": segments,
566
+ "normalized": True,
567
+ "bbox_format": "xywh",
568
+ "texts": texts,
569
+ }
570
+ )
571
+ x["hash"] = get_hash(self.json_file)
572
+ save_dataset_cache_file(self.prefix, path, x, DATASET_CACHE_VERSION)
573
+ return x
574
+
575
+ def get_labels(self) -> list[dict]:
576
+ """Load labels from cache or generate them from JSON file.
577
+
578
+ Returns:
579
+ (list[dict]): List of label dictionaries, each containing information about an image and its annotations.
580
+ """
581
+ cache_path = Path(self.json_file).with_suffix(".cache")
582
+ try:
583
+ cache, _ = load_dataset_cache_file(cache_path), True # attempt to load a *.cache file
584
+ assert cache["version"] == DATASET_CACHE_VERSION # matches current version
585
+ assert cache["hash"] == get_hash(self.json_file) # identical hash
586
+ except (FileNotFoundError, AssertionError, AttributeError, ModuleNotFoundError):
587
+ cache, _ = self.cache_labels(cache_path), False # run cache ops
588
+ [cache.pop(k) for k in ("hash", "version")] # remove items
589
+ labels = cache["labels"]
590
+ self.verify_labels(labels)
591
+ self.im_files = [str(label["im_file"]) for label in labels]
592
+ if LOCAL_RANK in {-1, 0}:
593
+ LOGGER.info(f"Load {self.json_file} from cache file {cache_path}")
594
+ return labels
595
+
596
+ def build_transforms(self, hyp: dict | None = None) -> Compose:
597
+ """Configure augmentations for training with optional text loading.
598
+
599
+ Args:
600
+ hyp (dict, optional): Hyperparameters for transforms.
601
+
602
+ Returns:
603
+ (Compose): Composed transforms including text augmentation if applicable.
604
+ """
605
+ transforms = super().build_transforms(hyp)
606
+ if self.augment:
607
+ # NOTE: hard-coded the args for now.
608
+ # NOTE: this implementation is different from official yoloe,
609
+ # the strategy of selecting negative is restricted in one dataset,
610
+ # while official pre-saved neg embeddings from all datasets at once.
611
+ transform = RandomLoadText(
612
+ max_samples=min(self.max_samples, 80),
613
+ padding=True,
614
+ padding_value=self._get_neg_texts(self.category_freq),
615
+ )
616
+ transforms.insert(-1, transform)
617
+ return transforms
618
+
619
+ @property
620
+ def category_names(self):
621
+ """Return unique category names from the dataset."""
622
+ return {t.strip() for label in self.labels for text in label["texts"] for t in text}
623
+
624
+ @property
625
+ def category_freq(self):
626
+ """Return frequency of each category in the dataset."""
627
+ category_freq = defaultdict(int)
628
+ for label in self.labels:
629
+ for text in label["texts"]:
630
+ for t in text:
631
+ t = t.strip()
632
+ category_freq[t] += 1
633
+ return category_freq
634
+
635
+ @staticmethod
636
+ def _get_neg_texts(category_freq: dict, threshold: int = 100) -> list[str]:
637
+ """Get negative text samples based on frequency threshold."""
638
+ threshold = min(max(category_freq.values()), 100)
639
+ return [k for k, v in category_freq.items() if v >= threshold]
640
+
641
+
642
+ class YOLOConcatDataset(ConcatDataset):
643
+ """Dataset as a concatenation of multiple datasets.
644
+
645
+ This class is useful to assemble different existing datasets for YOLO training, ensuring they use the same collation
646
+ function.
647
+
648
+ Methods:
649
+ collate_fn: Static method that collates data samples into batches using YOLODataset's collation function.
650
+
651
+ Examples:
652
+ >>> dataset1 = YOLODataset(...)
653
+ >>> dataset2 = YOLODataset(...)
654
+ >>> combined_dataset = YOLOConcatDataset([dataset1, dataset2])
655
+ """
656
+
657
+ @staticmethod
658
+ def collate_fn(batch: list[dict]) -> dict:
659
+ """Collate data samples into batches.
660
+
661
+ Args:
662
+ batch (list[dict]): List of dictionaries containing sample data.
663
+
664
+ Returns:
665
+ (dict): Collated batch with stacked tensors.
666
+ """
667
+ return YOLODataset.collate_fn(batch)
668
+
669
+ def close_mosaic(self, hyp: dict) -> None:
670
+ """Set mosaic, copy_paste and mixup options to 0.0 and build transformations.
671
+
672
+ Args:
673
+ hyp (dict): Hyperparameters for transforms.
674
+ """
675
+ for dataset in self.datasets:
676
+ if not hasattr(dataset, "close_mosaic"):
677
+ continue
678
+ dataset.close_mosaic(hyp)
679
+
680
+
681
+ # TODO: support semantic segmentation
682
+ class SemanticDataset(BaseDataset):
683
+ """Semantic Segmentation Dataset."""
684
+
685
+ def __init__(self):
686
+ """Initialize a SemanticDataset object."""
687
+ super().__init__()
688
+
689
+
690
+ class ClassificationDataset:
691
+ """Dataset class for image classification tasks extending torchvision ImageFolder functionality.
692
+
693
+ This class offers functionalities like image augmentation, caching, and verification. It's designed to efficiently
694
+ handle large datasets for training deep learning models, with optional image transformations and caching mechanisms
695
+ to speed up training.
696
+
697
+ Attributes:
698
+ cache_ram (bool): Indicates if caching in RAM is enabled.
699
+ cache_disk (bool): Indicates if caching on disk is enabled.
700
+ samples (list): A list of tuples, each containing the path to an image, its class index, path to its .npy cache
701
+ file (if caching on disk), and optionally the loaded image array (if caching in RAM).
702
+ torch_transforms (callable): PyTorch transforms to be applied to the images.
703
+ root (str): Root directory of the dataset.
704
+ prefix (str): Prefix for logging and cache filenames.
705
+
706
+ Methods:
707
+ __getitem__: Return subset of data and targets corresponding to given indices.
708
+ __len__: Return the total number of samples in the dataset.
709
+ verify_images: Verify all images in dataset.
710
+ """
711
+
712
+ def __init__(self, root: str, args, augment: bool = False, prefix: str = ""):
713
+ """Initialize YOLO classification dataset with root directory, arguments, augmentations, and cache settings.
714
+
715
+ Args:
716
+ root (str): Path to the dataset directory where images are stored in a class-specific folder structure.
717
+ args (Namespace): Configuration containing dataset-related settings such as image size, augmentation
718
+ parameters, and cache settings.
719
+ augment (bool, optional): Whether to apply augmentations to the dataset.
720
+ prefix (str, optional): Prefix for logging and cache filenames, aiding in dataset identification.
721
+ """
722
+ import torchvision # scope for faster 'import ultralytics'
723
+
724
+ # Base class assigned as attribute rather than used as base class to allow for scoping slow torchvision import
725
+ if TORCHVISION_0_18: # 'allow_empty' argument first introduced in torchvision 0.18
726
+ self.base = torchvision.datasets.ImageFolder(root=root, allow_empty=True)
727
+ else:
728
+ self.base = torchvision.datasets.ImageFolder(root=root)
729
+ self.samples = self.base.samples
730
+ self.root = self.base.root
731
+
732
+ # Initialize attributes
733
+ if augment and args.fraction < 1.0: # reduce training fraction
734
+ self.samples = self.samples[: round(len(self.samples) * args.fraction)]
735
+ self.prefix = colorstr(f"{prefix}: ") if prefix else ""
736
+ self.cache_ram = args.cache is True or str(args.cache).lower() == "ram" # cache images into RAM
737
+ if self.cache_ram:
738
+ LOGGER.warning(
739
+ "Classification `cache_ram` training has known memory leak in "
740
+ "https://github.com/ultralytics/ultralytics/issues/9824, setting `cache_ram=False`."
741
+ )
742
+ self.cache_ram = False
743
+ self.cache_disk = str(args.cache).lower() == "disk" # cache images on hard drive as uncompressed *.npy files
744
+ self.samples = self.verify_images() # filter out bad images
745
+ self.samples = [[*list(x), Path(x[0]).with_suffix(".npy"), None] for x in self.samples] # file, index, npy, im
746
+ scale = (1.0 - args.scale, 1.0) # (0.08, 1.0)
747
+ self.torch_transforms = (
748
+ classify_augmentations(
749
+ size=args.imgsz,
750
+ scale=scale,
751
+ hflip=args.fliplr,
752
+ vflip=args.flipud,
753
+ erasing=args.erasing,
754
+ auto_augment=args.auto_augment,
755
+ hsv_h=args.hsv_h,
756
+ hsv_s=args.hsv_s,
757
+ hsv_v=args.hsv_v,
758
+ )
759
+ if augment
760
+ else classify_transforms(size=args.imgsz)
761
+ )
762
+
763
+ def __getitem__(self, i: int) -> dict:
764
+ """Return subset of data and targets corresponding to given indices.
765
+
766
+ Args:
767
+ i (int): Index of the sample to retrieve.
768
+
769
+ Returns:
770
+ (dict): Dictionary containing the image and its class index.
771
+ """
772
+ f, j, fn, im = self.samples[i] # filename, index, filename.with_suffix('.npy'), image
773
+ if self.cache_ram:
774
+ if im is None: # Warning: two separate if statements required here, do not combine this with previous line
775
+ im = self.samples[i][3] = cv2.imread(f)
776
+ elif self.cache_disk:
777
+ if not fn.exists(): # load npy
778
+ np.save(fn.as_posix(), cv2.imread(f), allow_pickle=False)
779
+ im = np.load(fn)
780
+ else: # read image
781
+ im = cv2.imread(f) # BGR
782
+ # Convert NumPy array to PIL image
783
+ im = Image.fromarray(cv2.cvtColor(im, cv2.COLOR_BGR2RGB))
784
+ sample = self.torch_transforms(im)
785
+ return {"img": sample, "cls": j}
786
+
787
+ def __len__(self) -> int:
788
+ """Return the total number of samples in the dataset."""
789
+ return len(self.samples)
790
+
791
+ def verify_images(self) -> list[tuple]:
792
+ """Verify all images in dataset.
793
+
794
+ Returns:
795
+ (list): List of valid samples after verification.
796
+ """
797
+ desc = f"{self.prefix}Scanning {self.root}..."
798
+ path = Path(self.root).with_suffix(".cache") # *.cache file path
799
+
800
+ try:
801
+ check_file_speeds([file for (file, _) in self.samples[:5]], prefix=self.prefix) # check image read speeds
802
+ cache = load_dataset_cache_file(path) # attempt to load a *.cache file
803
+ assert cache["version"] == DATASET_CACHE_VERSION # matches current version
804
+ assert cache["hash"] == get_hash([x[0] for x in self.samples]) # identical hash
805
+ nf, nc, n, samples = cache.pop("results") # found, missing, empty, corrupt, total
806
+ if LOCAL_RANK in {-1, 0}:
807
+ d = f"{desc} {nf} images, {nc} corrupt"
808
+ TQDM(None, desc=d, total=n, initial=n)
809
+ if cache["msgs"]:
810
+ LOGGER.info("\n".join(cache["msgs"])) # display warnings
811
+ return samples
812
+
813
+ except (FileNotFoundError, AssertionError, AttributeError):
814
+ # Run scan if *.cache retrieval failed
815
+ nf, nc, msgs, samples, x = 0, 0, [], [], {}
816
+ with ThreadPool(NUM_THREADS) as pool:
817
+ results = pool.imap(func=verify_image, iterable=zip(self.samples, repeat(self.prefix)))
818
+ pbar = TQDM(results, desc=desc, total=len(self.samples))
819
+ for sample, nf_f, nc_f, msg in pbar:
820
+ if nf_f:
821
+ samples.append(sample)
822
+ if msg:
823
+ msgs.append(msg)
824
+ nf += nf_f
825
+ nc += nc_f
826
+ pbar.desc = f"{desc} {nf} images, {nc} corrupt"
827
+ pbar.close()
828
+ if msgs:
829
+ LOGGER.info("\n".join(msgs))
830
+ x["hash"] = get_hash([x[0] for x in self.samples])
831
+ x["results"] = nf, nc, len(samples), samples
832
+ x["msgs"] = msgs # warnings
833
+ save_dataset_cache_file(self.prefix, path, x, DATASET_CACHE_VERSION)
834
+ return samples