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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (272) hide show
  1. dgenerate_ultralytics_headless-8.3.134.dist-info/METADATA +400 -0
  2. dgenerate_ultralytics_headless-8.3.134.dist-info/RECORD +272 -0
  3. dgenerate_ultralytics_headless-8.3.134.dist-info/WHEEL +5 -0
  4. dgenerate_ultralytics_headless-8.3.134.dist-info/entry_points.txt +3 -0
  5. dgenerate_ultralytics_headless-8.3.134.dist-info/licenses/LICENSE +661 -0
  6. dgenerate_ultralytics_headless-8.3.134.dist-info/top_level.txt +1 -0
  7. tests/__init__.py +22 -0
  8. tests/conftest.py +83 -0
  9. tests/test_cli.py +138 -0
  10. tests/test_cuda.py +215 -0
  11. tests/test_engine.py +131 -0
  12. tests/test_exports.py +236 -0
  13. tests/test_integrations.py +154 -0
  14. tests/test_python.py +694 -0
  15. tests/test_solutions.py +187 -0
  16. ultralytics/__init__.py +30 -0
  17. ultralytics/assets/bus.jpg +0 -0
  18. ultralytics/assets/zidane.jpg +0 -0
  19. ultralytics/cfg/__init__.py +1023 -0
  20. ultralytics/cfg/datasets/Argoverse.yaml +77 -0
  21. ultralytics/cfg/datasets/DOTAv1.5.yaml +37 -0
  22. ultralytics/cfg/datasets/DOTAv1.yaml +36 -0
  23. ultralytics/cfg/datasets/GlobalWheat2020.yaml +68 -0
  24. ultralytics/cfg/datasets/HomeObjects-3K.yaml +33 -0
  25. ultralytics/cfg/datasets/ImageNet.yaml +2025 -0
  26. ultralytics/cfg/datasets/Objects365.yaml +443 -0
  27. ultralytics/cfg/datasets/SKU-110K.yaml +58 -0
  28. ultralytics/cfg/datasets/VOC.yaml +106 -0
  29. ultralytics/cfg/datasets/VisDrone.yaml +77 -0
  30. ultralytics/cfg/datasets/african-wildlife.yaml +25 -0
  31. ultralytics/cfg/datasets/brain-tumor.yaml +23 -0
  32. ultralytics/cfg/datasets/carparts-seg.yaml +44 -0
  33. ultralytics/cfg/datasets/coco-pose.yaml +42 -0
  34. ultralytics/cfg/datasets/coco.yaml +118 -0
  35. ultralytics/cfg/datasets/coco128-seg.yaml +101 -0
  36. ultralytics/cfg/datasets/coco128.yaml +101 -0
  37. ultralytics/cfg/datasets/coco8-multispectral.yaml +104 -0
  38. ultralytics/cfg/datasets/coco8-pose.yaml +26 -0
  39. ultralytics/cfg/datasets/coco8-seg.yaml +101 -0
  40. ultralytics/cfg/datasets/coco8.yaml +101 -0
  41. ultralytics/cfg/datasets/crack-seg.yaml +22 -0
  42. ultralytics/cfg/datasets/dog-pose.yaml +24 -0
  43. ultralytics/cfg/datasets/dota8-multispectral.yaml +38 -0
  44. ultralytics/cfg/datasets/dota8.yaml +35 -0
  45. ultralytics/cfg/datasets/hand-keypoints.yaml +26 -0
  46. ultralytics/cfg/datasets/lvis.yaml +1240 -0
  47. ultralytics/cfg/datasets/medical-pills.yaml +22 -0
  48. ultralytics/cfg/datasets/open-images-v7.yaml +666 -0
  49. ultralytics/cfg/datasets/package-seg.yaml +22 -0
  50. ultralytics/cfg/datasets/signature.yaml +21 -0
  51. ultralytics/cfg/datasets/tiger-pose.yaml +25 -0
  52. ultralytics/cfg/datasets/xView.yaml +155 -0
  53. ultralytics/cfg/default.yaml +127 -0
  54. ultralytics/cfg/models/11/yolo11-cls-resnet18.yaml +17 -0
  55. ultralytics/cfg/models/11/yolo11-cls.yaml +33 -0
  56. ultralytics/cfg/models/11/yolo11-obb.yaml +50 -0
  57. ultralytics/cfg/models/11/yolo11-pose.yaml +51 -0
  58. ultralytics/cfg/models/11/yolo11-seg.yaml +50 -0
  59. ultralytics/cfg/models/11/yolo11.yaml +50 -0
  60. ultralytics/cfg/models/11/yoloe-11-seg.yaml +48 -0
  61. ultralytics/cfg/models/11/yoloe-11.yaml +48 -0
  62. ultralytics/cfg/models/12/yolo12-cls.yaml +32 -0
  63. ultralytics/cfg/models/12/yolo12-obb.yaml +48 -0
  64. ultralytics/cfg/models/12/yolo12-pose.yaml +49 -0
  65. ultralytics/cfg/models/12/yolo12-seg.yaml +48 -0
  66. ultralytics/cfg/models/12/yolo12.yaml +48 -0
  67. ultralytics/cfg/models/rt-detr/rtdetr-l.yaml +53 -0
  68. ultralytics/cfg/models/rt-detr/rtdetr-resnet101.yaml +45 -0
  69. ultralytics/cfg/models/rt-detr/rtdetr-resnet50.yaml +45 -0
  70. ultralytics/cfg/models/rt-detr/rtdetr-x.yaml +57 -0
  71. ultralytics/cfg/models/v10/yolov10b.yaml +45 -0
  72. ultralytics/cfg/models/v10/yolov10l.yaml +45 -0
  73. ultralytics/cfg/models/v10/yolov10m.yaml +45 -0
  74. ultralytics/cfg/models/v10/yolov10n.yaml +45 -0
  75. ultralytics/cfg/models/v10/yolov10s.yaml +45 -0
  76. ultralytics/cfg/models/v10/yolov10x.yaml +45 -0
  77. ultralytics/cfg/models/v3/yolov3-spp.yaml +49 -0
  78. ultralytics/cfg/models/v3/yolov3-tiny.yaml +40 -0
  79. ultralytics/cfg/models/v3/yolov3.yaml +49 -0
  80. ultralytics/cfg/models/v5/yolov5-p6.yaml +62 -0
  81. ultralytics/cfg/models/v5/yolov5.yaml +51 -0
  82. ultralytics/cfg/models/v6/yolov6.yaml +56 -0
  83. ultralytics/cfg/models/v8/yoloe-v8-seg.yaml +45 -0
  84. ultralytics/cfg/models/v8/yoloe-v8.yaml +45 -0
  85. ultralytics/cfg/models/v8/yolov8-cls-resnet101.yaml +28 -0
  86. ultralytics/cfg/models/v8/yolov8-cls-resnet50.yaml +28 -0
  87. ultralytics/cfg/models/v8/yolov8-cls.yaml +32 -0
  88. ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml +58 -0
  89. ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml +60 -0
  90. ultralytics/cfg/models/v8/yolov8-ghost.yaml +50 -0
  91. ultralytics/cfg/models/v8/yolov8-obb.yaml +49 -0
  92. ultralytics/cfg/models/v8/yolov8-p2.yaml +57 -0
  93. ultralytics/cfg/models/v8/yolov8-p6.yaml +59 -0
  94. ultralytics/cfg/models/v8/yolov8-pose-p6.yaml +60 -0
  95. ultralytics/cfg/models/v8/yolov8-pose.yaml +50 -0
  96. ultralytics/cfg/models/v8/yolov8-rtdetr.yaml +49 -0
  97. ultralytics/cfg/models/v8/yolov8-seg-p6.yaml +59 -0
  98. ultralytics/cfg/models/v8/yolov8-seg.yaml +49 -0
  99. ultralytics/cfg/models/v8/yolov8-world.yaml +51 -0
  100. ultralytics/cfg/models/v8/yolov8-worldv2.yaml +49 -0
  101. ultralytics/cfg/models/v8/yolov8.yaml +49 -0
  102. ultralytics/cfg/models/v9/yolov9c-seg.yaml +41 -0
  103. ultralytics/cfg/models/v9/yolov9c.yaml +41 -0
  104. ultralytics/cfg/models/v9/yolov9e-seg.yaml +64 -0
  105. ultralytics/cfg/models/v9/yolov9e.yaml +64 -0
  106. ultralytics/cfg/models/v9/yolov9m.yaml +41 -0
  107. ultralytics/cfg/models/v9/yolov9s.yaml +41 -0
  108. ultralytics/cfg/models/v9/yolov9t.yaml +41 -0
  109. ultralytics/cfg/trackers/botsort.yaml +22 -0
  110. ultralytics/cfg/trackers/bytetrack.yaml +14 -0
  111. ultralytics/data/__init__.py +26 -0
  112. ultralytics/data/annotator.py +66 -0
  113. ultralytics/data/augment.py +2945 -0
  114. ultralytics/data/base.py +438 -0
  115. ultralytics/data/build.py +258 -0
  116. ultralytics/data/converter.py +754 -0
  117. ultralytics/data/dataset.py +834 -0
  118. ultralytics/data/loaders.py +676 -0
  119. ultralytics/data/scripts/download_weights.sh +18 -0
  120. ultralytics/data/scripts/get_coco.sh +61 -0
  121. ultralytics/data/scripts/get_coco128.sh +18 -0
  122. ultralytics/data/scripts/get_imagenet.sh +52 -0
  123. ultralytics/data/split.py +125 -0
  124. ultralytics/data/split_dota.py +325 -0
  125. ultralytics/data/utils.py +777 -0
  126. ultralytics/engine/__init__.py +1 -0
  127. ultralytics/engine/exporter.py +1519 -0
  128. ultralytics/engine/model.py +1156 -0
  129. ultralytics/engine/predictor.py +502 -0
  130. ultralytics/engine/results.py +1840 -0
  131. ultralytics/engine/trainer.py +853 -0
  132. ultralytics/engine/tuner.py +243 -0
  133. ultralytics/engine/validator.py +377 -0
  134. ultralytics/hub/__init__.py +168 -0
  135. ultralytics/hub/auth.py +137 -0
  136. ultralytics/hub/google/__init__.py +176 -0
  137. ultralytics/hub/session.py +446 -0
  138. ultralytics/hub/utils.py +248 -0
  139. ultralytics/models/__init__.py +9 -0
  140. ultralytics/models/fastsam/__init__.py +7 -0
  141. ultralytics/models/fastsam/model.py +61 -0
  142. ultralytics/models/fastsam/predict.py +181 -0
  143. ultralytics/models/fastsam/utils.py +24 -0
  144. ultralytics/models/fastsam/val.py +40 -0
  145. ultralytics/models/nas/__init__.py +7 -0
  146. ultralytics/models/nas/model.py +102 -0
  147. ultralytics/models/nas/predict.py +58 -0
  148. ultralytics/models/nas/val.py +39 -0
  149. ultralytics/models/rtdetr/__init__.py +7 -0
  150. ultralytics/models/rtdetr/model.py +63 -0
  151. ultralytics/models/rtdetr/predict.py +84 -0
  152. ultralytics/models/rtdetr/train.py +85 -0
  153. ultralytics/models/rtdetr/val.py +191 -0
  154. ultralytics/models/sam/__init__.py +6 -0
  155. ultralytics/models/sam/amg.py +260 -0
  156. ultralytics/models/sam/build.py +358 -0
  157. ultralytics/models/sam/model.py +170 -0
  158. ultralytics/models/sam/modules/__init__.py +1 -0
  159. ultralytics/models/sam/modules/blocks.py +1129 -0
  160. ultralytics/models/sam/modules/decoders.py +515 -0
  161. ultralytics/models/sam/modules/encoders.py +854 -0
  162. ultralytics/models/sam/modules/memory_attention.py +299 -0
  163. ultralytics/models/sam/modules/sam.py +1006 -0
  164. ultralytics/models/sam/modules/tiny_encoder.py +1002 -0
  165. ultralytics/models/sam/modules/transformer.py +351 -0
  166. ultralytics/models/sam/modules/utils.py +394 -0
  167. ultralytics/models/sam/predict.py +1605 -0
  168. ultralytics/models/utils/__init__.py +1 -0
  169. ultralytics/models/utils/loss.py +455 -0
  170. ultralytics/models/utils/ops.py +268 -0
  171. ultralytics/models/yolo/__init__.py +7 -0
  172. ultralytics/models/yolo/classify/__init__.py +7 -0
  173. ultralytics/models/yolo/classify/predict.py +88 -0
  174. ultralytics/models/yolo/classify/train.py +233 -0
  175. ultralytics/models/yolo/classify/val.py +215 -0
  176. ultralytics/models/yolo/detect/__init__.py +7 -0
  177. ultralytics/models/yolo/detect/predict.py +124 -0
  178. ultralytics/models/yolo/detect/train.py +217 -0
  179. ultralytics/models/yolo/detect/val.py +451 -0
  180. ultralytics/models/yolo/model.py +354 -0
  181. ultralytics/models/yolo/obb/__init__.py +7 -0
  182. ultralytics/models/yolo/obb/predict.py +66 -0
  183. ultralytics/models/yolo/obb/train.py +81 -0
  184. ultralytics/models/yolo/obb/val.py +283 -0
  185. ultralytics/models/yolo/pose/__init__.py +7 -0
  186. ultralytics/models/yolo/pose/predict.py +79 -0
  187. ultralytics/models/yolo/pose/train.py +154 -0
  188. ultralytics/models/yolo/pose/val.py +394 -0
  189. ultralytics/models/yolo/segment/__init__.py +7 -0
  190. ultralytics/models/yolo/segment/predict.py +113 -0
  191. ultralytics/models/yolo/segment/train.py +123 -0
  192. ultralytics/models/yolo/segment/val.py +428 -0
  193. ultralytics/models/yolo/world/__init__.py +5 -0
  194. ultralytics/models/yolo/world/train.py +119 -0
  195. ultralytics/models/yolo/world/train_world.py +176 -0
  196. ultralytics/models/yolo/yoloe/__init__.py +22 -0
  197. ultralytics/models/yolo/yoloe/predict.py +169 -0
  198. ultralytics/models/yolo/yoloe/train.py +298 -0
  199. ultralytics/models/yolo/yoloe/train_seg.py +124 -0
  200. ultralytics/models/yolo/yoloe/val.py +191 -0
  201. ultralytics/nn/__init__.py +29 -0
  202. ultralytics/nn/autobackend.py +842 -0
  203. ultralytics/nn/modules/__init__.py +182 -0
  204. ultralytics/nn/modules/activation.py +53 -0
  205. ultralytics/nn/modules/block.py +1966 -0
  206. ultralytics/nn/modules/conv.py +712 -0
  207. ultralytics/nn/modules/head.py +880 -0
  208. ultralytics/nn/modules/transformer.py +713 -0
  209. ultralytics/nn/modules/utils.py +164 -0
  210. ultralytics/nn/tasks.py +1627 -0
  211. ultralytics/nn/text_model.py +351 -0
  212. ultralytics/solutions/__init__.py +41 -0
  213. ultralytics/solutions/ai_gym.py +116 -0
  214. ultralytics/solutions/analytics.py +252 -0
  215. ultralytics/solutions/config.py +106 -0
  216. ultralytics/solutions/distance_calculation.py +124 -0
  217. ultralytics/solutions/heatmap.py +127 -0
  218. ultralytics/solutions/instance_segmentation.py +84 -0
  219. ultralytics/solutions/object_blurrer.py +90 -0
  220. ultralytics/solutions/object_counter.py +195 -0
  221. ultralytics/solutions/object_cropper.py +84 -0
  222. ultralytics/solutions/parking_management.py +273 -0
  223. ultralytics/solutions/queue_management.py +93 -0
  224. ultralytics/solutions/region_counter.py +120 -0
  225. ultralytics/solutions/security_alarm.py +154 -0
  226. ultralytics/solutions/similarity_search.py +172 -0
  227. ultralytics/solutions/solutions.py +724 -0
  228. ultralytics/solutions/speed_estimation.py +110 -0
  229. ultralytics/solutions/streamlit_inference.py +196 -0
  230. ultralytics/solutions/templates/similarity-search.html +160 -0
  231. ultralytics/solutions/trackzone.py +88 -0
  232. ultralytics/solutions/vision_eye.py +68 -0
  233. ultralytics/trackers/__init__.py +7 -0
  234. ultralytics/trackers/basetrack.py +124 -0
  235. ultralytics/trackers/bot_sort.py +260 -0
  236. ultralytics/trackers/byte_tracker.py +480 -0
  237. ultralytics/trackers/track.py +125 -0
  238. ultralytics/trackers/utils/__init__.py +1 -0
  239. ultralytics/trackers/utils/gmc.py +376 -0
  240. ultralytics/trackers/utils/kalman_filter.py +493 -0
  241. ultralytics/trackers/utils/matching.py +157 -0
  242. ultralytics/utils/__init__.py +1435 -0
  243. ultralytics/utils/autobatch.py +106 -0
  244. ultralytics/utils/autodevice.py +174 -0
  245. ultralytics/utils/benchmarks.py +695 -0
  246. ultralytics/utils/callbacks/__init__.py +5 -0
  247. ultralytics/utils/callbacks/base.py +234 -0
  248. ultralytics/utils/callbacks/clearml.py +153 -0
  249. ultralytics/utils/callbacks/comet.py +552 -0
  250. ultralytics/utils/callbacks/dvc.py +205 -0
  251. ultralytics/utils/callbacks/hub.py +108 -0
  252. ultralytics/utils/callbacks/mlflow.py +138 -0
  253. ultralytics/utils/callbacks/neptune.py +140 -0
  254. ultralytics/utils/callbacks/raytune.py +43 -0
  255. ultralytics/utils/callbacks/tensorboard.py +132 -0
  256. ultralytics/utils/callbacks/wb.py +185 -0
  257. ultralytics/utils/checks.py +897 -0
  258. ultralytics/utils/dist.py +119 -0
  259. ultralytics/utils/downloads.py +499 -0
  260. ultralytics/utils/errors.py +43 -0
  261. ultralytics/utils/export.py +219 -0
  262. ultralytics/utils/files.py +221 -0
  263. ultralytics/utils/instance.py +499 -0
  264. ultralytics/utils/loss.py +813 -0
  265. ultralytics/utils/metrics.py +1356 -0
  266. ultralytics/utils/ops.py +885 -0
  267. ultralytics/utils/patches.py +143 -0
  268. ultralytics/utils/plotting.py +1011 -0
  269. ultralytics/utils/tal.py +416 -0
  270. ultralytics/utils/torch_utils.py +990 -0
  271. ultralytics/utils/triton.py +116 -0
  272. ultralytics/utils/tuner.py +159 -0
@@ -0,0 +1,754 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ import json
4
+ import random
5
+ import shutil
6
+ from collections import defaultdict
7
+ from concurrent.futures import ThreadPoolExecutor, as_completed
8
+ from pathlib import Path
9
+
10
+ import cv2
11
+ import numpy as np
12
+ from PIL import Image
13
+
14
+ from ultralytics.utils import DATASETS_DIR, LOGGER, NUM_THREADS, TQDM
15
+ from ultralytics.utils.downloads import download, zip_directory
16
+ from ultralytics.utils.files import increment_path
17
+
18
+
19
+ def coco91_to_coco80_class():
20
+ """
21
+ Converts 91-index COCO class IDs to 80-index COCO class IDs.
22
+
23
+ Returns:
24
+ (list): A list of 91 class IDs where the index represents the 80-index class ID and the value is the
25
+ corresponding 91-index class ID.
26
+ """
27
+ return [
28
+ 0,
29
+ 1,
30
+ 2,
31
+ 3,
32
+ 4,
33
+ 5,
34
+ 6,
35
+ 7,
36
+ 8,
37
+ 9,
38
+ 10,
39
+ None,
40
+ 11,
41
+ 12,
42
+ 13,
43
+ 14,
44
+ 15,
45
+ 16,
46
+ 17,
47
+ 18,
48
+ 19,
49
+ 20,
50
+ 21,
51
+ 22,
52
+ 23,
53
+ None,
54
+ 24,
55
+ 25,
56
+ None,
57
+ None,
58
+ 26,
59
+ 27,
60
+ 28,
61
+ 29,
62
+ 30,
63
+ 31,
64
+ 32,
65
+ 33,
66
+ 34,
67
+ 35,
68
+ 36,
69
+ 37,
70
+ 38,
71
+ 39,
72
+ None,
73
+ 40,
74
+ 41,
75
+ 42,
76
+ 43,
77
+ 44,
78
+ 45,
79
+ 46,
80
+ 47,
81
+ 48,
82
+ 49,
83
+ 50,
84
+ 51,
85
+ 52,
86
+ 53,
87
+ 54,
88
+ 55,
89
+ 56,
90
+ 57,
91
+ 58,
92
+ 59,
93
+ None,
94
+ 60,
95
+ None,
96
+ None,
97
+ 61,
98
+ None,
99
+ 62,
100
+ 63,
101
+ 64,
102
+ 65,
103
+ 66,
104
+ 67,
105
+ 68,
106
+ 69,
107
+ 70,
108
+ 71,
109
+ 72,
110
+ None,
111
+ 73,
112
+ 74,
113
+ 75,
114
+ 76,
115
+ 77,
116
+ 78,
117
+ 79,
118
+ None,
119
+ ]
120
+
121
+
122
+ def coco80_to_coco91_class():
123
+ r"""
124
+ Converts 80-index (val2014) to 91-index (paper).
125
+ For details see https://tech.amikelive.com/node-718/what-object-categories-labels-are-in-coco-dataset/.
126
+
127
+ Examples:
128
+ >>> import numpy as np
129
+ >>> a = np.loadtxt("data/coco.names", dtype="str", delimiter="\n")
130
+ >>> b = np.loadtxt("data/coco_paper.names", dtype="str", delimiter="\n")
131
+
132
+ Convert the darknet to COCO format
133
+ >>> x1 = [list(a[i] == b).index(True) + 1 for i in range(80)]
134
+
135
+ Convert the COCO to darknet format
136
+ >>> x2 = [list(b[i] == a).index(True) if any(b[i] == a) else None for i in range(91)]
137
+ """
138
+ return [
139
+ 1,
140
+ 2,
141
+ 3,
142
+ 4,
143
+ 5,
144
+ 6,
145
+ 7,
146
+ 8,
147
+ 9,
148
+ 10,
149
+ 11,
150
+ 13,
151
+ 14,
152
+ 15,
153
+ 16,
154
+ 17,
155
+ 18,
156
+ 19,
157
+ 20,
158
+ 21,
159
+ 22,
160
+ 23,
161
+ 24,
162
+ 25,
163
+ 27,
164
+ 28,
165
+ 31,
166
+ 32,
167
+ 33,
168
+ 34,
169
+ 35,
170
+ 36,
171
+ 37,
172
+ 38,
173
+ 39,
174
+ 40,
175
+ 41,
176
+ 42,
177
+ 43,
178
+ 44,
179
+ 46,
180
+ 47,
181
+ 48,
182
+ 49,
183
+ 50,
184
+ 51,
185
+ 52,
186
+ 53,
187
+ 54,
188
+ 55,
189
+ 56,
190
+ 57,
191
+ 58,
192
+ 59,
193
+ 60,
194
+ 61,
195
+ 62,
196
+ 63,
197
+ 64,
198
+ 65,
199
+ 67,
200
+ 70,
201
+ 72,
202
+ 73,
203
+ 74,
204
+ 75,
205
+ 76,
206
+ 77,
207
+ 78,
208
+ 79,
209
+ 80,
210
+ 81,
211
+ 82,
212
+ 84,
213
+ 85,
214
+ 86,
215
+ 87,
216
+ 88,
217
+ 89,
218
+ 90,
219
+ ]
220
+
221
+
222
+ def convert_coco(
223
+ labels_dir="../coco/annotations/",
224
+ save_dir="coco_converted/",
225
+ use_segments=False,
226
+ use_keypoints=False,
227
+ cls91to80=True,
228
+ lvis=False,
229
+ ):
230
+ """
231
+ Converts COCO dataset annotations to a YOLO annotation format suitable for training YOLO models.
232
+
233
+ Args:
234
+ labels_dir (str, optional): Path to directory containing COCO dataset annotation files.
235
+ save_dir (str, optional): Path to directory to save results to.
236
+ use_segments (bool, optional): Whether to include segmentation masks in the output.
237
+ use_keypoints (bool, optional): Whether to include keypoint annotations in the output.
238
+ cls91to80 (bool, optional): Whether to map 91 COCO class IDs to the corresponding 80 COCO class IDs.
239
+ lvis (bool, optional): Whether to convert data in lvis dataset way.
240
+
241
+ Examples:
242
+ >>> from ultralytics.data.converter import convert_coco
243
+
244
+ Convert COCO annotations to YOLO format
245
+ >>> convert_coco("../datasets/coco/annotations/", use_segments=True, use_keypoints=False, cls91to80=False)
246
+
247
+ Convert LVIS annotations to YOLO format
248
+ >>> convert_coco(
249
+ >>> "../datasets/lvis/annotations/",
250
+ ... use_segments=True,
251
+ ... use_keypoints=False,
252
+ ... cls91to80=False,
253
+ ... lvis=True
254
+ ... )
255
+
256
+ Output:
257
+ Generates output files in the specified output directory.
258
+ """
259
+ # Create dataset directory
260
+ save_dir = increment_path(save_dir) # increment if save directory already exists
261
+ for p in save_dir / "labels", save_dir / "images":
262
+ p.mkdir(parents=True, exist_ok=True) # make dir
263
+
264
+ # Convert classes
265
+ coco80 = coco91_to_coco80_class()
266
+
267
+ # Import json
268
+ for json_file in sorted(Path(labels_dir).resolve().glob("*.json")):
269
+ lname = "" if lvis else json_file.stem.replace("instances_", "")
270
+ fn = Path(save_dir) / "labels" / lname # folder name
271
+ fn.mkdir(parents=True, exist_ok=True)
272
+ if lvis:
273
+ # NOTE: create folders for both train and val in advance,
274
+ # since LVIS val set contains images from COCO 2017 train in addition to the COCO 2017 val split.
275
+ (fn / "train2017").mkdir(parents=True, exist_ok=True)
276
+ (fn / "val2017").mkdir(parents=True, exist_ok=True)
277
+ with open(json_file, encoding="utf-8") as f:
278
+ data = json.load(f)
279
+
280
+ # Create image dict
281
+ images = {f"{x['id']:d}": x for x in data["images"]}
282
+ # Create image-annotations dict
283
+ annotations = defaultdict(list)
284
+ for ann in data["annotations"]:
285
+ annotations[ann["image_id"]].append(ann)
286
+
287
+ image_txt = []
288
+ # Write labels file
289
+ for img_id, anns in TQDM(annotations.items(), desc=f"Annotations {json_file}"):
290
+ img = images[f"{img_id:d}"]
291
+ h, w = img["height"], img["width"]
292
+ f = str(Path(img["coco_url"]).relative_to("http://images.cocodataset.org")) if lvis else img["file_name"]
293
+ if lvis:
294
+ image_txt.append(str(Path("./images") / f))
295
+
296
+ bboxes = []
297
+ segments = []
298
+ keypoints = []
299
+ for ann in anns:
300
+ if ann.get("iscrowd", False):
301
+ continue
302
+ # The COCO box format is [top left x, top left y, width, height]
303
+ box = np.array(ann["bbox"], dtype=np.float64)
304
+ box[:2] += box[2:] / 2 # xy top-left corner to center
305
+ box[[0, 2]] /= w # normalize x
306
+ box[[1, 3]] /= h # normalize y
307
+ if box[2] <= 0 or box[3] <= 0: # if w <= 0 and h <= 0
308
+ continue
309
+
310
+ cls = coco80[ann["category_id"] - 1] if cls91to80 else ann["category_id"] - 1 # class
311
+ box = [cls] + box.tolist()
312
+ if box not in bboxes:
313
+ bboxes.append(box)
314
+ if use_segments and ann.get("segmentation") is not None:
315
+ if len(ann["segmentation"]) == 0:
316
+ segments.append([])
317
+ continue
318
+ elif len(ann["segmentation"]) > 1:
319
+ s = merge_multi_segment(ann["segmentation"])
320
+ s = (np.concatenate(s, axis=0) / np.array([w, h])).reshape(-1).tolist()
321
+ else:
322
+ s = [j for i in ann["segmentation"] for j in i] # all segments concatenated
323
+ s = (np.array(s).reshape(-1, 2) / np.array([w, h])).reshape(-1).tolist()
324
+ s = [cls] + s
325
+ segments.append(s)
326
+ if use_keypoints and ann.get("keypoints") is not None:
327
+ keypoints.append(
328
+ box + (np.array(ann["keypoints"]).reshape(-1, 3) / np.array([w, h, 1])).reshape(-1).tolist()
329
+ )
330
+
331
+ # Write
332
+ with open((fn / f).with_suffix(".txt"), "a", encoding="utf-8") as file:
333
+ for i in range(len(bboxes)):
334
+ if use_keypoints:
335
+ line = (*(keypoints[i]),) # cls, box, keypoints
336
+ else:
337
+ line = (
338
+ *(segments[i] if use_segments and len(segments[i]) > 0 else bboxes[i]),
339
+ ) # cls, box or segments
340
+ file.write(("%g " * len(line)).rstrip() % line + "\n")
341
+
342
+ if lvis:
343
+ filename = Path(save_dir) / json_file.name.replace("lvis_v1_", "").replace(".json", ".txt")
344
+ with open(filename, "a", encoding="utf-8") as f:
345
+ f.writelines(f"{line}\n" for line in image_txt)
346
+
347
+ LOGGER.info(f"{'LVIS' if lvis else 'COCO'} data converted successfully.\nResults saved to {save_dir.resolve()}")
348
+
349
+
350
+ def convert_segment_masks_to_yolo_seg(masks_dir, output_dir, classes):
351
+ """
352
+ Converts a dataset of segmentation mask images to the YOLO segmentation format.
353
+
354
+ This function takes the directory containing the binary format mask images and converts them into YOLO segmentation format.
355
+ The converted masks are saved in the specified output directory.
356
+
357
+ Args:
358
+ masks_dir (str): The path to the directory where all mask images (png, jpg) are stored.
359
+ output_dir (str): The path to the directory where the converted YOLO segmentation masks will be stored.
360
+ classes (int): Total classes in the dataset i.e. for COCO classes=80
361
+
362
+ Examples:
363
+ >>> from ultralytics.data.converter import convert_segment_masks_to_yolo_seg
364
+
365
+ The classes here is the total classes in the dataset, for COCO dataset we have 80 classes
366
+ >>> convert_segment_masks_to_yolo_seg("path/to/masks_directory", "path/to/output/directory", classes=80)
367
+
368
+ Notes:
369
+ The expected directory structure for the masks is:
370
+
371
+ - masks
372
+ ├─ mask_image_01.png or mask_image_01.jpg
373
+ ├─ mask_image_02.png or mask_image_02.jpg
374
+ ├─ mask_image_03.png or mask_image_03.jpg
375
+ └─ mask_image_04.png or mask_image_04.jpg
376
+
377
+ After execution, the labels will be organized in the following structure:
378
+
379
+ - output_dir
380
+ ├─ mask_yolo_01.txt
381
+ ├─ mask_yolo_02.txt
382
+ ├─ mask_yolo_03.txt
383
+ └─ mask_yolo_04.txt
384
+ """
385
+ pixel_to_class_mapping = {i + 1: i for i in range(classes)}
386
+ for mask_path in Path(masks_dir).iterdir():
387
+ if mask_path.suffix in {".png", ".jpg"}:
388
+ mask = cv2.imread(str(mask_path), cv2.IMREAD_GRAYSCALE) # Read the mask image in grayscale
389
+ img_height, img_width = mask.shape # Get image dimensions
390
+ LOGGER.info(f"Processing {mask_path} imgsz = {img_height} x {img_width}")
391
+
392
+ unique_values = np.unique(mask) # Get unique pixel values representing different classes
393
+ yolo_format_data = []
394
+
395
+ for value in unique_values:
396
+ if value == 0:
397
+ continue # Skip background
398
+ class_index = pixel_to_class_mapping.get(value, -1)
399
+ if class_index == -1:
400
+ LOGGER.warning(f"Unknown class for pixel value {value} in file {mask_path}, skipping.")
401
+ continue
402
+
403
+ # Create a binary mask for the current class and find contours
404
+ contours, _ = cv2.findContours(
405
+ (mask == value).astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
406
+ ) # Find contours
407
+
408
+ for contour in contours:
409
+ if len(contour) >= 3: # YOLO requires at least 3 points for a valid segmentation
410
+ contour = contour.squeeze() # Remove single-dimensional entries
411
+ yolo_format = [class_index]
412
+ for point in contour:
413
+ # Normalize the coordinates
414
+ yolo_format.append(round(point[0] / img_width, 6)) # Rounding to 6 decimal places
415
+ yolo_format.append(round(point[1] / img_height, 6))
416
+ yolo_format_data.append(yolo_format)
417
+ # Save Ultralytics YOLO format data to file
418
+ output_path = Path(output_dir) / f"{mask_path.stem}.txt"
419
+ with open(output_path, "w", encoding="utf-8") as file:
420
+ for item in yolo_format_data:
421
+ line = " ".join(map(str, item))
422
+ file.write(line + "\n")
423
+ LOGGER.info(f"Processed and stored at {output_path} imgsz = {img_height} x {img_width}")
424
+
425
+
426
+ def convert_dota_to_yolo_obb(dota_root_path: str):
427
+ """
428
+ Converts DOTA dataset annotations to YOLO OBB (Oriented Bounding Box) format.
429
+
430
+ The function processes images in the 'train' and 'val' folders of the DOTA dataset. For each image, it reads the
431
+ associated label from the original labels directory and writes new labels in YOLO OBB format to a new directory.
432
+
433
+ Args:
434
+ dota_root_path (str): The root directory path of the DOTA dataset.
435
+
436
+ Examples:
437
+ >>> from ultralytics.data.converter import convert_dota_to_yolo_obb
438
+ >>> convert_dota_to_yolo_obb("path/to/DOTA")
439
+
440
+ Notes:
441
+ The directory structure assumed for the DOTA dataset:
442
+
443
+ - DOTA
444
+ ├─ images
445
+ │ ├─ train
446
+ │ └─ val
447
+ └─ labels
448
+ ├─ train_original
449
+ └─ val_original
450
+
451
+ After execution, the function will organize the labels into:
452
+
453
+ - DOTA
454
+ └─ labels
455
+ ├─ train
456
+ └─ val
457
+ """
458
+ dota_root_path = Path(dota_root_path)
459
+
460
+ # Class names to indices mapping
461
+ class_mapping = {
462
+ "plane": 0,
463
+ "ship": 1,
464
+ "storage-tank": 2,
465
+ "baseball-diamond": 3,
466
+ "tennis-court": 4,
467
+ "basketball-court": 5,
468
+ "ground-track-field": 6,
469
+ "harbor": 7,
470
+ "bridge": 8,
471
+ "large-vehicle": 9,
472
+ "small-vehicle": 10,
473
+ "helicopter": 11,
474
+ "roundabout": 12,
475
+ "soccer-ball-field": 13,
476
+ "swimming-pool": 14,
477
+ "container-crane": 15,
478
+ "airport": 16,
479
+ "helipad": 17,
480
+ }
481
+
482
+ def convert_label(image_name, image_width, image_height, orig_label_dir, save_dir):
483
+ """Converts a single image's DOTA annotation to YOLO OBB format and saves it to a specified directory."""
484
+ orig_label_path = orig_label_dir / f"{image_name}.txt"
485
+ save_path = save_dir / f"{image_name}.txt"
486
+
487
+ with orig_label_path.open("r") as f, save_path.open("w") as g:
488
+ lines = f.readlines()
489
+ for line in lines:
490
+ parts = line.strip().split()
491
+ if len(parts) < 9:
492
+ continue
493
+ class_name = parts[8]
494
+ class_idx = class_mapping[class_name]
495
+ coords = [float(p) for p in parts[:8]]
496
+ normalized_coords = [
497
+ coords[i] / image_width if i % 2 == 0 else coords[i] / image_height for i in range(8)
498
+ ]
499
+ formatted_coords = [f"{coord:.6g}" for coord in normalized_coords]
500
+ g.write(f"{class_idx} {' '.join(formatted_coords)}\n")
501
+
502
+ for phase in ["train", "val"]:
503
+ image_dir = dota_root_path / "images" / phase
504
+ orig_label_dir = dota_root_path / "labels" / f"{phase}_original"
505
+ save_dir = dota_root_path / "labels" / phase
506
+
507
+ save_dir.mkdir(parents=True, exist_ok=True)
508
+
509
+ image_paths = list(image_dir.iterdir())
510
+ for image_path in TQDM(image_paths, desc=f"Processing {phase} images"):
511
+ if image_path.suffix != ".png":
512
+ continue
513
+ image_name_without_ext = image_path.stem
514
+ img = cv2.imread(str(image_path))
515
+ h, w = img.shape[:2]
516
+ convert_label(image_name_without_ext, w, h, orig_label_dir, save_dir)
517
+
518
+
519
+ def min_index(arr1, arr2):
520
+ """
521
+ Find a pair of indexes with the shortest distance between two arrays of 2D points.
522
+
523
+ Args:
524
+ arr1 (np.ndarray): A NumPy array of shape (N, 2) representing N 2D points.
525
+ arr2 (np.ndarray): A NumPy array of shape (M, 2) representing M 2D points.
526
+
527
+ Returns:
528
+ (tuple): A tuple containing the indexes of the points with the shortest distance in arr1 and arr2 respectively.
529
+ """
530
+ dis = ((arr1[:, None, :] - arr2[None, :, :]) ** 2).sum(-1)
531
+ return np.unravel_index(np.argmin(dis, axis=None), dis.shape)
532
+
533
+
534
+ def merge_multi_segment(segments):
535
+ """
536
+ Merge multiple segments into one list by connecting the coordinates with the minimum distance between each segment.
537
+ This function connects these coordinates with a thin line to merge all segments into one.
538
+
539
+ Args:
540
+ segments (List[List]): Original segmentations in COCO's JSON file.
541
+ Each element is a list of coordinates, like [segmentation1, segmentation2,...].
542
+
543
+ Returns:
544
+ s (List[np.ndarray]): A list of connected segments represented as NumPy arrays.
545
+ """
546
+ s = []
547
+ segments = [np.array(i).reshape(-1, 2) for i in segments]
548
+ idx_list = [[] for _ in range(len(segments))]
549
+
550
+ # Record the indexes with min distance between each segment
551
+ for i in range(1, len(segments)):
552
+ idx1, idx2 = min_index(segments[i - 1], segments[i])
553
+ idx_list[i - 1].append(idx1)
554
+ idx_list[i].append(idx2)
555
+
556
+ # Use two round to connect all the segments
557
+ for k in range(2):
558
+ # Forward connection
559
+ if k == 0:
560
+ for i, idx in enumerate(idx_list):
561
+ # Middle segments have two indexes, reverse the index of middle segments
562
+ if len(idx) == 2 and idx[0] > idx[1]:
563
+ idx = idx[::-1]
564
+ segments[i] = segments[i][::-1, :]
565
+
566
+ segments[i] = np.roll(segments[i], -idx[0], axis=0)
567
+ segments[i] = np.concatenate([segments[i], segments[i][:1]])
568
+ # Deal with the first segment and the last one
569
+ if i in {0, len(idx_list) - 1}:
570
+ s.append(segments[i])
571
+ else:
572
+ idx = [0, idx[1] - idx[0]]
573
+ s.append(segments[i][idx[0] : idx[1] + 1])
574
+
575
+ else:
576
+ for i in range(len(idx_list) - 1, -1, -1):
577
+ if i not in {0, len(idx_list) - 1}:
578
+ idx = idx_list[i]
579
+ nidx = abs(idx[1] - idx[0])
580
+ s.append(segments[i][nidx:])
581
+ return s
582
+
583
+
584
+ def yolo_bbox2segment(im_dir, save_dir=None, sam_model="sam_b.pt", device=None):
585
+ """
586
+ Converts existing object detection dataset (bounding boxes) to segmentation dataset or oriented bounding box (OBB)
587
+ in YOLO format. Generates segmentation data using SAM auto-annotator as needed.
588
+
589
+ Args:
590
+ im_dir (str | Path): Path to image directory to convert.
591
+ save_dir (str | Path): Path to save the generated labels, labels will be saved
592
+ into `labels-segment` in the same directory level of `im_dir` if save_dir is None.
593
+ sam_model (str): Segmentation model to use for intermediate segmentation data.
594
+ device (int | str): The specific device to run SAM models.
595
+
596
+ Notes:
597
+ The input directory structure assumed for dataset:
598
+
599
+ - im_dir
600
+ ├─ 001.jpg
601
+ ├─ ...
602
+ └─ NNN.jpg
603
+ - labels
604
+ ├─ 001.txt
605
+ ├─ ...
606
+ └─ NNN.txt
607
+ """
608
+ from ultralytics import SAM
609
+ from ultralytics.data import YOLODataset
610
+ from ultralytics.utils.ops import xywh2xyxy
611
+
612
+ # NOTE: add placeholder to pass class index check
613
+ dataset = YOLODataset(im_dir, data=dict(names=list(range(1000))))
614
+ if len(dataset.labels[0]["segments"]) > 0: # if it's segment data
615
+ LOGGER.info("Segmentation labels detected, no need to generate new ones!")
616
+ return
617
+
618
+ LOGGER.info("Detection labels detected, generating segment labels by SAM model!")
619
+ sam_model = SAM(sam_model)
620
+ for label in TQDM(dataset.labels, total=len(dataset.labels), desc="Generating segment labels"):
621
+ h, w = label["shape"]
622
+ boxes = label["bboxes"]
623
+ if len(boxes) == 0: # skip empty labels
624
+ continue
625
+ boxes[:, [0, 2]] *= w
626
+ boxes[:, [1, 3]] *= h
627
+ im = cv2.imread(label["im_file"])
628
+ sam_results = sam_model(im, bboxes=xywh2xyxy(boxes), verbose=False, save=False, device=device)
629
+ label["segments"] = sam_results[0].masks.xyn
630
+
631
+ save_dir = Path(save_dir) if save_dir else Path(im_dir).parent / "labels-segment"
632
+ save_dir.mkdir(parents=True, exist_ok=True)
633
+ for label in dataset.labels:
634
+ texts = []
635
+ lb_name = Path(label["im_file"]).with_suffix(".txt").name
636
+ txt_file = save_dir / lb_name
637
+ cls = label["cls"]
638
+ for i, s in enumerate(label["segments"]):
639
+ if len(s) == 0:
640
+ continue
641
+ line = (int(cls[i]), *s.reshape(-1))
642
+ texts.append(("%g " * len(line)).rstrip() % line)
643
+ with open(txt_file, "a", encoding="utf-8") as f:
644
+ f.writelines(text + "\n" for text in texts)
645
+ LOGGER.info(f"Generated segment labels saved in {save_dir}")
646
+
647
+
648
+ def create_synthetic_coco_dataset():
649
+ """
650
+ Creates a synthetic COCO dataset with random images based on filenames from label lists.
651
+
652
+ This function downloads COCO labels, reads image filenames from label list files,
653
+ creates synthetic images for train2017 and val2017 subsets, and organizes
654
+ them in the COCO dataset structure. It uses multithreading to generate images efficiently.
655
+
656
+ Examples:
657
+ >>> from ultralytics.data.converter import create_synthetic_coco_dataset
658
+ >>> create_synthetic_coco_dataset()
659
+
660
+ Notes:
661
+ - Requires internet connection to download label files.
662
+ - Generates random RGB images of varying sizes (480x480 to 640x640 pixels).
663
+ - Existing test2017 directory is removed as it's not needed.
664
+ - Reads image filenames from train2017.txt and val2017.txt files.
665
+ """
666
+
667
+ def create_synthetic_image(image_file):
668
+ """Generates synthetic images with random sizes and colors for dataset augmentation or testing purposes."""
669
+ if not image_file.exists():
670
+ size = (random.randint(480, 640), random.randint(480, 640))
671
+ Image.new(
672
+ "RGB",
673
+ size=size,
674
+ color=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)),
675
+ ).save(image_file)
676
+
677
+ # Download labels
678
+ dir = DATASETS_DIR / "coco"
679
+ url = "https://github.com/ultralytics/assets/releases/download/v0.0.0/"
680
+ label_zip = "coco2017labels-segments.zip"
681
+ download([url + label_zip], dir=dir.parent)
682
+
683
+ # Create synthetic images
684
+ shutil.rmtree(dir / "labels" / "test2017", ignore_errors=True) # Remove test2017 directory as not needed
685
+ with ThreadPoolExecutor(max_workers=NUM_THREADS) as executor:
686
+ for subset in ["train2017", "val2017"]:
687
+ subset_dir = dir / "images" / subset
688
+ subset_dir.mkdir(parents=True, exist_ok=True)
689
+
690
+ # Read image filenames from label list file
691
+ label_list_file = dir / f"{subset}.txt"
692
+ if label_list_file.exists():
693
+ with open(label_list_file, encoding="utf-8") as f:
694
+ image_files = [dir / line.strip() for line in f]
695
+
696
+ # Submit all tasks
697
+ futures = [executor.submit(create_synthetic_image, image_file) for image_file in image_files]
698
+ for _ in TQDM(as_completed(futures), total=len(futures), desc=f"Generating images for {subset}"):
699
+ pass # The actual work is done in the background
700
+ else:
701
+ LOGGER.warning(f"Labels file {label_list_file} does not exist. Skipping image creation for {subset}.")
702
+
703
+ LOGGER.info("Synthetic COCO dataset created successfully.")
704
+
705
+
706
+ def convert_to_multispectral(path, n_channels=10, replace=False, zip=False):
707
+ """
708
+ Convert RGB images to multispectral images by interpolating across wavelength bands.
709
+
710
+ This function takes RGB images and interpolates them to create multispectral images with a specified number
711
+ of channels. It can process either a single image or a directory of images.
712
+
713
+ Args:
714
+ path (str | Path): Path to an image file or directory containing images to convert.
715
+ n_channels (int): Number of spectral channels to generate in the output image.
716
+ replace (bool): Whether to replace the original image file with the converted one.
717
+ zip (bool): Whether to zip the converted images into a zip file.
718
+
719
+ Examples:
720
+ >>> # Convert a single image
721
+ >>> convert_to_multispectral("path/to/image.jpg", n_channels=10)
722
+ >>> # Convert a dataset
723
+ >>> convert_to_multispectral("../datasets/coco8", n_channels=10)
724
+ """
725
+ from scipy.interpolate import interp1d
726
+
727
+ from ultralytics.data.utils import IMG_FORMATS
728
+
729
+ path = Path(path)
730
+ if path.is_dir():
731
+ # Process directory
732
+ im_files = sum([list(path.rglob(f"*.{ext}")) for ext in (IMG_FORMATS - {"tif", "tiff"})], [])
733
+ for im_path in im_files:
734
+ try:
735
+ convert_to_multispectral(im_path, n_channels)
736
+ if replace:
737
+ im_path.unlink()
738
+ except Exception as e:
739
+ LOGGER.info(f"Error converting {im_path}: {e}")
740
+
741
+ if zip:
742
+ zip_directory(path)
743
+ else:
744
+ # Process a single image
745
+ output_path = path.with_suffix(".tiff")
746
+ img = cv2.cvtColor(cv2.imread(str(path)), cv2.COLOR_BGR2RGB)
747
+
748
+ # Interpolate all pixels at once
749
+ rgb_wavelengths = np.array([650, 510, 475]) # R, G, B wavelengths (nm)
750
+ target_wavelengths = np.linspace(450, 700, n_channels)
751
+ f = interp1d(rgb_wavelengths.T, img, kind="linear", bounds_error=False, fill_value="extrapolate")
752
+ multispectral = f(target_wavelengths)
753
+ cv2.imwritemulti(str(output_path), np.clip(multispectral, 0, 255).astype(np.uint8).transpose(2, 0, 1))
754
+ LOGGER.info(f"Converted {output_path}")