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,855 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import json
7
+ import random
8
+ import shutil
9
+ from collections import defaultdict
10
+ from concurrent.futures import ThreadPoolExecutor, as_completed
11
+ from pathlib import Path
12
+
13
+ import cv2
14
+ import numpy as np
15
+ from PIL import Image
16
+
17
+ from ultralytics.utils import ASSETS_URL, DATASETS_DIR, LOGGER, NUM_THREADS, TQDM, YAML
18
+ from ultralytics.utils.checks import check_file, check_requirements
19
+ from ultralytics.utils.downloads import download, zip_directory
20
+ from ultralytics.utils.files import increment_path
21
+
22
+
23
+ def coco91_to_coco80_class() -> list[int]:
24
+ """Convert 91-index COCO class IDs to 80-index COCO class IDs.
25
+
26
+ Returns:
27
+ (list[int]): A list of 91 class IDs where the index represents the 80-index class ID and the value is the
28
+ corresponding 91-index class ID.
29
+ """
30
+ return [
31
+ 0,
32
+ 1,
33
+ 2,
34
+ 3,
35
+ 4,
36
+ 5,
37
+ 6,
38
+ 7,
39
+ 8,
40
+ 9,
41
+ 10,
42
+ None,
43
+ 11,
44
+ 12,
45
+ 13,
46
+ 14,
47
+ 15,
48
+ 16,
49
+ 17,
50
+ 18,
51
+ 19,
52
+ 20,
53
+ 21,
54
+ 22,
55
+ 23,
56
+ None,
57
+ 24,
58
+ 25,
59
+ None,
60
+ None,
61
+ 26,
62
+ 27,
63
+ 28,
64
+ 29,
65
+ 30,
66
+ 31,
67
+ 32,
68
+ 33,
69
+ 34,
70
+ 35,
71
+ 36,
72
+ 37,
73
+ 38,
74
+ 39,
75
+ None,
76
+ 40,
77
+ 41,
78
+ 42,
79
+ 43,
80
+ 44,
81
+ 45,
82
+ 46,
83
+ 47,
84
+ 48,
85
+ 49,
86
+ 50,
87
+ 51,
88
+ 52,
89
+ 53,
90
+ 54,
91
+ 55,
92
+ 56,
93
+ 57,
94
+ 58,
95
+ 59,
96
+ None,
97
+ 60,
98
+ None,
99
+ None,
100
+ 61,
101
+ None,
102
+ 62,
103
+ 63,
104
+ 64,
105
+ 65,
106
+ 66,
107
+ 67,
108
+ 68,
109
+ 69,
110
+ 70,
111
+ 71,
112
+ 72,
113
+ None,
114
+ 73,
115
+ 74,
116
+ 75,
117
+ 76,
118
+ 77,
119
+ 78,
120
+ 79,
121
+ None,
122
+ ]
123
+
124
+
125
+ def coco80_to_coco91_class() -> list[int]:
126
+ r"""Convert 80-index (val2014) to 91-index (paper).
127
+
128
+ Returns:
129
+ (list[int]): A list of 80 class IDs where each value is the corresponding 91-index class ID.
130
+
131
+ Examples:
132
+ >>> import numpy as np
133
+ >>> a = np.loadtxt("data/coco.names", dtype="str", delimiter="\n")
134
+ >>> b = np.loadtxt("data/coco_paper.names", dtype="str", delimiter="\n")
135
+
136
+ Convert the darknet to COCO format
137
+ >>> x1 = [list(a[i] == b).index(True) + 1 for i in range(80)]
138
+
139
+ Convert the COCO to darknet format
140
+ >>> x2 = [list(b[i] == a).index(True) if any(b[i] == a) else None for i in range(91)]
141
+
142
+ References:
143
+ https://tech.amikelive.com/node-718/what-object-categories-labels-are-in-coco-dataset/
144
+ """
145
+ return [
146
+ 1,
147
+ 2,
148
+ 3,
149
+ 4,
150
+ 5,
151
+ 6,
152
+ 7,
153
+ 8,
154
+ 9,
155
+ 10,
156
+ 11,
157
+ 13,
158
+ 14,
159
+ 15,
160
+ 16,
161
+ 17,
162
+ 18,
163
+ 19,
164
+ 20,
165
+ 21,
166
+ 22,
167
+ 23,
168
+ 24,
169
+ 25,
170
+ 27,
171
+ 28,
172
+ 31,
173
+ 32,
174
+ 33,
175
+ 34,
176
+ 35,
177
+ 36,
178
+ 37,
179
+ 38,
180
+ 39,
181
+ 40,
182
+ 41,
183
+ 42,
184
+ 43,
185
+ 44,
186
+ 46,
187
+ 47,
188
+ 48,
189
+ 49,
190
+ 50,
191
+ 51,
192
+ 52,
193
+ 53,
194
+ 54,
195
+ 55,
196
+ 56,
197
+ 57,
198
+ 58,
199
+ 59,
200
+ 60,
201
+ 61,
202
+ 62,
203
+ 63,
204
+ 64,
205
+ 65,
206
+ 67,
207
+ 70,
208
+ 72,
209
+ 73,
210
+ 74,
211
+ 75,
212
+ 76,
213
+ 77,
214
+ 78,
215
+ 79,
216
+ 80,
217
+ 81,
218
+ 82,
219
+ 84,
220
+ 85,
221
+ 86,
222
+ 87,
223
+ 88,
224
+ 89,
225
+ 90,
226
+ ]
227
+
228
+
229
+ def convert_coco(
230
+ labels_dir: str = "../coco/annotations/",
231
+ save_dir: str = "coco_converted/",
232
+ use_segments: bool = False,
233
+ use_keypoints: bool = False,
234
+ cls91to80: bool = True,
235
+ lvis: bool = False,
236
+ ):
237
+ """Convert COCO dataset annotations to a YOLO annotation format suitable for training YOLO models.
238
+
239
+ Args:
240
+ labels_dir (str, optional): Path to directory containing COCO dataset annotation files.
241
+ save_dir (str, optional): Path to directory to save results to.
242
+ use_segments (bool, optional): Whether to include segmentation masks in the output.
243
+ use_keypoints (bool, optional): Whether to include keypoint annotations in the output.
244
+ cls91to80 (bool, optional): Whether to map 91 COCO class IDs to the corresponding 80 COCO class IDs.
245
+ lvis (bool, optional): Whether to convert data in lvis dataset way.
246
+
247
+ Examples:
248
+ >>> from ultralytics.data.converter import convert_coco
249
+
250
+ Convert COCO annotations to YOLO format
251
+ >>> convert_coco("coco/annotations/", use_segments=True, use_keypoints=False, cls91to80=False)
252
+
253
+ Convert LVIS annotations to YOLO format
254
+ >>> convert_coco("lvis/annotations/", use_segments=True, use_keypoints=False, cls91to80=False, lvis=True)
255
+ """
256
+ # Create dataset directory
257
+ save_dir = increment_path(save_dir) # increment if save directory already exists
258
+ for p in save_dir / "labels", save_dir / "images":
259
+ p.mkdir(parents=True, exist_ok=True) # make dir
260
+
261
+ # Convert classes
262
+ coco80 = coco91_to_coco80_class()
263
+
264
+ # Import json
265
+ for json_file in sorted(Path(labels_dir).resolve().glob("*.json")):
266
+ lname = "" if lvis else json_file.stem.replace("instances_", "")
267
+ fn = Path(save_dir) / "labels" / lname # folder name
268
+ fn.mkdir(parents=True, exist_ok=True)
269
+ if lvis:
270
+ # NOTE: create folders for both train and val in advance,
271
+ # since LVIS val set contains images from COCO 2017 train in addition to the COCO 2017 val split.
272
+ (fn / "train2017").mkdir(parents=True, exist_ok=True)
273
+ (fn / "val2017").mkdir(parents=True, exist_ok=True)
274
+ with open(json_file, encoding="utf-8") as f:
275
+ data = json.load(f)
276
+
277
+ # Create image dict
278
+ images = {f"{x['id']:d}": x for x in data["images"]}
279
+ # Create image-annotations dict
280
+ annotations = defaultdict(list)
281
+ for ann in data["annotations"]:
282
+ annotations[ann["image_id"]].append(ann)
283
+
284
+ image_txt = []
285
+ # Write labels file
286
+ for img_id, anns in TQDM(annotations.items(), desc=f"Annotations {json_file}"):
287
+ img = images[f"{img_id:d}"]
288
+ h, w = img["height"], img["width"]
289
+ f = str(Path(img["coco_url"]).relative_to("http://images.cocodataset.org")) if lvis else img["file_name"]
290
+ if lvis:
291
+ image_txt.append(str(Path("./images") / f))
292
+
293
+ bboxes = []
294
+ segments = []
295
+ keypoints = []
296
+ for ann in anns:
297
+ if ann.get("iscrowd", False):
298
+ continue
299
+ # The COCO box format is [top left x, top left y, width, height]
300
+ box = np.array(ann["bbox"], dtype=np.float64)
301
+ box[:2] += box[2:] / 2 # xy top-left corner to center
302
+ box[[0, 2]] /= w # normalize x
303
+ box[[1, 3]] /= h # normalize y
304
+ if box[2] <= 0 or box[3] <= 0: # if w <= 0 and h <= 0
305
+ continue
306
+
307
+ cls = coco80[ann["category_id"] - 1] if cls91to80 else ann["category_id"] - 1 # class
308
+ box = [cls, *box.tolist()]
309
+ if box not in bboxes:
310
+ bboxes.append(box)
311
+ if use_segments and ann.get("segmentation") is not None:
312
+ if len(ann["segmentation"]) == 0:
313
+ segments.append([])
314
+ continue
315
+ elif len(ann["segmentation"]) > 1:
316
+ s = merge_multi_segment(ann["segmentation"])
317
+ s = (np.concatenate(s, axis=0) / np.array([w, h])).reshape(-1).tolist()
318
+ else:
319
+ s = [j for i in ann["segmentation"] for j in i] # all segments concatenated
320
+ s = (np.array(s).reshape(-1, 2) / np.array([w, h])).reshape(-1).tolist()
321
+ s = [cls, *s]
322
+ segments.append(s)
323
+ if use_keypoints and ann.get("keypoints") is not None:
324
+ keypoints.append(
325
+ box + (np.array(ann["keypoints"]).reshape(-1, 3) / np.array([w, h, 1])).reshape(-1).tolist()
326
+ )
327
+
328
+ # Write
329
+ with open((fn / f).with_suffix(".txt"), "a", encoding="utf-8") as file:
330
+ for i in range(len(bboxes)):
331
+ if use_keypoints:
332
+ line = (*(keypoints[i]),) # cls, box, keypoints
333
+ else:
334
+ line = (
335
+ *(segments[i] if use_segments and len(segments[i]) > 0 else bboxes[i]),
336
+ ) # cls, box or segments
337
+ file.write(("%g " * len(line)).rstrip() % line + "\n")
338
+
339
+ if lvis:
340
+ filename = Path(save_dir) / json_file.name.replace("lvis_v1_", "").replace(".json", ".txt")
341
+ with open(filename, "a", encoding="utf-8") as f:
342
+ f.writelines(f"{line}\n" for line in image_txt)
343
+
344
+ LOGGER.info(f"{'LVIS' if lvis else 'COCO'} data converted successfully.\nResults saved to {save_dir.resolve()}")
345
+
346
+
347
+ def convert_segment_masks_to_yolo_seg(masks_dir: str, output_dir: str, classes: int):
348
+ """Convert a dataset of segmentation mask images to the YOLO segmentation format.
349
+
350
+ This function takes the directory containing the binary format mask images and converts them into YOLO segmentation
351
+ format. The converted masks are saved in the specified output directory.
352
+
353
+ Args:
354
+ masks_dir (str): The path to the directory where all mask images (png, jpg) are stored.
355
+ output_dir (str): The path to the directory where the converted YOLO segmentation masks will be stored.
356
+ classes (int): Total number of classes in the dataset, e.g., 80 for COCO.
357
+
358
+ Examples:
359
+ >>> from ultralytics.data.converter import convert_segment_masks_to_yolo_seg
360
+
361
+ The classes here is the total classes in the dataset, for COCO dataset we have 80 classes
362
+ >>> convert_segment_masks_to_yolo_seg("path/to/masks_directory", "path/to/output/directory", classes=80)
363
+
364
+ Notes:
365
+ The expected directory structure for the masks is:
366
+
367
+ - masks
368
+ ├─ mask_image_01.png or mask_image_01.jpg
369
+ ├─ mask_image_02.png or mask_image_02.jpg
370
+ ├─ mask_image_03.png or mask_image_03.jpg
371
+ └─ mask_image_04.png or mask_image_04.jpg
372
+
373
+ After execution, the labels will be organized in the following structure:
374
+
375
+ - output_dir
376
+ ├─ mask_yolo_01.txt
377
+ ├─ mask_yolo_02.txt
378
+ ├─ mask_yolo_03.txt
379
+ └─ mask_yolo_04.txt
380
+ """
381
+ pixel_to_class_mapping = {i + 1: i for i in range(classes)}
382
+ for mask_path in Path(masks_dir).iterdir():
383
+ if mask_path.suffix in {".png", ".jpg"}:
384
+ mask = cv2.imread(str(mask_path), cv2.IMREAD_GRAYSCALE) # Read the mask image in grayscale
385
+ img_height, img_width = mask.shape # Get image dimensions
386
+ LOGGER.info(f"Processing {mask_path} imgsz = {img_height} x {img_width}")
387
+
388
+ unique_values = np.unique(mask) # Get unique pixel values representing different classes
389
+ yolo_format_data = []
390
+
391
+ for value in unique_values:
392
+ if value == 0:
393
+ continue # Skip background
394
+ class_index = pixel_to_class_mapping.get(value, -1)
395
+ if class_index == -1:
396
+ LOGGER.warning(f"Unknown class for pixel value {value} in file {mask_path}, skipping.")
397
+ continue
398
+
399
+ # Create a binary mask for the current class and find contours
400
+ contours, _ = cv2.findContours(
401
+ (mask == value).astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
402
+ ) # Find contours
403
+
404
+ for contour in contours:
405
+ if len(contour) >= 3: # YOLO requires at least 3 points for a valid segmentation
406
+ contour = contour.squeeze() # Remove single-dimensional entries
407
+ yolo_format = [class_index]
408
+ for point in contour:
409
+ # Normalize the coordinates
410
+ yolo_format.append(round(point[0] / img_width, 6)) # Rounding to 6 decimal places
411
+ yolo_format.append(round(point[1] / img_height, 6))
412
+ yolo_format_data.append(yolo_format)
413
+ # Save Ultralytics YOLO format data to file
414
+ output_path = Path(output_dir) / f"{mask_path.stem}.txt"
415
+ with open(output_path, "w", encoding="utf-8") as file:
416
+ for item in yolo_format_data:
417
+ line = " ".join(map(str, item))
418
+ file.write(line + "\n")
419
+ LOGGER.info(f"Processed and stored at {output_path} imgsz = {img_height} x {img_width}")
420
+
421
+
422
+ def convert_dota_to_yolo_obb(dota_root_path: str):
423
+ """Convert DOTA dataset annotations to YOLO OBB (Oriented Bounding Box) format.
424
+
425
+ The function processes images in the 'train' and 'val' folders of the DOTA dataset. For each image, it reads the
426
+ associated label from the original labels directory and writes new labels in YOLO OBB format to a new directory.
427
+
428
+ Args:
429
+ dota_root_path (str): The root directory path of the DOTA dataset.
430
+
431
+ Examples:
432
+ >>> from ultralytics.data.converter import convert_dota_to_yolo_obb
433
+ >>> convert_dota_to_yolo_obb("path/to/DOTA")
434
+
435
+ Notes:
436
+ The directory structure assumed for the DOTA dataset:
437
+
438
+ - DOTA
439
+ ├─ images
440
+ │ ├─ train
441
+ │ └─ val
442
+ └─ labels
443
+ ├─ train_original
444
+ └─ val_original
445
+
446
+ After execution, the function will organize the labels into:
447
+
448
+ - DOTA
449
+ └─ labels
450
+ ├─ train
451
+ └─ val
452
+ """
453
+ dota_root_path = Path(dota_root_path)
454
+
455
+ # Class names to indices mapping
456
+ class_mapping = {
457
+ "plane": 0,
458
+ "ship": 1,
459
+ "storage-tank": 2,
460
+ "baseball-diamond": 3,
461
+ "tennis-court": 4,
462
+ "basketball-court": 5,
463
+ "ground-track-field": 6,
464
+ "harbor": 7,
465
+ "bridge": 8,
466
+ "large-vehicle": 9,
467
+ "small-vehicle": 10,
468
+ "helicopter": 11,
469
+ "roundabout": 12,
470
+ "soccer-ball-field": 13,
471
+ "swimming-pool": 14,
472
+ "container-crane": 15,
473
+ "airport": 16,
474
+ "helipad": 17,
475
+ }
476
+
477
+ def convert_label(image_name: str, image_width: int, image_height: int, orig_label_dir: Path, save_dir: Path):
478
+ """Convert a single image's DOTA annotation to YOLO OBB format and save it to a specified directory."""
479
+ orig_label_path = orig_label_dir / f"{image_name}.txt"
480
+ save_path = save_dir / f"{image_name}.txt"
481
+
482
+ with orig_label_path.open("r") as f, save_path.open("w") as g:
483
+ lines = f.readlines()
484
+ for line in lines:
485
+ parts = line.strip().split()
486
+ if len(parts) < 9:
487
+ continue
488
+ class_name = parts[8]
489
+ class_idx = class_mapping[class_name]
490
+ coords = [float(p) for p in parts[:8]]
491
+ normalized_coords = [
492
+ coords[i] / image_width if i % 2 == 0 else coords[i] / image_height for i in range(8)
493
+ ]
494
+ formatted_coords = [f"{coord:.6g}" for coord in normalized_coords]
495
+ g.write(f"{class_idx} {' '.join(formatted_coords)}\n")
496
+
497
+ for phase in {"train", "val"}:
498
+ image_dir = dota_root_path / "images" / phase
499
+ orig_label_dir = dota_root_path / "labels" / f"{phase}_original"
500
+ save_dir = dota_root_path / "labels" / phase
501
+
502
+ save_dir.mkdir(parents=True, exist_ok=True)
503
+
504
+ image_paths = list(image_dir.iterdir())
505
+ for image_path in TQDM(image_paths, desc=f"Processing {phase} images"):
506
+ if image_path.suffix != ".png":
507
+ continue
508
+ image_name_without_ext = image_path.stem
509
+ img = cv2.imread(str(image_path))
510
+ h, w = img.shape[:2]
511
+ convert_label(image_name_without_ext, w, h, orig_label_dir, save_dir)
512
+
513
+
514
+ def min_index(arr1: np.ndarray, arr2: np.ndarray):
515
+ """Find a pair of indexes with the shortest distance between two arrays of 2D points.
516
+
517
+ Args:
518
+ arr1 (np.ndarray): A NumPy array of shape (N, 2) representing N 2D points.
519
+ arr2 (np.ndarray): A NumPy array of shape (M, 2) representing M 2D points.
520
+
521
+ Returns:
522
+ idx1 (int): Index of the point in arr1 with the shortest distance.
523
+ idx2 (int): Index of the point in arr2 with the shortest distance.
524
+ """
525
+ dis = ((arr1[:, None, :] - arr2[None, :, :]) ** 2).sum(-1)
526
+ return np.unravel_index(np.argmin(dis, axis=None), dis.shape)
527
+
528
+
529
+ def merge_multi_segment(segments: list[list]):
530
+ """Merge multiple segments into one list by connecting the coordinates with the minimum distance between each
531
+ segment.
532
+
533
+ This function connects these coordinates with a thin line to merge all segments into one.
534
+
535
+ Args:
536
+ segments (list[list]): Original segmentations in COCO's JSON file. Each element is a list of coordinates, like
537
+ [segmentation1, segmentation2,...].
538
+
539
+ Returns:
540
+ s (list[np.ndarray]): A list of connected segments represented as NumPy arrays.
541
+ """
542
+ s = []
543
+ segments = [np.array(i).reshape(-1, 2) for i in segments]
544
+ idx_list = [[] for _ in range(len(segments))]
545
+
546
+ # Record the indexes with min distance between each segment
547
+ for i in range(1, len(segments)):
548
+ idx1, idx2 = min_index(segments[i - 1], segments[i])
549
+ idx_list[i - 1].append(idx1)
550
+ idx_list[i].append(idx2)
551
+
552
+ # Use two round to connect all the segments
553
+ for k in range(2):
554
+ # Forward connection
555
+ if k == 0:
556
+ for i, idx in enumerate(idx_list):
557
+ # Middle segments have two indexes, reverse the index of middle segments
558
+ if len(idx) == 2 and idx[0] > idx[1]:
559
+ idx = idx[::-1]
560
+ segments[i] = segments[i][::-1, :]
561
+
562
+ segments[i] = np.roll(segments[i], -idx[0], axis=0)
563
+ segments[i] = np.concatenate([segments[i], segments[i][:1]])
564
+ # Deal with the first segment and the last one
565
+ if i in {0, len(idx_list) - 1}:
566
+ s.append(segments[i])
567
+ else:
568
+ idx = [0, idx[1] - idx[0]]
569
+ s.append(segments[i][idx[0] : idx[1] + 1])
570
+
571
+ else:
572
+ for i in range(len(idx_list) - 1, -1, -1):
573
+ if i not in {0, len(idx_list) - 1}:
574
+ idx = idx_list[i]
575
+ nidx = abs(idx[1] - idx[0])
576
+ s.append(segments[i][nidx:])
577
+ return s
578
+
579
+
580
+ def yolo_bbox2segment(im_dir: str | Path, save_dir: str | Path | None = None, sam_model: str = "sam_b.pt", device=None):
581
+ """Convert existing object detection dataset (bounding boxes) to segmentation dataset or oriented bounding box (OBB)
582
+ in YOLO format. Generate segmentation data using SAM auto-annotator as needed.
583
+
584
+ Args:
585
+ im_dir (str | Path): Path to image directory to convert.
586
+ save_dir (str | Path, optional): Path to save the generated labels, labels will be saved into `labels-segment`
587
+ in the same directory level of `im_dir` if save_dir is None.
588
+ sam_model (str): Segmentation model to use for intermediate segmentation data.
589
+ device (int | str, optional): The specific device to run SAM models.
590
+
591
+ Notes:
592
+ The input directory structure assumed for dataset:
593
+
594
+ - im_dir
595
+ ├─ 001.jpg
596
+ ├─ ...
597
+ └─ NNN.jpg
598
+ - labels
599
+ ├─ 001.txt
600
+ ├─ ...
601
+ └─ NNN.txt
602
+ """
603
+ from ultralytics import SAM
604
+ from ultralytics.data import YOLODataset
605
+ from ultralytics.utils.ops import xywh2xyxy
606
+
607
+ # NOTE: add placeholder to pass class index check
608
+ dataset = YOLODataset(im_dir, data=dict(names=list(range(1000)), channels=3))
609
+ if len(dataset.labels[0]["segments"]) > 0: # if it's segment data
610
+ LOGGER.info("Segmentation labels detected, no need to generate new ones!")
611
+ return
612
+
613
+ LOGGER.info("Detection labels detected, generating segment labels by SAM model!")
614
+ sam_model = SAM(sam_model)
615
+ for label in TQDM(dataset.labels, total=len(dataset.labels), desc="Generating segment labels"):
616
+ h, w = label["shape"]
617
+ boxes = label["bboxes"]
618
+ if len(boxes) == 0: # skip empty labels
619
+ continue
620
+ boxes[:, [0, 2]] *= w
621
+ boxes[:, [1, 3]] *= h
622
+ im = cv2.imread(label["im_file"])
623
+ sam_results = sam_model(im, bboxes=xywh2xyxy(boxes), verbose=False, save=False, device=device)
624
+ label["segments"] = sam_results[0].masks.xyn
625
+
626
+ save_dir = Path(save_dir) if save_dir else Path(im_dir).parent / "labels-segment"
627
+ save_dir.mkdir(parents=True, exist_ok=True)
628
+ for label in dataset.labels:
629
+ texts = []
630
+ lb_name = Path(label["im_file"]).with_suffix(".txt").name
631
+ txt_file = save_dir / lb_name
632
+ cls = label["cls"]
633
+ for i, s in enumerate(label["segments"]):
634
+ if len(s) == 0:
635
+ continue
636
+ line = (int(cls[i]), *s.reshape(-1))
637
+ texts.append(("%g " * len(line)).rstrip() % line)
638
+ with open(txt_file, "a", encoding="utf-8") as f:
639
+ f.writelines(text + "\n" for text in texts)
640
+ LOGGER.info(f"Generated segment labels saved in {save_dir}")
641
+
642
+
643
+ def create_synthetic_coco_dataset():
644
+ """Create a synthetic COCO dataset with random images based on filenames from label lists.
645
+
646
+ This function downloads COCO labels, reads image filenames from label list files, creates synthetic images for
647
+ train2017 and val2017 subsets, and organizes them in the COCO dataset structure. It uses multithreading to generate
648
+ images efficiently.
649
+
650
+ Examples:
651
+ >>> from ultralytics.data.converter import create_synthetic_coco_dataset
652
+ >>> create_synthetic_coco_dataset()
653
+
654
+ Notes:
655
+ - Requires internet connection to download label files.
656
+ - Generates random RGB images of varying sizes (480x480 to 640x640 pixels).
657
+ - Existing test2017 directory is removed as it's not needed.
658
+ - Reads image filenames from train2017.txt and val2017.txt files.
659
+ """
660
+
661
+ def create_synthetic_image(image_file: Path):
662
+ """Generate synthetic images with random sizes and colors for dataset augmentation or testing purposes."""
663
+ if not image_file.exists():
664
+ size = (random.randint(480, 640), random.randint(480, 640))
665
+ Image.new(
666
+ "RGB",
667
+ size=size,
668
+ color=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)),
669
+ ).save(image_file)
670
+
671
+ # Download labels
672
+ dir = DATASETS_DIR / "coco"
673
+ download([f"{ASSETS_URL}/coco2017labels-segments.zip"], dir=dir.parent)
674
+
675
+ # Create synthetic images
676
+ shutil.rmtree(dir / "labels" / "test2017", ignore_errors=True) # Remove test2017 directory as not needed
677
+ with ThreadPoolExecutor(max_workers=NUM_THREADS) as executor:
678
+ for subset in {"train2017", "val2017"}:
679
+ subset_dir = dir / "images" / subset
680
+ subset_dir.mkdir(parents=True, exist_ok=True)
681
+
682
+ # Read image filenames from label list file
683
+ label_list_file = dir / f"{subset}.txt"
684
+ if label_list_file.exists():
685
+ with open(label_list_file, encoding="utf-8") as f:
686
+ image_files = [dir / line.strip() for line in f]
687
+
688
+ # Submit all tasks
689
+ futures = [executor.submit(create_synthetic_image, image_file) for image_file in image_files]
690
+ for _ in TQDM(as_completed(futures), total=len(futures), desc=f"Generating images for {subset}"):
691
+ pass # The actual work is done in the background
692
+ else:
693
+ LOGGER.warning(f"Labels file {label_list_file} does not exist. Skipping image creation for {subset}.")
694
+
695
+ LOGGER.info("Synthetic COCO dataset created successfully.")
696
+
697
+
698
+ def convert_to_multispectral(path: str | Path, n_channels: int = 10, replace: bool = False, zip: bool = False):
699
+ """Convert RGB images to multispectral images by interpolating across wavelength bands.
700
+
701
+ This function takes RGB images and interpolates them to create multispectral images with a specified number of
702
+ channels. It can process either a single image or a directory of images.
703
+
704
+ Args:
705
+ path (str | Path): Path to an image file or directory containing images to convert.
706
+ n_channels (int): Number of spectral channels to generate in the output image.
707
+ replace (bool): Whether to replace the original image file with the converted one.
708
+ zip (bool): Whether to zip the converted images into a zip file.
709
+
710
+ Examples:
711
+ Convert a single image
712
+ >>> convert_to_multispectral("path/to/image.jpg", n_channels=10)
713
+
714
+ Convert a dataset
715
+ >>> convert_to_multispectral("coco8", n_channels=10)
716
+ """
717
+ from scipy.interpolate import interp1d
718
+
719
+ from ultralytics.data.utils import IMG_FORMATS
720
+
721
+ path = Path(path)
722
+ if path.is_dir():
723
+ # Process directory
724
+ im_files = [f for ext in (IMG_FORMATS - {"tif", "tiff"}) for f in path.rglob(f"*.{ext}")]
725
+ for im_path in im_files:
726
+ try:
727
+ convert_to_multispectral(im_path, n_channels)
728
+ if replace:
729
+ im_path.unlink()
730
+ except Exception as e:
731
+ LOGGER.info(f"Error converting {im_path}: {e}")
732
+
733
+ if zip:
734
+ zip_directory(path)
735
+ else:
736
+ # Process a single image
737
+ output_path = path.with_suffix(".tiff")
738
+ img = cv2.cvtColor(cv2.imread(str(path)), cv2.COLOR_BGR2RGB)
739
+
740
+ # Interpolate all pixels at once
741
+ rgb_wavelengths = np.array([650, 510, 475]) # R, G, B wavelengths (nm)
742
+ target_wavelengths = np.linspace(450, 700, n_channels)
743
+ f = interp1d(rgb_wavelengths.T, img, kind="linear", bounds_error=False, fill_value="extrapolate")
744
+ multispectral = f(target_wavelengths)
745
+ cv2.imwritemulti(str(output_path), np.clip(multispectral, 0, 255).astype(np.uint8).transpose(2, 0, 1))
746
+ LOGGER.info(f"Converted {output_path}")
747
+
748
+
749
+ async def convert_ndjson_to_yolo(ndjson_path: str | Path, output_path: str | Path | None = None) -> Path:
750
+ """Convert NDJSON dataset format to Ultralytics YOLO11 dataset structure.
751
+
752
+ This function converts datasets stored in NDJSON (Newline Delimited JSON) format to the standard YOLO format with
753
+ separate directories for images and labels. It supports parallel processing for efficient conversion of large
754
+ datasets and can download images from URLs if they don't exist locally.
755
+
756
+ The NDJSON format consists of:
757
+ - First line: Dataset metadata with class names and configuration
758
+ - Subsequent lines: Individual image records with annotations and optional URLs
759
+
760
+ Args:
761
+ ndjson_path (Union[str, Path]): Path to the input NDJSON file containing dataset information.
762
+ output_path (Optional[Union[str, Path]], optional): Directory where the converted YOLO dataset will be saved. If
763
+ None, uses the parent directory of the NDJSON file. Defaults to None.
764
+
765
+ Returns:
766
+ (Path): Path to the generated data.yaml file that can be used for YOLO training.
767
+
768
+ Examples:
769
+ Convert a local NDJSON file:
770
+ >>> yaml_path = convert_ndjson_to_yolo("dataset.ndjson")
771
+ >>> print(f"Dataset converted to: {yaml_path}")
772
+
773
+ Convert with custom output directory:
774
+ >>> yaml_path = convert_ndjson_to_yolo("dataset.ndjson", output_path="./converted_datasets")
775
+
776
+ Use with YOLO training
777
+ >>> from ultralytics import YOLO
778
+ >>> model = YOLO("yolo11n.pt")
779
+ >>> model.train(data="https://github.com/ultralytics/assets/releases/download/v0.0.0/coco8-ndjson.ndjson")
780
+ """
781
+ check_requirements("aiohttp")
782
+ import aiohttp
783
+
784
+ ndjson_path = Path(check_file(ndjson_path))
785
+ output_path = Path(output_path or DATASETS_DIR)
786
+ with open(ndjson_path) as f:
787
+ lines = [json.loads(line.strip()) for line in f if line.strip()]
788
+
789
+ dataset_record, image_records = lines[0], lines[1:]
790
+ dataset_dir = output_path / ndjson_path.stem
791
+ splits = {record["split"] for record in image_records}
792
+
793
+ # Create directories and prepare YAML structure
794
+ dataset_dir.mkdir(parents=True, exist_ok=True)
795
+ data_yaml = dict(dataset_record)
796
+ data_yaml["names"] = {int(k): v for k, v in dataset_record.get("class_names", {}).items()}
797
+ data_yaml.pop("class_names")
798
+
799
+ for split in sorted(splits):
800
+ (dataset_dir / "images" / split).mkdir(parents=True, exist_ok=True)
801
+ (dataset_dir / "labels" / split).mkdir(parents=True, exist_ok=True)
802
+ data_yaml[split] = f"images/{split}"
803
+
804
+ async def process_record(session, semaphore, record):
805
+ """Process single image record with async session."""
806
+ async with semaphore:
807
+ split, original_name = record["split"], record["file"]
808
+ label_path = dataset_dir / "labels" / split / f"{Path(original_name).stem}.txt"
809
+ image_path = dataset_dir / "images" / split / original_name
810
+
811
+ annotations = record.get("annotations", {})
812
+ lines_to_write = []
813
+ for key in annotations.keys():
814
+ lines_to_write = [" ".join(map(str, item)) for item in annotations[key]]
815
+ break
816
+ if "classification" in annotations:
817
+ lines_to_write = [str(cls) for cls in annotations["classification"]]
818
+
819
+ label_path.write_text("\n".join(lines_to_write) + "\n" if lines_to_write else "")
820
+
821
+ if http_url := record.get("url"):
822
+ if not image_path.exists():
823
+ try:
824
+ async with session.get(http_url, timeout=aiohttp.ClientTimeout(total=30)) as response:
825
+ response.raise_for_status()
826
+ with open(image_path, "wb") as f:
827
+ async for chunk in response.content.iter_chunked(8192):
828
+ f.write(chunk)
829
+ return True
830
+ except Exception as e:
831
+ LOGGER.warning(f"Failed to download {http_url}: {e}")
832
+ return False
833
+ return True
834
+
835
+ # Process all images with async downloads
836
+ semaphore = asyncio.Semaphore(64)
837
+ async with aiohttp.ClientSession() as session:
838
+ pbar = TQDM(
839
+ total=len(image_records),
840
+ desc=f"Converting {ndjson_path.name} → {dataset_dir} ({len(image_records)} images)",
841
+ )
842
+
843
+ async def tracked_process(record):
844
+ result = await process_record(session, semaphore, record)
845
+ pbar.update(1)
846
+ return result
847
+
848
+ await asyncio.gather(*[tracked_process(record) for record in image_records])
849
+ pbar.close()
850
+
851
+ # Write data.yaml
852
+ yaml_path = dataset_dir / "data.yaml"
853
+ YAML.save(yaml_path, data_yaml)
854
+
855
+ return yaml_path