ShashwatGupta23 Cursor commited on
Commit
5673379
·
1 Parent(s): f63e98a

RefDiffNet: standalone A11_CA prebackbone Gradio Space

Browse files

Ship standalone a11_ca + prebackbone_infer (no ultralytics vendor),
Gradio 5.16.1 with gradio-client 1.7.0 patch, pre-aligned image pairs,
and prebackbone_a11_ca.pt weights.

Co-authored-by: Cursor <cursoragent@cursor.com>

This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitignore +2 -1
  2. README.md +34 -33
  3. a11_ca.py +213 -0
  4. app.py +103 -24
  5. deploy_to_refdiffnet.sh +4 -5
  6. examples/Missing_hole_07_missing_hole_03_rot_idx004_input.jpg +3 -0
  7. examples/Missing_hole_07_missing_hole_03_rot_idx004_reference.jpg +3 -0
  8. examples/Mouse_bite_05_mouse_bite_02_idx007_input.jpg +3 -0
  9. examples/Mouse_bite_05_mouse_bite_02_idx007_reference.jpg +3 -0
  10. examples/Open_circuit_04_open_circuit_14_idx002_input.jpg +3 -0
  11. examples/Open_circuit_04_open_circuit_14_idx002_reference.jpg +3 -0
  12. examples/Open_circuit_09_open_circuit_05_idx010_input.jpg +3 -0
  13. examples/Open_circuit_09_open_circuit_05_idx010_reference.jpg +3 -0
  14. examples/Short_06_short_11_rot_idx010_input.jpg +3 -0
  15. examples/Short_06_short_11_rot_idx010_reference.jpg +3 -0
  16. examples/Spur_06_spur_10_rot_idx014_input.jpg +3 -0
  17. examples/Spur_06_spur_10_rot_idx014_reference.jpg +3 -0
  18. examples/Spurious_copper_01_spurious_copper_13_rot_idx003_input.jpg +3 -0
  19. examples/Spurious_copper_01_spurious_copper_13_rot_idx003_reference.jpg +3 -0
  20. extract_prebackbone_weights.py +57 -12
  21. gradio_patch.py +32 -0
  22. prebackbone_infer.py +48 -109
  23. prepare_space.sh +81 -0
  24. requirements.txt +6 -11
  25. setup.sh +8 -14
  26. vendor/pyproject.toml +0 -194
  27. vendor/ultralytics.egg-info/PKG-INFO +0 -88
  28. vendor/ultralytics.egg-info/SOURCES.txt +0 -308
  29. vendor/ultralytics.egg-info/dependency_links.txt +0 -1
  30. vendor/ultralytics.egg-info/entry_points.txt +0 -3
  31. vendor/ultralytics.egg-info/requires.txt +0 -83
  32. vendor/ultralytics.egg-info/top_level.txt +0 -1
  33. vendor/ultralytics/__init__.py +0 -48
  34. vendor/ultralytics/cfg/__init__.py +0 -1039
  35. vendor/ultralytics/cfg/datasets/Argoverse.yaml +0 -78
  36. vendor/ultralytics/cfg/datasets/DOTAv1.5.yaml +0 -37
  37. vendor/ultralytics/cfg/datasets/DOTAv1.yaml +0 -36
  38. vendor/ultralytics/cfg/datasets/GlobalWheat2020.yaml +0 -68
  39. vendor/ultralytics/cfg/datasets/HomeObjects-3K.yaml +0 -32
  40. vendor/ultralytics/cfg/datasets/ImageNet.yaml +0 -2025
  41. vendor/ultralytics/cfg/datasets/Objects365.yaml +0 -447
  42. vendor/ultralytics/cfg/datasets/SKU-110K.yaml +0 -58
  43. vendor/ultralytics/cfg/datasets/TT100K.yaml +0 -346
  44. vendor/ultralytics/cfg/datasets/VOC.yaml +0 -102
  45. vendor/ultralytics/cfg/datasets/VisDrone.yaml +0 -87
  46. vendor/ultralytics/cfg/datasets/african-wildlife.yaml +0 -25
  47. vendor/ultralytics/cfg/datasets/brain-tumor.yaml +0 -22
  48. vendor/ultralytics/cfg/datasets/carparts-seg.yaml +0 -44
  49. vendor/ultralytics/cfg/datasets/coco-pose.yaml +0 -64
  50. vendor/ultralytics/cfg/datasets/coco.yaml +0 -118
.gitignore CHANGED
@@ -3,6 +3,7 @@ __pycache__/
3
  .gradio/
4
  *.log
5
  .DS_Store
 
 
6
  # Full YOLO checkpoint optional locally; Space ships prebackbone_a11_ca.pt only
7
  weights/best.pt
8
- examples/
 
3
  .gradio/
4
  *.log
5
  .DS_Store
6
+ # Legacy vendored ultralytics (no longer used)
7
+ vendor/
8
  # Full YOLO checkpoint optional locally; Space ships prebackbone_a11_ca.pt only
9
  weights/best.pt
 
README.md CHANGED
@@ -4,7 +4,7 @@ emoji: 🔬
4
  colorFrom: blue
5
  colorTo: green
6
  sdk: gradio
7
- sdk_version: "4.44.1"
8
  python_version: "3.10"
9
  app_file: app.py
10
  pinned: false
@@ -15,12 +15,12 @@ license: agpl-3.0
15
 
16
  **Space:** [vinayedula/RefDiffNet](https://huggingface.co/spaces/vinayedula/RefDiffNet)
17
 
18
- Gradio demo for the **A11_CA** prebackbone trained with YOLO12n on HR-IPCB.
19
 
20
  - **Inputs:** defect PCB image + golden reference image
21
  - **Output:** enriched image (`enriched = defect + α · gate · delta`)
22
 
23
- Weights: `weights/prebackbone_a11_ca.pt` (~few MB, prebackbone only — not full `best.pt`)
24
 
25
  ## Deploy to Hugging Face Spaces
26
 
@@ -35,45 +35,28 @@ bash hf_prebackbone_demo/prepare_space.sh
35
 
36
  This will:
37
 
38
- - Copy the custom **Ultralytics** fork into `hf_prebackbone_demo/vendor/`
39
- - Extract `prebackbone_a11_ca.pt` from `best.pt` (small file for the Space)
40
- - Copy example image pairs into `hf_prebackbone_demo/examples/`
41
 
42
- ### 2. Create a new Space on Hugging Face
43
-
44
- 1. Go to [huggingface.co/new-space](https://huggingface.co/new-space)
45
- 2. Choose **Gradio** SDK
46
- 3. Clone the empty Space repo locally
47
-
48
- ### 3. Push to [vinayedula/RefDiffNet](https://huggingface.co/spaces/vinayedula/RefDiffNet)
49
 
50
  ```bash
51
  cd hf_prebackbone_demo
52
  bash deploy_to_refdiffnet.sh
53
  ```
54
 
55
- Or manually:
56
 
57
- ```bash
58
- git clone https://huggingface.co/spaces/vinayedula/RefDiffNet
59
- cd RefDiffNet
60
- # copy app.py, vendor/, weights/prebackbone_a11_ca.pt, examples/, etc.
61
- git add . && git commit -m "RefDiffNet demo" && git push
62
- ```
63
-
64
- > **Note:** `prebackbone_a11_ca.pt` is only a few MB (no LFS needed). Full `best.pt` is optional.
65
-
66
- ### 4. Space settings (recommended)
67
 
68
  | Setting | Value |
69
  |---------|--------|
70
- | Hardware | CPU Basic (works) or **GPU** for faster loads |
71
  | Secrets | Optional: `HF_TOKEN` if weights are in a private model repo |
72
 
73
  ### Alternative: host weights on the Hub
74
 
75
- Upload `prebackbone_a11_ca.pt` to a model repo, then set:
76
-
77
  ```
78
  HF_MODEL_REPO=YOUR_USER/YOUR_MODEL
79
  ```
@@ -84,22 +67,40 @@ The app downloads `prebackbone_a11_ca.pt` from that repo.
84
 
85
  ```bash
86
  cd hf_prebackbone_demo
 
 
87
  pip install -r requirements.txt
88
- pip install -e ../ultralytics # custom fork with A11_CA
89
- python extract_prebackbone_weights.py --ckpt /path/to/best.pt
90
  export PREBACKBONE_ONLY_WEIGHTS=weights/prebackbone_a11_ca.pt
91
  python app.py
92
  ```
93
 
94
- Open http://localhost:7860
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
 
96
  ## Environment variables
97
 
98
  | Variable | Description |
99
  |----------|-------------|
100
  | `PREBACKBONE_ONLY_WEIGHTS` | Path to `prebackbone_a11_ca.pt` |
101
- | `PREBACKBONE_FULL_CKPT` | Full `best.pt` (only for one-time extraction) |
102
  | `HF_MODEL_REPO` | Hub repo with `prebackbone_a11_ca.pt` |
103
- | `PREBACKBONE_IMGSZ` | Letterbox size (default `640`) |
104
- | `ULTRALYTICS_ROOT` | Path to ultralytics repo if not vendored |
105
  | `PORT` | Gradio port (default `7860`) |
 
4
  colorFrom: blue
5
  colorTo: green
6
  sdk: gradio
7
+ sdk_version: "5.16.1"
8
  python_version: "3.10"
9
  app_file: app.py
10
  pinned: false
 
15
 
16
  **Space:** [vinayedula/RefDiffNet](https://huggingface.co/spaces/vinayedula/RefDiffNet)
17
 
18
+ Standalone Gradio demo for the **A11_CA** prebackbone (no Ultralytics at runtime).
19
 
20
  - **Inputs:** defect PCB image + golden reference image
21
  - **Output:** enriched image (`enriched = defect + α · gate · delta`)
22
 
23
+ Weights: `weights/prebackbone_a11_ca.pt` (~few MB)
24
 
25
  ## Deploy to Hugging Face Spaces
26
 
 
35
 
36
  This will:
37
 
38
+ - Extract `prebackbone_a11_ca.pt` from `best.pt` (uses the VYOLO ultralytics fork **once** on your machine)
39
+ - Copy example image pairs into `examples/`
40
+ - Remove legacy `vendor/` if present
41
 
42
+ ### 2. Push to [vinayedula/RefDiffNet](https://huggingface.co/spaces/vinayedula/RefDiffNet)
 
 
 
 
 
 
43
 
44
  ```bash
45
  cd hf_prebackbone_demo
46
  bash deploy_to_refdiffnet.sh
47
  ```
48
 
49
+ > **Note:** The Space ships only `a11_ca.py`, `prebackbone_infer.py`, and `prebackbone_a11_ca.pt` — not the full ultralytics tree.
50
 
51
+ ### 3. Space settings (recommended)
 
 
 
 
 
 
 
 
 
52
 
53
  | Setting | Value |
54
  |---------|--------|
55
+ | Hardware | CPU Basic (works) or **GPU** for faster inference |
56
  | Secrets | Optional: `HF_TOKEN` if weights are in a private model repo |
57
 
58
  ### Alternative: host weights on the Hub
59
 
 
 
60
  ```
61
  HF_MODEL_REPO=YOUR_USER/YOUR_MODEL
62
  ```
 
67
 
68
  ```bash
69
  cd hf_prebackbone_demo
70
+ # Clean broken Gradio 4.x + starlette 1.x mix if you hit jinja2 / localhost errors:
71
+ pip uninstall -y gradio gradio-client starlette fastapi uvicorn 2>/dev/null || true
72
  pip install -r requirements.txt
73
+ pip install --force-reinstall "numpy>=1.23.0,<2"
 
74
  export PREBACKBONE_ONLY_WEIGHTS=weights/prebackbone_a11_ca.pt
75
  python app.py
76
  ```
77
 
78
+ Open **http://127.0.0.1:7860** (default bind). Remote server: `GRADIO_SERVER_NAME=0.0.0.0 python app.py` or SSH port-forward.
79
+
80
+ ### One-time weight extraction (from full `best.pt`)
81
+
82
+ Only needed if you do not already have `prebackbone_a11_ca.pt`:
83
+
84
+ ```bash
85
+ ULTRALYTICS_ROOT=../ultralytics python extract_prebackbone_weights.py \
86
+ --ckpt ../ultralytics/Proposed/yolo12_training/HRIPCB_Results/yolo12n_hripcb_200epochs_batch16/weights/best.pt
87
+ ```
88
+
89
+ ## Layout
90
+
91
+ | File | Role |
92
+ |------|------|
93
+ | `a11_ca.py` | Standalone A11_CA module definition |
94
+ | `prebackbone_infer.py` | Load weights, run enrichment (same H×W inputs) |
95
+ | `gradio_patch.py` | Gradio 5.16 / client 1.7 compatibility patch |
96
+ | `app.py` | Gradio UI |
97
+ | `weights/prebackbone_a11_ca.pt` | Prebackbone weights only |
98
 
99
  ## Environment variables
100
 
101
  | Variable | Description |
102
  |----------|-------------|
103
  | `PREBACKBONE_ONLY_WEIGHTS` | Path to `prebackbone_a11_ca.pt` |
 
104
  | `HF_MODEL_REPO` | Hub repo with `prebackbone_a11_ca.pt` |
105
+ | `PREBACKBONE_DEVICE` | `cpu` or `cuda` (default: auto) |
 
106
  | `PORT` | Gradio port (default `7860`) |
a11_ca.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Standalone A11_CA prebackbone (defect + golden reference -> enriched image)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+ import torch.nn.functional as F
8
+
9
+ __all__ = [
10
+ "ConvBNAct",
11
+ "LocalContrastNorm",
12
+ "FixedHaarBands",
13
+ "EncoderAttentionCoordStem2d",
14
+ "A11CoordinateEncoderAttentionPreBackbone",
15
+ "build_prebackbone",
16
+ ]
17
+
18
+
19
+ class ConvBNAct(nn.Module):
20
+ def __init__(
21
+ self,
22
+ c1: int,
23
+ c2: int,
24
+ k: int = 3,
25
+ s: int = 1,
26
+ p: int | None = None,
27
+ groups: int = 1,
28
+ act: bool = True,
29
+ ):
30
+ super().__init__()
31
+ if p is None:
32
+ p = k // 2
33
+ self.conv = nn.Conv2d(c1, c2, k, s, p, groups=groups, bias=False)
34
+ self.bn = nn.BatchNorm2d(c2)
35
+ self.act = nn.SiLU(inplace=True) if act else nn.Identity()
36
+
37
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
38
+ return self.act(self.bn(self.conv(x)))
39
+
40
+
41
+ class LocalContrastNorm(nn.Module):
42
+ """Lightweight no-parameter local contrast normalization."""
43
+
44
+ def __init__(self, kernel_size: int = 7, eps: float = 1e-4):
45
+ super().__init__()
46
+ self.kernel_size = kernel_size
47
+ self.eps = eps
48
+ self.pad = kernel_size // 2
49
+
50
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
51
+ mean = F.avg_pool2d(x, self.kernel_size, stride=1, padding=self.pad)
52
+ var = F.avg_pool2d((x - mean) ** 2, self.kernel_size, stride=1, padding=self.pad)
53
+ return (x - mean) / torch.sqrt(var + self.eps)
54
+
55
+
56
+ class FixedHaarBands(nn.Module):
57
+ """Fixed Haar wavelet decomposition at 1/2 resolution (LL, LH, HL, HH per channel)."""
58
+
59
+ def __init__(self, channels: int = 3):
60
+ super().__init__()
61
+ self.channels = channels
62
+
63
+ ll = torch.tensor([[1, 1], [1, 1]], dtype=torch.float32) / 2.0
64
+ lh = torch.tensor([[-1, -1], [1, 1]], dtype=torch.float32) / 2.0
65
+ hl = torch.tensor([[-1, 1], [-1, 1]], dtype=torch.float32) / 2.0
66
+ hh = torch.tensor([[1, -1], [-1, 1]], dtype=torch.float32) / 2.0
67
+
68
+ weight = torch.stack([ll, lh, hl, hh], dim=0).view(4, 1, 2, 2)
69
+ weight = weight.repeat(channels, 1, 1, 1)
70
+ self.register_buffer("weight", weight)
71
+
72
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
73
+ return F.conv2d(x, self.weight, stride=2, padding=0, groups=self.channels)
74
+
75
+
76
+ class EncoderAttentionCoordStem2d(nn.Module):
77
+ """H/W pooled coordinate modulation; returns feat * attn_h * attn_w."""
78
+
79
+ def __init__(self, hidden: int) -> None:
80
+ super().__init__()
81
+ ch = max(hidden // 8, 8)
82
+ self.pool_h = nn.AdaptiveAvgPool2d((None, 1))
83
+ self.pool_w = nn.AdaptiveAvgPool2d((1, None))
84
+ self.conv1 = nn.Conv2d(hidden, ch, kernel_size=1, bias=False)
85
+ self.bn1 = nn.BatchNorm2d(ch)
86
+ self.act = nn.SiLU(inplace=True)
87
+ self.conv_h = nn.Conv2d(ch, hidden, kernel_size=1, bias=True)
88
+ self.conv_w = nn.Conv2d(ch, hidden, kernel_size=1, bias=True)
89
+
90
+ def forward(self, feat: torch.Tensor) -> torch.Tensor:
91
+ _, _, h, w = feat.shape
92
+ xh = self.pool_h(feat)
93
+ xw = self.pool_w(feat).permute(0, 1, 3, 2)
94
+ coord = torch.cat([xh, xw], dim=2)
95
+ coord = self.act(self.bn1(self.conv1(coord)))
96
+ ah, aw = torch.split(coord, [h, w], dim=2)
97
+ aw = aw.permute(0, 1, 3, 2)
98
+ mh = torch.sigmoid(self.conv_h(ah))
99
+ mw = torch.sigmoid(self.conv_w(aw))
100
+ return feat * mh * mw
101
+
102
+
103
+ class A11CoordinateEncoderAttentionPreBackbone(nn.Module):
104
+ """
105
+ A11_CA: defect + golden -> enriched = defect + alpha * gate * delta.
106
+
107
+ Cues: Haar bands, signed low-res residual, morphology; encoder + channel/spatial gates.
108
+ """
109
+
110
+ def __init__(
111
+ self,
112
+ channels: int = 3,
113
+ hidden: int = 24,
114
+ use_lcn: bool = True,
115
+ alpha_init: float = 0.08,
116
+ ):
117
+ super().__init__()
118
+ self.channels = channels
119
+ self.hidden = hidden
120
+
121
+ self.lcn = LocalContrastNorm(kernel_size=7) if use_lcn else nn.Identity()
122
+ self.haar = FixedHaarBands(channels=channels)
123
+
124
+ in_ch = channels * 12
125
+ self.encoder = nn.Sequential(
126
+ ConvBNAct(in_ch, hidden, k=1, s=1),
127
+ ConvBNAct(hidden, hidden, k=3, s=1, groups=hidden),
128
+ ConvBNAct(hidden, hidden, k=1, s=1),
129
+ ConvBNAct(hidden, hidden, k=3, s=1, groups=hidden),
130
+ ConvBNAct(hidden, hidden, k=1, s=1),
131
+ )
132
+
133
+ gate_hidden = max(hidden // 8, 4)
134
+ self.channel_gate = nn.Sequential(
135
+ nn.AdaptiveAvgPool2d(1),
136
+ nn.Conv2d(hidden, gate_hidden, kernel_size=1, bias=True),
137
+ nn.SiLU(inplace=True),
138
+ nn.Conv2d(gate_hidden, hidden, kernel_size=1, bias=True),
139
+ nn.Sigmoid(),
140
+ )
141
+
142
+ self.rgb_delta = nn.Sequential(
143
+ ConvBNAct(hidden, hidden, k=1, s=1),
144
+ nn.Conv2d(hidden, channels, kernel_size=1, bias=True),
145
+ nn.Tanh(),
146
+ )
147
+
148
+ self.spatial_gate_replacement = nn.Sequential(
149
+ EncoderAttentionCoordStem2d(hidden),
150
+ nn.Conv2d(hidden, 1, kernel_size=1, bias=True),
151
+ nn.Sigmoid(),
152
+ )
153
+
154
+ self.alpha = nn.Parameter(torch.tensor(float(alpha_init)))
155
+
156
+ def forward(self, defect: torch.Tensor, golden: torch.Tensor) -> torch.Tensor:
157
+ if defect.shape != golden.shape:
158
+ raise ValueError(
159
+ f"A11_CA expects same shape for defect and golden tensors, "
160
+ f"got {tuple(defect.shape)} vs {tuple(golden.shape)}"
161
+ )
162
+
163
+ defect_n = self.lcn(defect)
164
+ golden_n = self.lcn(golden)
165
+
166
+ bd = self.haar(defect_n)
167
+ bg = self.haar(golden_n)
168
+
169
+ defect_lr = F.avg_pool2d(defect_n, kernel_size=2, stride=2)
170
+ golden_lr = F.avg_pool2d(golden_n, kernel_size=2, stride=2)
171
+ signed_lr = defect_lr - golden_lr
172
+ pos_lr = F.relu(signed_lr)
173
+ neg_lr = F.relu(-signed_lr)
174
+ morph_pos = F.max_pool2d(pos_lr, kernel_size=3, stride=1, padding=1)
175
+ morph_neg = F.max_pool2d(neg_lr, kernel_size=3, stride=1, padding=1)
176
+
177
+ x = torch.cat([bd, bg, pos_lr, neg_lr, morph_pos, morph_neg], dim=1)
178
+
179
+ feat = self.encoder(x)
180
+ feat = feat * self.channel_gate(feat)
181
+
182
+ delta_lr = self.rgb_delta(feat)
183
+ gate_lr = self.spatial_gate_replacement(feat)
184
+
185
+ gate = F.interpolate(gate_lr, size=defect.shape[2:], mode="bilinear", align_corners=False)
186
+ delta = F.interpolate(delta_lr, size=defect.shape[2:], mode="bilinear", align_corners=False)
187
+ enriched = defect + self.alpha * gate * delta
188
+
189
+ self._debug = {
190
+ "defect": defect.detach(),
191
+ "golden": golden.detach(),
192
+ "gate": gate.detach(),
193
+ "delta": delta.detach(),
194
+ "alpha": float(self.alpha.detach().item()),
195
+ "enriched": enriched.detach(),
196
+ }
197
+
198
+ return enriched
199
+
200
+
201
+ _REGISTRY: dict[str, type[nn.Module]] = {
202
+ "A11_CA": A11CoordinateEncoderAttentionPreBackbone,
203
+ }
204
+
205
+
206
+ def build_prebackbone(name: str | None, channels: int = 3, **kwargs) -> nn.Module | None:
207
+ if not name:
208
+ return None
209
+ key = str(name).upper()
210
+ if key not in _REGISTRY:
211
+ supported = ", ".join(sorted(_REGISTRY))
212
+ raise ValueError(f"Unsupported prebackbone '{name}'. Supported: {supported}")
213
+ return _REGISTRY[key](channels=channels, **kwargs)
app.py CHANGED
@@ -3,10 +3,32 @@
3
  from __future__ import annotations
4
 
5
  import os
 
 
6
 
7
- # Hugging Face Spaces: required before importing gradio
8
- os.environ.setdefault("GRADIO_SERVER_NAME", "0.0.0.0")
9
- os.environ.setdefault("GRADIO_SERVER_PORT", os.environ.get("PORT", "7860"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
  import gradio as gr
12
  import numpy as np
@@ -16,7 +38,7 @@ from prebackbone_infer import enrich_pair, get_enricher
16
 
17
  TITLE = "RefDiffNet — PCB Reference–Defect Enrichment"
18
  DESCRIPTION = """
19
- Upload a **defect PCB image** and its **golden reference** (same board, no defect).
20
  The A11_CA prebackbone outputs an **enriched** image: `enriched = defect + α · gate · delta`
21
  """
22
 
@@ -26,6 +48,9 @@ def run_demo(defect_path: str | None, reference_path: str | None):
26
  raise gr.Error("Please upload both defect and reference images.")
27
 
28
  defect_rgb, ref_rgb, enriched_rgb = enrich_pair(defect_path, reference_path)
 
 
 
29
 
30
  h = max(defect_rgb.shape[0], ref_rgb.shape[0], enriched_rgb.shape[0])
31
 
@@ -39,7 +64,19 @@ def run_demo(defect_path: str | None, reference_path: str | None):
39
  return Image.fromarray(enriched_rgb), Image.fromarray(row)
40
 
41
 
42
- def _preload_model():
 
 
 
 
 
 
 
 
 
 
 
 
43
  try:
44
  get_enricher()
45
  print("[RefDiffNet] Prebackbone loaded.")
@@ -47,27 +84,69 @@ def _preload_model():
47
  print(f"[RefDiffNet] WARN: {e}")
48
 
49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  if __name__ == "__main__":
51
- _preload_model()
52
-
53
- demo = gr.Interface(
54
- fn=run_demo,
55
- inputs=[
56
- gr.Image(type="filepath", label="Defect image (input)"),
57
- gr.Image(type="filepath", label="Golden reference"),
58
- ],
59
- outputs=[
60
- gr.Image(type="pil", label="Enriched output"),
61
- gr.Image(type="pil", label="Defect | Reference | Enriched"),
62
- ],
63
- title=TITLE,
64
- description=DESCRIPTION,
65
- allow_flagging="never",
66
- )
67
 
68
  demo.launch(
69
- server_name="0.0.0.0",
70
- server_port=int(os.environ.get("PORT", "7860")),
71
- share=False,
72
  show_error=True,
 
 
73
  )
 
3
  from __future__ import annotations
4
 
5
  import os
6
+ import socket
7
+ from pathlib import Path
8
 
9
+ _ROOT = Path(__file__).resolve().parent
10
+
11
+
12
+ def _is_hf_space() -> bool:
13
+ return bool(os.environ.get("SPACE_ID") or os.environ.get("SYSTEM") == "spaces")
14
+
15
+
16
+ def _configure_runtime() -> None:
17
+ os.environ.setdefault("GRADIO_SERVER_PORT", os.environ.get("PORT", "7860"))
18
+ os.environ.setdefault(
19
+ "PREBACKBONE_ONLY_WEIGHTS",
20
+ str(_ROOT / "weights" / "prebackbone_a11_ca.pt"),
21
+ )
22
+ if _is_hf_space():
23
+ os.environ.setdefault("PRELOAD_MODEL", "1")
24
+ os.environ.setdefault("GRADIO_SERVER_NAME", "0.0.0.0")
25
+
26
+
27
+ _configure_runtime()
28
+
29
+ import gradio_patch
30
+
31
+ gradio_patch.apply()
32
 
33
  import gradio as gr
34
  import numpy as np
 
38
 
39
  TITLE = "RefDiffNet — PCB Reference–Defect Enrichment"
40
  DESCRIPTION = """
41
+ Upload a **defect PCB image** and its **golden reference** (same H×W, pre-aligned — e.g. `*_input.jpg` / `*_reference.jpg` from training).
42
  The A11_CA prebackbone outputs an **enriched** image: `enriched = defect + α · gate · delta`
43
  """
44
 
 
48
  raise gr.Error("Please upload both defect and reference images.")
49
 
50
  defect_rgb, ref_rgb, enriched_rgb = enrich_pair(defect_path, reference_path)
51
+ defect_rgb = np.array(defect_rgb, dtype=np.uint8, copy=True)
52
+ ref_rgb = np.array(ref_rgb, dtype=np.uint8, copy=True)
53
+ enriched_rgb = np.array(enriched_rgb, dtype=np.uint8, copy=True)
54
 
55
  h = max(defect_rgb.shape[0], ref_rgb.shape[0], enriched_rgb.shape[0])
56
 
 
64
  return Image.fromarray(enriched_rgb), Image.fromarray(row)
65
 
66
 
67
+ def _example_pairs() -> list[list[str]]:
68
+ pairs: list[list[str]] = []
69
+ ex_dir = _ROOT / "examples"
70
+ if not ex_dir.is_dir():
71
+ return pairs
72
+ for inp in sorted(ex_dir.glob("*_input.jpg")):
73
+ ref = inp.with_name(inp.name.replace("_input.", "_reference."))
74
+ if ref.is_file():
75
+ pairs.append([str(inp), str(ref)])
76
+ return pairs
77
+
78
+
79
+ def _preload_model() -> None:
80
  try:
81
  get_enricher()
82
  print("[RefDiffNet] Prebackbone loaded.")
 
84
  print(f"[RefDiffNet] WARN: {e}")
85
 
86
 
87
+ def build_demo() -> gr.Blocks:
88
+ with gr.Blocks(title=TITLE) as demo:
89
+ gr.Markdown(DESCRIPTION.strip())
90
+ with gr.Row():
91
+ defect_in = gr.Image(type="filepath", label="Defect image (input)")
92
+ ref_in = gr.Image(type="filepath", label="Golden reference")
93
+ run_btn = gr.Button("Run enrichment", variant="primary")
94
+ with gr.Row():
95
+ out_enriched = gr.Image(type="pil", label="Enriched output")
96
+ out_row = gr.Image(type="pil", label="Defect | Reference | Enriched")
97
+ run_btn.click(run_demo, inputs=[defect_in, ref_in], outputs=[out_enriched, out_row])
98
+
99
+ examples = _example_pairs()
100
+ if examples:
101
+ gr.Examples(
102
+ examples=examples,
103
+ inputs=[defect_in, ref_in],
104
+ examples_per_page=3,
105
+ label="Example pairs (pre-aligned HR-IPCB samples)",
106
+ )
107
+ return demo
108
+
109
+
110
+ demo = build_demo()
111
+
112
+
113
+ def _launch_kwargs() -> dict:
114
+ if _is_hf_space():
115
+ return {
116
+ "server_name": "0.0.0.0",
117
+ "server_port": int(os.environ.get("PORT", "7860")),
118
+ "share": False,
119
+ }
120
+ server_name = os.environ.get("GRADIO_SERVER_NAME", "127.0.0.1")
121
+ preferred_port = int(os.environ.get("PORT", os.environ.get("GRADIO_SERVER_PORT", "7860")))
122
+ bind_host = "127.0.0.1" if server_name in ("127.0.0.1", "localhost") else server_name
123
+ server_port = preferred_port
124
+ if server_name in ("127.0.0.1", "localhost"):
125
+ for port in range(preferred_port, preferred_port + 20):
126
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
127
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
128
+ try:
129
+ sock.bind((bind_host, port))
130
+ server_port = port
131
+ break
132
+ except OSError:
133
+ continue
134
+ share = os.environ.get("GRADIO_SHARE", "").lower() in ("1", "true", "yes")
135
+ return {
136
+ "server_name": server_name,
137
+ "server_port": server_port,
138
+ "share": share,
139
+ }
140
+
141
+
142
  if __name__ == "__main__":
143
+ print(f"[RefDiffNet] gradio {getattr(gr, '__version__', 'unknown')}")
144
+ if os.environ.get("PRELOAD_MODEL", "0").lower() in ("1", "true", "yes"):
145
+ _preload_model()
 
 
 
 
 
 
 
 
 
 
 
 
 
146
 
147
  demo.launch(
148
+ **(_launch_kwargs()),
 
 
149
  show_error=True,
150
+ inbrowser=False,
151
+ prevent_thread_lock=False,
152
  )
deploy_to_refdiffnet.sh CHANGED
@@ -6,7 +6,7 @@ cd "$(dirname "$0")"
6
  SPACE_REMOTE="${SPACE_REMOTE:-https://huggingface.co/spaces/vinayedula/RefDiffNet}"
7
 
8
  if [[ ! -f weights/prebackbone_a11_ca.pt ]]; then
9
- echo "Run: python extract_prebackbone_weights.py --ckpt /path/to/best.pt"
10
  exit 1
11
  fi
12
 
@@ -15,7 +15,9 @@ git lfs install 2>/dev/null || true
15
 
16
  git add \
17
  app.py \
 
18
  prebackbone_infer.py \
 
19
  extract_prebackbone_weights.py \
20
  deploy_to_refdiffnet.sh \
21
  prepare_space.sh \
@@ -24,13 +26,11 @@ git add \
24
  README.md \
25
  .gitattributes \
26
  .gitignore \
27
- vendor/ \
28
  examples/ \
29
  weights/prebackbone_a11_ca.pt
30
 
31
- # Commit only if there are staged changes
32
  if ! git diff --cached --quiet; then
33
- git commit -m "RefDiffNet: A11_CA prebackbone enrichment demo"
34
  elif ! git rev-parse HEAD >/dev/null 2>&1; then
35
  echo "ERROR: No commit to push. Check git add / files."
36
  exit 1
@@ -38,7 +38,6 @@ else
38
  echo "No new changes; pushing existing commit."
39
  fi
40
 
41
- # HF Spaces use 'main' (git init often creates 'master')
42
  git branch -M main
43
 
44
  if git remote get-url origin &>/dev/null; then
 
6
  SPACE_REMOTE="${SPACE_REMOTE:-https://huggingface.co/spaces/vinayedula/RefDiffNet}"
7
 
8
  if [[ ! -f weights/prebackbone_a11_ca.pt ]]; then
9
+ echo "Run: bash prepare_space.sh (or extract_prebackbone_weights.py)"
10
  exit 1
11
  fi
12
 
 
15
 
16
  git add \
17
  app.py \
18
+ a11_ca.py \
19
  prebackbone_infer.py \
20
+ gradio_patch.py \
21
  extract_prebackbone_weights.py \
22
  deploy_to_refdiffnet.sh \
23
  prepare_space.sh \
 
26
  README.md \
27
  .gitattributes \
28
  .gitignore \
 
29
  examples/ \
30
  weights/prebackbone_a11_ca.pt
31
 
 
32
  if ! git diff --cached --quiet; then
33
+ git commit -m "RefDiffNet: standalone A11_CA prebackbone demo"
34
  elif ! git rev-parse HEAD >/dev/null 2>&1; then
35
  echo "ERROR: No commit to push. Check git add / files."
36
  exit 1
 
38
  echo "No new changes; pushing existing commit."
39
  fi
40
 
 
41
  git branch -M main
42
 
43
  if git remote get-url origin &>/dev/null; then
examples/Missing_hole_07_missing_hole_03_rot_idx004_input.jpg ADDED

Git LFS Details

  • SHA256: 9a39c7c46a995f722c29a32976960bcd7f3c56873ca818510c038a61c8ffd422
  • Pointer size: 130 Bytes
  • Size of remote file: 95.4 kB
examples/Missing_hole_07_missing_hole_03_rot_idx004_reference.jpg ADDED

Git LFS Details

  • SHA256: 054eae99652e187fb6fb7c7a8b3047d0d71277586b843463dc4596fffd2546f9
  • Pointer size: 131 Bytes
  • Size of remote file: 103 kB
examples/Mouse_bite_05_mouse_bite_02_idx007_input.jpg ADDED

Git LFS Details

  • SHA256: a6efba34dd8b643a415df2b02eb2edc3c611b2f578116b15f29695f7fa888d3d
  • Pointer size: 131 Bytes
  • Size of remote file: 113 kB
examples/Mouse_bite_05_mouse_bite_02_idx007_reference.jpg ADDED

Git LFS Details

  • SHA256: 4e701c76e58650548a98a0eb761b2e8621c6b3e0919bbc9ca75cbb3d8ece0b9c
  • Pointer size: 131 Bytes
  • Size of remote file: 102 kB
examples/Open_circuit_04_open_circuit_14_idx002_input.jpg ADDED

Git LFS Details

  • SHA256: 245c1b713aef03f5114eead5398d5e5b63c1c2e3727a9a657ea6d0faa5049cab
  • Pointer size: 131 Bytes
  • Size of remote file: 112 kB
examples/Open_circuit_04_open_circuit_14_idx002_reference.jpg ADDED

Git LFS Details

  • SHA256: 60d74604a30ba79eab9c0f994f10bc6fd32f44cfc87b081630007be943237012
  • Pointer size: 131 Bytes
  • Size of remote file: 133 kB
examples/Open_circuit_09_open_circuit_05_idx010_input.jpg ADDED

Git LFS Details

  • SHA256: 7abcb19f4f53de88ef2ee47663da06c929432a4d35d605ea51e6e03050d00260
  • Pointer size: 131 Bytes
  • Size of remote file: 127 kB
examples/Open_circuit_09_open_circuit_05_idx010_reference.jpg ADDED

Git LFS Details

  • SHA256: e0b64f8de13b061e63b07cfcaa5ebe544fb1a3bfcafc8ca1efccb7acbba42851
  • Pointer size: 131 Bytes
  • Size of remote file: 125 kB
examples/Short_06_short_11_rot_idx010_input.jpg ADDED

Git LFS Details

  • SHA256: c82c95095e3cef7186655187f64a80fa05f8be9d4f782498872486314d2fd359
  • Pointer size: 130 Bytes
  • Size of remote file: 66.4 kB
examples/Short_06_short_11_rot_idx010_reference.jpg ADDED

Git LFS Details

  • SHA256: 9f3e091195c05b81c3214e0614dec77a7a8a03f31ab71e592a7d13960c30bf58
  • Pointer size: 130 Bytes
  • Size of remote file: 70.9 kB
examples/Spur_06_spur_10_rot_idx014_input.jpg ADDED

Git LFS Details

  • SHA256: 14833a327eb60f62cc7113d62037147f3bfc24247615d21b49f9f19f0ac1b69c
  • Pointer size: 130 Bytes
  • Size of remote file: 84.7 kB
examples/Spur_06_spur_10_rot_idx014_reference.jpg ADDED

Git LFS Details

  • SHA256: 1b71bfc784a396bccd80739e92da6afa55969438b11c76ba22d0ae52e5249183
  • Pointer size: 130 Bytes
  • Size of remote file: 77.3 kB
examples/Spurious_copper_01_spurious_copper_13_rot_idx003_input.jpg ADDED

Git LFS Details

  • SHA256: 5c74453157700bd4b66eecfc6463a65f587b830fe13355a344358e00b14560b8
  • Pointer size: 130 Bytes
  • Size of remote file: 96.9 kB
examples/Spurious_copper_01_spurious_copper_13_rot_idx003_reference.jpg ADDED

Git LFS Details

  • SHA256: c7201b1c77159474001b894916c26974ff861b218886482951c55b5c3c5f54a0
  • Pointer size: 131 Bytes
  • Size of remote file: 112 kB
extract_prebackbone_weights.py CHANGED
@@ -1,20 +1,18 @@
1
  #!/usr/bin/env python3
2
- """One-time: extract prebackbone weights from a full YOLO best.pt checkpoint."""
3
 
4
  from __future__ import annotations
5
 
6
  import argparse
 
7
  import sys
8
  from pathlib import Path
9
 
10
  import torch
11
 
12
- # Allow running before vendor is installed
 
13
  _HERE = Path(__file__).resolve().parent
14
- for base in (_HERE / "vendor", _HERE.parent / "ultralytics"):
15
- if (base / "ultralytics" / "__init__.py").exists():
16
- sys.path.insert(0, str(base))
17
- break
18
 
19
 
20
  def _clean_state_dict(state: dict) -> dict:
@@ -23,26 +21,73 @@ def _clean_state_dict(state: dict) -> dict:
23
  return {k: v for k, v in state.items() if not any(k == s or k.endswith(f".{s}") for s in skip)}
24
 
25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  def extract(
27
  full_ckpt: Path,
28
  out_path: Path,
29
  prebackbone_name: str | None = None,
30
  ) -> Path:
31
- from ultralytics.nn.tasks import torch_safe_load
 
 
32
 
33
- ckpt, _ = torch_safe_load(str(full_ckpt))
34
  train_args = ckpt.get("train_args") or {}
35
  name = (prebackbone_name or train_args.get("prebackbone") or "A11_CA").upper()
36
  channels = int(train_args.get("channels", 3) or 3)
37
 
38
- model = (ckpt.get("ema") or ckpt.get("model")).float()
39
  pb = getattr(model, "prebackbone", None)
40
  if pb is None:
41
- raise RuntimeError(f"No prebackbone in {full_ckpt}")
42
 
43
  state = _clean_state_dict(pb.state_dict())
44
 
45
- # Save only tensors + metadata (no YOLO backbone/head)
 
 
 
 
 
 
 
 
 
 
 
 
46
  payload = {
47
  "prebackbone": name,
48
  "channels": channels,
@@ -52,7 +97,7 @@ def extract(
52
  out_path.parent.mkdir(parents=True, exist_ok=True)
53
  torch.save(payload, out_path)
54
 
55
- n_params = sum(t.numel() for t in payload["state_dict"].values())
56
  size_mb = out_path.stat().st_size / (1024 * 1024)
57
  print(f"Saved {out_path} ({size_mb:.2f} MB, {n_params:,} parameters, type={name})")
58
  return out_path
 
1
  #!/usr/bin/env python3
2
+ """Extract prebackbone-only weights from a full YOLO best.pt checkpoint."""
3
 
4
  from __future__ import annotations
5
 
6
  import argparse
7
+ import os
8
  import sys
9
  from pathlib import Path
10
 
11
  import torch
12
 
13
+ from a11_ca import build_prebackbone
14
+
15
  _HERE = Path(__file__).resolve().parent
 
 
 
 
16
 
17
 
18
  def _clean_state_dict(state: dict) -> dict:
 
21
  return {k: v for k, v in state.items() if not any(k == s or k.endswith(f".{s}") for s in skip)}
22
 
23
 
24
+ def _resolve_ultralytics_root() -> Path | None:
25
+ env = os.environ.get("ULTRALYTICS_ROOT", "").strip()
26
+ candidates = []
27
+ if env:
28
+ candidates.append(Path(env).expanduser())
29
+ candidates.extend((_HERE.parent / "ultralytics", _HERE / "vendor"))
30
+ for base in candidates:
31
+ if (base / "ultralytics" / "__init__.py").exists():
32
+ return base
33
+ if base.name == "ultralytics" and (base / "__init__.py").exists():
34
+ return base.parent
35
+ return None
36
+
37
+
38
+ def _load_full_checkpoint(full_ckpt: Path) -> tuple[dict, object]:
39
+ """Load best.pt; uses VYOLO ultralytics fork when present (pickled EMA model)."""
40
+ root = _resolve_ultralytics_root()
41
+ if root is not None:
42
+ root_str = str(root.resolve())
43
+ if root_str not in sys.path:
44
+ sys.path.insert(0, root_str)
45
+ from ultralytics.nn.tasks import torch_safe_load
46
+
47
+ ckpt, _ = torch_safe_load(str(full_ckpt))
48
+ return ckpt, ckpt.get("ema") or ckpt.get("model")
49
+
50
+ raise SystemExit(
51
+ f"Cannot unpickle {full_ckpt} without the VYOLO ultralytics fork.\n"
52
+ "One-time extraction from the training repo:\n"
53
+ " cd /path/to/VYOLO/hf_prebackbone_demo\n"
54
+ " ULTRALYTICS_ROOT=../ultralytics python extract_prebackbone_weights.py --ckpt ../ultralytics/.../best.pt\n"
55
+ "Inference only needs weights/prebackbone_a11_ca.pt (no ultralytics)."
56
+ )
57
+
58
+
59
  def extract(
60
  full_ckpt: Path,
61
  out_path: Path,
62
  prebackbone_name: str | None = None,
63
  ) -> Path:
64
+ ckpt, model = _load_full_checkpoint(full_ckpt)
65
+ if model is None:
66
+ raise RuntimeError(f"No model/ema in {full_ckpt}")
67
 
 
68
  train_args = ckpt.get("train_args") or {}
69
  name = (prebackbone_name or train_args.get("prebackbone") or "A11_CA").upper()
70
  channels = int(train_args.get("channels", 3) or 3)
71
 
 
72
  pb = getattr(model, "prebackbone", None)
73
  if pb is None:
74
+ raise RuntimeError(f"No prebackbone submodule in {full_ckpt}")
75
 
76
  state = _clean_state_dict(pb.state_dict())
77
 
78
+ # Verify keys match standalone architecture before saving
79
+ standalone = build_prebackbone(name, channels=channels)
80
+ if standalone is None:
81
+ raise RuntimeError(f"Unsupported prebackbone type: {name}")
82
+ expected = set(standalone.state_dict().keys())
83
+ got = set(state.keys())
84
+ if expected != got:
85
+ missing = expected - got
86
+ extra = got - expected
87
+ raise RuntimeError(
88
+ f"State dict mismatch for {name}: missing={sorted(missing)[:5]}, extra={sorted(extra)[:5]}"
89
+ )
90
+
91
  payload = {
92
  "prebackbone": name,
93
  "channels": channels,
 
97
  out_path.parent.mkdir(parents=True, exist_ok=True)
98
  torch.save(payload, out_path)
99
 
100
+ n_params = sum(t.numel() for t in state.values())
101
  size_mb = out_path.stat().st_size / (1024 * 1024)
102
  print(f"Saved {out_path} ({size_mb:.2f} MB, {n_params:,} parameters, type={name})")
103
  return out_path
gradio_patch.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Patch gradio_client JSON-schema helpers (bool additionalProperties with pydantic v2)."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ def apply() -> None:
7
+ try:
8
+ import gradio_client.utils as gc_utils
9
+ except ImportError:
10
+ return
11
+
12
+ if getattr(gc_utils, "_refdiffnet_patched", False):
13
+ return
14
+
15
+ _orig_get_type = gc_utils.get_type
16
+
17
+ def get_type(schema): # type: ignore[no-untyped-def]
18
+ if not isinstance(schema, dict):
19
+ return "Any"
20
+ return _orig_get_type(schema)
21
+
22
+ gc_utils.get_type = get_type # type: ignore[assignment]
23
+
24
+ _orig_json = gc_utils._json_schema_to_python_type
25
+
26
+ def _json_schema_to_python_type(schema, defs): # type: ignore[no-untyped-def]
27
+ if not isinstance(schema, dict):
28
+ return "Any"
29
+ return _orig_json(schema, defs)
30
+
31
+ gc_utils._json_schema_to_python_type = _json_schema_to_python_type # type: ignore[assignment]
32
+ gc_utils._refdiffnet_patched = True # type: ignore[attr-defined]
prebackbone_infer.py CHANGED
@@ -1,4 +1,4 @@
1
- """Prebackbone enrichment inference (A11_CA) — loads prebackbone weights only."""
2
 
3
  from __future__ import annotations
4
 
@@ -6,39 +6,27 @@ import os
6
  from pathlib import Path
7
  from typing import Any
8
 
9
- import cv2
10
  import numpy as np
11
  import torch
12
  from PIL import Image
13
 
14
- IMGSZ = int(os.environ.get("PREBACKBONE_IMGSZ", "640"))
15
- PREBACKBONE_ONLY_NAME = "prebackbone_a11_ca.pt"
16
-
17
-
18
- def _resolve_ultralytics_root() -> Path | None:
19
- here = Path(__file__).resolve().parent
20
- for base in (
21
- here / "vendor",
22
- here.parent / "ultralytics",
23
- Path(os.environ.get("ULTRALYTICS_ROOT", "")).expanduser(),
24
- ):
25
- if not base:
26
- continue
27
- if (base / "ultralytics" / "__init__.py").exists():
28
- return base
29
- if base.name == "ultralytics" and (base / "__init__.py").exists():
30
- return base.parent
31
- return None
32
 
 
33
 
34
- def _ensure_ultralytics_import() -> None:
35
- import sys
36
 
37
- root = _resolve_ultralytics_root()
38
- if root is not None:
39
- root_str = str(root.resolve())
40
- if root_str not in sys.path:
41
- sys.path.insert(0, root_str)
 
 
 
 
 
 
 
42
 
43
 
44
  def _here() -> Path:
@@ -53,7 +41,6 @@ def _prebackbone_only_path() -> Path:
53
 
54
 
55
  def _full_checkpoint_path() -> Path | None:
56
- """Fallback full YOLO ckpt — only used to auto-extract prebackbone weights."""
57
  env = os.environ.get("PREBACKBONE_FULL_CKPT", "").strip()
58
  if env:
59
  p = Path(env).expanduser()
@@ -83,7 +70,6 @@ def _download_hf_file(repo_id: str, filename: str) -> Path:
83
 
84
 
85
  def _resolve_weights_path() -> Path:
86
- """Prefer small prebackbone-only file; optional HF hub download."""
87
  pb_only = _prebackbone_only_path()
88
  if pb_only.exists():
89
  return pb_only
@@ -93,7 +79,7 @@ def _resolve_weights_path() -> Path:
93
  try:
94
  return _download_hf_file(hf_repo, PREBACKBONE_ONLY_NAME)
95
  except Exception:
96
- pass # try full ckpt filename below
97
  env_weights = os.environ.get("PREBACKBONE_WEIGHTS", PREBACKBONE_ONLY_NAME)
98
  return _download_hf_file(hf_repo, env_weights)
99
 
@@ -105,7 +91,6 @@ def _resolve_weights_path() -> Path:
105
 
106
 
107
  def _maybe_extract_from_full_ckpt(pb_only_path: Path) -> Path:
108
- """If only best.pt exists, extract prebackbone tensors once."""
109
  if pb_only_path.exists():
110
  return pb_only_path
111
  full = _full_checkpoint_path()
@@ -118,7 +103,6 @@ def _maybe_extract_from_full_ckpt(pb_only_path: Path) -> Path:
118
 
119
 
120
  def _filter_state_dict(state: dict, module: torch.nn.Module) -> dict:
121
- """Keep only keys that belong to the module (drops thop total_ops/total_params)."""
122
  expected = set(module.state_dict().keys())
123
  filtered = {k: v for k, v in state.items() if k in expected}
124
  if len(filtered) < len(expected):
@@ -128,9 +112,6 @@ def _filter_state_dict(state: dict, module: torch.nn.Module) -> dict:
128
 
129
 
130
  def _load_prebackbone_module(weights_path: Path, device: torch.device) -> torch.nn.Module:
131
- _ensure_ultralytics_import()
132
- from ultralytics.nn.prebackbone import build_prebackbone
133
-
134
  if not weights_path.exists():
135
  weights_path = _maybe_extract_from_full_ckpt(weights_path)
136
 
@@ -163,79 +144,46 @@ def _load_prebackbone_module(weights_path: Path, device: torch.device) -> torch.
163
  return module.to(device).eval()
164
 
165
 
166
- def _bgr_to_rgb(im_bgr: np.ndarray) -> np.ndarray:
167
- return cv2.cvtColor(im_bgr, cv2.COLOR_BGR2RGB)
168
-
169
-
170
- def _rgb_to_bgr(im_rgb: np.ndarray) -> np.ndarray:
171
- return cv2.cvtColor(im_rgb, cv2.COLOR_RGB2BGR)
172
-
173
-
174
- def _letterbox_pair_bgr(
175
- defect_bgr: np.ndarray,
176
- golden_bgr: np.ndarray,
177
- new_shape: tuple[int, int] = (IMGSZ, IMGSZ),
178
- ) -> tuple[np.ndarray, np.ndarray]:
179
- shape = defect_bgr.shape[:2]
180
- if golden_bgr.shape[:2] != shape:
181
- golden_bgr = cv2.resize(golden_bgr, (shape[1], shape[0]), interpolation=cv2.INTER_LINEAR)
182
-
183
- new_h, new_w = new_shape
184
- r = min(new_h / shape[0], new_w / shape[1])
185
- new_unpad = (round(shape[1] * r), round(shape[0] * r))
186
- dw, dh = (new_w - new_unpad[0]) / 2, (new_h - new_unpad[1]) / 2
187
-
188
- if shape[::-1] != new_unpad:
189
- defect_bgr = cv2.resize(defect_bgr, new_unpad, interpolation=cv2.INTER_LINEAR)
190
- golden_bgr = cv2.resize(golden_bgr, new_unpad, interpolation=cv2.INTER_LINEAR)
191
-
192
- top, bottom = round(dh - 0.1), round(dh + 0.1)
193
- left, right = round(dw - 0.1), round(dw + 0.1)
194
- pad = (114, 114, 114)
195
- defect_bgr = cv2.copyMakeBorder(defect_bgr, top, bottom, left, right, cv2.BORDER_CONSTANT, value=pad)
196
- golden_bgr = cv2.copyMakeBorder(golden_bgr, top, bottom, left, right, cv2.BORDER_CONSTANT, value=pad)
197
- return defect_bgr, golden_bgr
198
-
199
-
200
- def _img_to_tensor_rgb(im_rgb: np.ndarray, device: torch.device) -> torch.Tensor:
201
- x = torch.from_numpy(im_rgb).to(device=device)
202
- return x.permute(2, 0, 1).contiguous().float().unsqueeze(0) / 255.0
203
-
204
-
205
- def _tensor_to_rgb_u8(x: torch.Tensor) -> np.ndarray:
206
- if x.ndim == 4:
207
- x = x[0]
208
- x = x.detach().float().clamp(0.0, 1.0).cpu()
209
- return (x.permute(1, 2, 0).numpy() * 255.0).round().astype(np.uint8)
210
-
211
-
212
  def _load_image_rgb(image: str | Path | Image.Image | np.ndarray) -> np.ndarray:
213
  if isinstance(image, Image.Image):
214
- return np.array(image.convert("RGB"))
215
  if isinstance(image, np.ndarray):
216
  arr = image
217
  if arr.ndim == 2:
218
- return np.stack([arr, arr, arr], axis=-1)
219
  if arr.shape[2] == 4:
220
- return arr[..., :3]
221
- return arr[..., :3] if arr.shape[2] >= 3 else arr
222
  path = Path(image)
223
- bgr = cv2.imread(str(path))
224
- if bgr is None:
225
  raise FileNotFoundError(f"Unable to read image: {path}")
226
- return _bgr_to_rgb(bgr)
 
 
 
 
 
 
 
 
 
 
 
 
 
227
 
228
 
229
  class PreBackboneEnricher:
230
- """Runs A11_CA prebackbone only (no YOLO backbone/head loaded)."""
231
 
232
  def __init__(self, weights: str | Path | None = None, device: str | None = None):
233
  if device is None:
234
- device = "cuda" if torch.cuda.is_available() else "cpu"
 
 
235
  self.device = torch.device(device)
236
  self.weights = Path(weights) if weights else _resolve_weights_path()
237
  self.prebackbone = _load_prebackbone_module(self.weights, self.device)
238
- self.imgsz = IMGSZ
239
 
240
  @torch.inference_mode()
241
  def enrich(
@@ -243,26 +191,17 @@ class PreBackboneEnricher:
243
  defect: str | Path | Image.Image | np.ndarray,
244
  reference: str | Path | Image.Image | np.ndarray,
245
  *,
246
- letterbox: bool = True,
247
  return_reference: bool = False,
248
  ) -> np.ndarray | tuple[np.ndarray, np.ndarray, np.ndarray]:
249
- defect_rgb0 = _load_image_rgb(defect)
250
- golden_rgb0 = _load_image_rgb(reference)
251
-
252
- defect_bgr0 = _rgb_to_bgr(defect_rgb0)
253
- golden_bgr0 = _rgb_to_bgr(golden_rgb0)
254
-
255
- if letterbox:
256
- defect_bgr, golden_bgr = _letterbox_pair_bgr(defect_bgr0, golden_bgr0, (self.imgsz, self.imgsz))
257
- else:
258
- if defect_bgr0.shape != golden_bgr0.shape:
259
- golden_bgr0 = cv2.resize(
260
- golden_bgr0, (defect_bgr0.shape[1], defect_bgr0.shape[0]), interpolation=cv2.INTER_LINEAR
261
- )
262
- defect_bgr, golden_bgr = defect_bgr0, golden_bgr0
263
-
264
- defect_rgb = _bgr_to_rgb(defect_bgr)
265
- golden_rgb = _bgr_to_rgb(golden_bgr)
266
 
267
  defect_t = _img_to_tensor_rgb(defect_rgb, self.device)
268
  golden_t = _img_to_tensor_rgb(golden_rgb, self.device)
 
1
+ """Prebackbone enrichment inference (A11_CA) — standalone, no ultralytics."""
2
 
3
  from __future__ import annotations
4
 
 
6
  from pathlib import Path
7
  from typing import Any
8
 
 
9
  import numpy as np
10
  import torch
11
  from PIL import Image
12
 
13
+ from a11_ca import build_prebackbone
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
+ PREBACKBONE_ONLY_NAME = "prebackbone_a11_ca.pt"
16
 
 
 
17
 
18
+ def _to_numpy_u8(arr) -> np.ndarray:
19
+ """Canonical uint8 HWC in conda numpy (avoids ~/.local numpy vs torch/opencv)."""
20
+ if isinstance(arr, Image.Image):
21
+ arr = arr.convert("RGB")
22
+ w, h = arr.size
23
+ return np.frombuffer(arr.tobytes(), dtype=np.uint8).reshape((h, w, 3)).copy()
24
+ raw = np.asarray(arr)
25
+ if raw.ndim == 2:
26
+ raw = np.stack([raw, raw, raw], axis=-1)
27
+ elif raw.shape[-1] > 3:
28
+ raw = raw[..., :3]
29
+ return np.array(raw.tolist(), dtype=np.uint8, order="C")
30
 
31
 
32
  def _here() -> Path:
 
41
 
42
 
43
  def _full_checkpoint_path() -> Path | None:
 
44
  env = os.environ.get("PREBACKBONE_FULL_CKPT", "").strip()
45
  if env:
46
  p = Path(env).expanduser()
 
70
 
71
 
72
  def _resolve_weights_path() -> Path:
 
73
  pb_only = _prebackbone_only_path()
74
  if pb_only.exists():
75
  return pb_only
 
79
  try:
80
  return _download_hf_file(hf_repo, PREBACKBONE_ONLY_NAME)
81
  except Exception:
82
+ pass
83
  env_weights = os.environ.get("PREBACKBONE_WEIGHTS", PREBACKBONE_ONLY_NAME)
84
  return _download_hf_file(hf_repo, env_weights)
85
 
 
91
 
92
 
93
  def _maybe_extract_from_full_ckpt(pb_only_path: Path) -> Path:
 
94
  if pb_only_path.exists():
95
  return pb_only_path
96
  full = _full_checkpoint_path()
 
103
 
104
 
105
  def _filter_state_dict(state: dict, module: torch.nn.Module) -> dict:
 
106
  expected = set(module.state_dict().keys())
107
  filtered = {k: v for k, v in state.items() if k in expected}
108
  if len(filtered) < len(expected):
 
112
 
113
 
114
  def _load_prebackbone_module(weights_path: Path, device: torch.device) -> torch.nn.Module:
 
 
 
115
  if not weights_path.exists():
116
  weights_path = _maybe_extract_from_full_ckpt(weights_path)
117
 
 
144
  return module.to(device).eval()
145
 
146
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
  def _load_image_rgb(image: str | Path | Image.Image | np.ndarray) -> np.ndarray:
148
  if isinstance(image, Image.Image):
149
+ return _to_numpy_u8(image.convert("RGB"))
150
  if isinstance(image, np.ndarray):
151
  arr = image
152
  if arr.ndim == 2:
153
+ return _to_numpy_u8(np.stack([arr, arr, arr], axis=-1))
154
  if arr.shape[2] == 4:
155
+ return _to_numpy_u8(arr[..., :3])
156
+ return _to_numpy_u8(arr[..., :3] if arr.shape[2] >= 3 else arr)
157
  path = Path(image)
158
+ if not path.exists():
 
159
  raise FileNotFoundError(f"Unable to read image: {path}")
160
+ return _to_numpy_u8(Image.open(path).convert("RGB"))
161
+
162
+
163
+ def _img_to_tensor_rgb(im_rgb: np.ndarray, device: torch.device) -> torch.Tensor:
164
+ arr = np.ascontiguousarray(_to_numpy_u8(im_rgb), dtype=np.uint8)
165
+ x = torch.tensor(arr, device=device, dtype=torch.float32)
166
+ return x.permute(2, 0, 1).contiguous().unsqueeze(0) / 255.0
167
+
168
+
169
+ def _tensor_to_rgb_u8(x: torch.Tensor) -> np.ndarray:
170
+ if x.ndim == 4:
171
+ x = x[0]
172
+ hwc = x.detach().float().clamp(0.0, 1.0).mul(255.0).round().byte().permute(1, 2, 0).cpu()
173
+ return np.array(hwc.tolist(), dtype=np.uint8)
174
 
175
 
176
  class PreBackboneEnricher:
177
+ """Runs A11_CA prebackbone only (defect + golden -> enriched, same spatial size)."""
178
 
179
  def __init__(self, weights: str | Path | None = None, device: str | None = None):
180
  if device is None:
181
+ device = os.environ.get("PREBACKBONE_DEVICE") or (
182
+ "cuda" if torch.cuda.is_available() else "cpu"
183
+ )
184
  self.device = torch.device(device)
185
  self.weights = Path(weights) if weights else _resolve_weights_path()
186
  self.prebackbone = _load_prebackbone_module(self.weights, self.device)
 
187
 
188
  @torch.inference_mode()
189
  def enrich(
 
191
  defect: str | Path | Image.Image | np.ndarray,
192
  reference: str | Path | Image.Image | np.ndarray,
193
  *,
 
194
  return_reference: bool = False,
195
  ) -> np.ndarray | tuple[np.ndarray, np.ndarray, np.ndarray]:
196
+ defect_rgb = _load_image_rgb(defect)
197
+ golden_rgb = _load_image_rgb(reference)
198
+
199
+ if defect_rgb.shape != golden_rgb.shape:
200
+ raise ValueError(
201
+ f"Defect and reference must have the same shape (HxWxC), "
202
+ f"got {defect_rgb.shape} vs {golden_rgb.shape}. "
203
+ "Use pre-aligned pairs (e.g. training prebackbone_samples) with no extra resizing."
204
+ )
 
 
 
 
 
 
 
 
205
 
206
  defect_t = _img_to_tensor_rgb(defect_rgb, self.device)
207
  golden_t = _img_to_tensor_rgb(golden_rgb, self.device)
prepare_space.sh ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Bundle weights + examples for Hugging Face Space upload (standalone, no vendor/).
3
+ set -euo pipefail
4
+
5
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
6
+ VYOLO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
7
+ ULTRA_SRC="${VYOLO_ROOT}/ultralytics"
8
+ SPACE_DIR="${SCRIPT_DIR}"
9
+ WEIGHTS_SRC="${ULTRA_SRC}/Proposed/yolo12_training/HRIPCB_Results/yolo12n_hripcb_200epochs_batch16/weights/best.pt"
10
+ SAMPLES_SRC="${ULTRA_SRC}/Proposed/yolo12_training/HRIPCB_Results/yolo12n_hripcb_200epochs_batch16/prebackbone_samples"
11
+
12
+ echo "==> Preparing Hugging Face Space in ${SPACE_DIR}"
13
+
14
+ # 1) Weights — extract prebackbone-only (~few MB) from best.pt
15
+ mkdir -p "${SPACE_DIR}/weights"
16
+ PB_ONLY="${SPACE_DIR}/weights/prebackbone_a11_ca.pt"
17
+ if [[ -f "${WEIGHTS_SRC}" ]]; then
18
+ PYTHON="${PYTHON:-python3}"
19
+ if "${PYTHON}" -c "import torch" 2>/dev/null; then
20
+ export ULTRALYTICS_ROOT="${ULTRA_SRC}"
21
+ (cd "${SPACE_DIR}" && "${PYTHON}" extract_prebackbone_weights.py --ckpt "${WEIGHTS_SRC}" --out "${PB_ONLY}")
22
+ echo " Prebackbone-only weights: $(du -h "${PB_ONLY}" | cut -f1)"
23
+ if [[ "${INCLUDE_FULL_CKPT:-0}" == "1" ]]; then
24
+ cp -f "${WEIGHTS_SRC}" "${SPACE_DIR}/weights/best.pt"
25
+ echo " Also copied full best.pt (optional fallback)"
26
+ fi
27
+ else
28
+ echo " WARN: torch not available — place prebackbone_a11_ca.pt in weights/ manually"
29
+ fi
30
+ else
31
+ echo " WARN: ${WEIGHTS_SRC} not found — place prebackbone_a11_ca.pt in weights/"
32
+ fi
33
+
34
+ # 2) Example pairs for Gradio Examples
35
+ EX_DIR="${SPACE_DIR}/examples"
36
+ rm -rf "${EX_DIR}"
37
+ mkdir -p "${EX_DIR}"
38
+ EPOCH070="${SAMPLES_SRC}/epoch_070"
39
+ if [[ -d "${EPOCH070}" ]]; then
40
+ for inp in "${EPOCH070}"/*_input.jpg; do
41
+ [[ -f "${inp}" ]] || continue
42
+ base="$(basename "${inp}")"
43
+ ref="${inp/_input./_reference.}"
44
+ if [[ -f "${ref}" ]]; then
45
+ cp -f "${inp}" "${EX_DIR}/${base}"
46
+ cp -f "${ref}" "${EX_DIR}/${base/_input./_reference.}"
47
+ fi
48
+ done
49
+ fi
50
+ if [[ -d "${SAMPLES_SRC}" ]]; then
51
+ mapfile -t _inputs < <(find "${SAMPLES_SRC}" -name '*_input.jpg' | head -6)
52
+ for inp in "${_inputs[@]}"; do
53
+ base="$(basename "${inp}")"
54
+ [[ -f "${EX_DIR}/${base}" ]] && continue
55
+ ref="${inp/_input./_reference.}"
56
+ if [[ -f "${ref}" ]]; then
57
+ cp -f "${inp}" "${EX_DIR}/${base}"
58
+ cp -f "${ref}" "${EX_DIR}/${base/_input./_reference.}"
59
+ fi
60
+ done
61
+ unset _inputs
62
+ fi
63
+ if compgen -G "${EX_DIR}/*_input.jpg" >/dev/null; then
64
+ echo " Examples: $(ls -1 "${EX_DIR}"/*_input.jpg | wc -l) pairs"
65
+ else
66
+ echo " WARN: no prebackbone_samples found for examples"
67
+ fi
68
+
69
+ # 3) Drop legacy vendored ultralytics if present
70
+ if [[ -d "${SPACE_DIR}/vendor" ]]; then
71
+ rm -rf "${SPACE_DIR}/vendor"
72
+ echo " Removed legacy vendor/ (standalone demo)"
73
+ fi
74
+
75
+ TOTAL="$(du -sh "${SPACE_DIR}" | cut -f1)"
76
+ echo "==> Done (total ${TOTAL}). Next:"
77
+ echo " cd ${SPACE_DIR}"
78
+ echo " git init && git lfs install && git lfs track '*.pt'"
79
+ echo " git add . && git commit -m 'RefDiffNet standalone demo'"
80
+ echo " git remote add origin https://huggingface.co/spaces/USER/SPACE"
81
+ echo " git push"
requirements.txt CHANGED
@@ -1,16 +1,11 @@
1
- # Gradio version is set by README sdk_version on Hugging Face Spaces (4.44.0)
2
  # Python 3.13+ removed stdlib audioop; pydub (gradio dep) needs this backport
3
  audioop-lts>=0.2.1; python_version >= "3.13"
4
  torch>=2.0.0
5
  torchvision>=0.15.0
6
- opencv-python-headless>=4.8.0
7
- pillow>=10.0.0
8
- numpy>=1.23.0
9
- pyyaml>=6.0
10
- # Gradio 4.44 needs HfFolder (removed in huggingface_hub 1.x)
11
  huggingface_hub>=0.23.0,<1.0
12
- matplotlib>=3.7.0
13
- scipy>=1.10.0
14
- psutil>=5.9.0
15
- polars>=0.20.0
16
- ultralytics-thop>=2.0.18
 
1
+ # Gradio version matches README sdk_version (Hugging Face Spaces)
2
  # Python 3.13+ removed stdlib audioop; pydub (gradio dep) needs this backport
3
  audioop-lts>=0.2.1; python_version >= "3.13"
4
  torch>=2.0.0
5
  torchvision>=0.15.0
6
+ pillow>=10.0.0,<11
7
+ # torch 2.2.x wheels are built against NumPy 1.x
8
+ numpy>=1.23.0,<2
9
+ gradio==5.16.1
10
+ gradio-client==1.7.0
11
  huggingface_hub>=0.23.0,<1.0
 
 
 
 
 
setup.sh CHANGED
@@ -1,18 +1,12 @@
1
  #!/usr/bin/env bash
2
- # Hugging Face Spaces: install vendored custom Ultralytics before app starts.
3
  set -euo pipefail
4
  cd "$(dirname "$0")"
5
- # HF base image may install huggingface_hub 1.x; Gradio 4.x needs <1.0 (HfFolder)
6
- pip install -q "huggingface_hub>=0.23.0,<1.0"
7
- # Fix Gradio 4.44.0 + pydantic schema bug (TypeError: bool is not iterable)
8
- pip install -q "gradio-client>=1.4.0,<2.0.0"
9
- export YOLO_CONFIG_DIR="${YOLO_CONFIG_DIR:-/tmp/Ultralytics}"
10
  export GRADIO_SERVER_NAME="${GRADIO_SERVER_NAME:-0.0.0.0}"
11
- mkdir -p "${YOLO_CONFIG_DIR}"
12
-
13
- if [[ -d vendor ]]; then
14
- pip install -q -e ./vendor
15
- echo "Installed custom ultralytics from ./vendor"
16
- else
17
- echo "WARN: vendor/ missing — run prepare_space.sh before deploying"
18
- fi
 
1
  #!/usr/bin/env bash
2
+ # Hugging Face Spaces: install deps before app starts (no ultralytics).
3
  set -euo pipefail
4
  cd "$(dirname "$0")"
5
+ pip install -q -r requirements.txt
6
+ pip install -q "numpy>=1.23.0,<2" "gradio-client==1.7.0"
7
+ python -c "import gradio_patch; gradio_patch.apply(); print('gradio_patch OK')"
 
 
8
  export GRADIO_SERVER_NAME="${GRADIO_SERVER_NAME:-0.0.0.0}"
9
+ export GRADIO_SERVER_PORT="${GRADIO_SERVER_PORT:-${PORT:-7860}}"
10
+ export PRELOAD_MODEL="${PRELOAD_MODEL:-1}"
11
+ export PREBACKBONE_ONLY_WEIGHTS="${PREBACKBONE_ONLY_WEIGHTS:-$(pwd)/weights/prebackbone_a11_ca.pt}"
12
+ echo "RefDiffNet: standalone A11_CA (GRADIO_SERVER_NAME=${GRADIO_SERVER_NAME})"
 
 
 
 
vendor/pyproject.toml DELETED
@@ -1,194 +0,0 @@
1
- # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
-
3
- # Overview:
4
- # This pyproject.toml file manages the build, packaging, and distribution of the Ultralytics library.
5
- # It defines essential project metadata, dependencies, and settings used to develop and deploy the library.
6
-
7
- # Key Sections:
8
- # - [build-system]: Specifies the build requirements and backend (e.g., setuptools, wheel).
9
- # - [project]: Includes details like name, version, description, authors, dependencies and more.
10
- # - [project.optional-dependencies]: Provides additional, optional packages for extended features.
11
- # - [tool.*]: Configures settings for various tools (pytest, yapf, etc.) used in the project.
12
-
13
- # Installation:
14
- # The Ultralytics library can be installed using the command: 'pip install ultralytics'
15
- # For development purposes, you can install the package in editable mode with: 'pip install -e .'
16
- # This approach allows for real-time code modifications without the need for re-installation.
17
-
18
- # Documentation:
19
- # For comprehensive documentation and usage instructions, visit: https://docs.ultralytics.com
20
-
21
- [build-system]
22
- requires = ["setuptools>=70.0.0,<=82.0.1", "wheel"]
23
- build-backend = "setuptools.build_meta"
24
-
25
- # Project settings -----------------------------------------------------------------------------------------------------
26
- [project]
27
- name = "ultralytics"
28
- dynamic = ["version"]
29
- description = "Ultralytics YOLO 🚀 for SOTA object detection, multi-object tracking, instance segmentation, pose estimation and image classification."
30
- readme = "README.md"
31
- requires-python = ">=3.8"
32
- license = { "text" = "AGPL-3.0" }
33
- keywords = ["machine-learning", "deep-learning", "computer-vision", "ML", "DL", "AI", "YOLO", "YOLOv3", "YOLOv5", "YOLOv8", "YOLOv9", "YOLOv10", "YOLO11", "HUB", "Ultralytics"]
34
- authors = [
35
- { name = "Glenn Jocher", email = "glenn.jocher@ultralytics.com" },
36
- { name = "Jing Qiu", email = "jing.qiu@ultralytics.com" },
37
- ]
38
- maintainers = [
39
- { name = "Ultralytics", email = "hello@ultralytics.com" },
40
- ]
41
- classifiers = [
42
- "Development Status :: 4 - Beta",
43
- "Intended Audience :: Developers",
44
- "Intended Audience :: Education",
45
- "Intended Audience :: Science/Research",
46
- "License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)",
47
- "Programming Language :: Python :: 3",
48
- "Programming Language :: Python :: 3.8",
49
- "Programming Language :: Python :: 3.9",
50
- "Programming Language :: Python :: 3.10",
51
- "Programming Language :: Python :: 3.11",
52
- "Programming Language :: Python :: 3.12",
53
- "Topic :: Software Development",
54
- "Topic :: Scientific/Engineering",
55
- "Topic :: Scientific/Engineering :: Artificial Intelligence",
56
- "Topic :: Scientific/Engineering :: Image Recognition",
57
- "Operating System :: POSIX :: Linux",
58
- "Operating System :: MacOS",
59
- "Operating System :: Microsoft :: Windows",
60
- ]
61
-
62
- # Required dependencies ------------------------------------------------------------------------------------------------
63
- dependencies = [
64
- "numpy>=1.23.0",
65
- "matplotlib>=3.3.0",
66
- "opencv-python>=4.6.0",
67
- "pillow>=7.1.2",
68
- "pyyaml>=5.3.1",
69
- "requests>=2.23.0",
70
- "scipy>=1.4.1",
71
- "torch>=1.8.0",
72
- "torch>=1.8.0,!=2.4.0; sys_platform == 'win32'", # Windows CPU errors w/ 2.4.0 https://github.com/ultralytics/ultralytics/issues/15049
73
- "torchvision>=0.9.0",
74
- "psutil>=5.8.0", # system utilization
75
- "polars>=0.20.0",
76
- "ultralytics-thop>=2.0.18", # FLOPs computation https://github.com/ultralytics/thop
77
- ]
78
-
79
- # Optional dependencies ------------------------------------------------------------------------------------------------
80
- [project.optional-dependencies]
81
- dev = [
82
- "ipython",
83
- "pytest",
84
- "pytest-cov",
85
- "coverage[toml]",
86
- "zensical>=0.0.15; python_version >= '3.10'",
87
- "mkdocs-ultralytics-plugin>=0.2.4", # for meta descriptions and images, dates and authors
88
- "minijinja>=2.0.0", # render docs macros without mkdocs-macros-plugin
89
- ]
90
- export = [
91
- "numpy<2.0.0", # TF 2.20 compatibility
92
- "onnx>=1.12.0; platform_system != 'Darwin'", # ONNX export
93
- "onnx>=1.12.0,<1.18.0; platform_system == 'Darwin'", # TF inference hanging on MacOS (tested up to onnx==1.20.0)
94
- "onnxslim>=0.1.82",
95
- "coremltools>=9.0; platform_system != 'Windows' and python_version <= '3.13'", # CoreML supported on macOS and Linux
96
- "scikit-learn>=1.3.2; platform_system != 'Windows' and python_version <= '3.13'", # CoreML k-means quantization
97
- "openvino>=2024.0.0", # OpenVINO export
98
- "tensorflow>=2.0.0,<=2.19.0", # TF bug https://github.com/ultralytics/ultralytics/issues/5161
99
- "tensorflowjs>=2.0.0", # TF.js export, automatically installs tensorflow
100
- "tensorstore>=0.1.63; platform_machine == 'aarch64' and python_version >= '3.9'", # for TF Raspberry Pi exports
101
- "h5py!=3.11.0; platform_machine == 'aarch64'", # fix h5py build issues due to missing aarch64 wheels in 3.11 release
102
- "setuptools<=81.0.0", # pin due to >=82.0.0 breaking tensorflow.js package
103
- "packaging>=26.0; platform_machine == 'aarch64' and platform_system == 'Linux' and python_version >= '3.9'", # IMX export bug
104
- ]
105
- solutions = [
106
- "shapely>=2.0.0", # shapely for point and polygon data matching
107
- "streamlit>=1.51.0; python_version >= '3.10'", # for live inference on web browser, i.e `yolo streamlit-predict`
108
- "streamlit>=1.29.0,<1.51.0; python_version < '3.10' and (python_version < '3.9' or platform_machine != 'aarch64' or platform_system != 'Linux')",
109
- "flask>=3.0.1", # for similarity search solution
110
- ]
111
- logging = [
112
- "wandb", # https://docs.ultralytics.com/integrations/weights-biases/
113
- "tensorboard", # https://docs.ultralytics.com/integrations/tensorboard/
114
- "mlflow", # https://docs.ultralytics.com/integrations/mlflow/
115
- ]
116
- extra = [
117
- "ipython", # interactive notebook
118
- "albumentations>=1.4.6", # training augmentations
119
- "faster-coco-eval>=1.6.7", # COCO mAP
120
- ]
121
- typing = [
122
- "scipy-stubs>=1.14.1.4; python_version >= '3.10'",
123
- "types-pillow",
124
- "types-psutil",
125
- "types-pyyaml",
126
- "types-requests",
127
- "types-shapely",
128
- ]
129
-
130
- [project.urls]
131
- "Homepage" = "https://ultralytics.com"
132
- "Source" = "https://github.com/ultralytics/ultralytics"
133
- "Documentation" = "https://docs.ultralytics.com"
134
- "Bug Reports" = "https://github.com/ultralytics/ultralytics/issues"
135
- "Changelog" = "https://github.com/ultralytics/ultralytics/releases"
136
-
137
- [project.scripts]
138
- yolo = "ultralytics.cfg:entrypoint"
139
- ultralytics = "ultralytics.cfg:entrypoint"
140
-
141
- # Tools settings -------------------------------------------------------------------------------------------------------
142
- [tool.setuptools] # configuration specific to the `setuptools` build backend.
143
- packages = { find = { where = ["."], include = ["ultralytics", "ultralytics.*"] } }
144
- # Tests included below for checking Conda builds in https://github.com/conda-forge/ultralytics-feedstock
145
- package-data = { "ultralytics" = ["**/*.yaml", "**/*.sh", "../tests/*.py"], "ultralytics.assets" = ["*.jpg"], "ultralytics.solutions.templates" = ["*.html"]}
146
-
147
- [tool.setuptools.dynamic]
148
- version = { attr = "ultralytics.__version__" }
149
-
150
- [tool.pytest.ini_options]
151
- addopts = "--doctest-modules --durations=30 --color=yes"
152
- markers = [
153
- "slow: skip slow tests unless --slow is set",
154
- ]
155
- norecursedirs = [".git", "dist", "build"]
156
-
157
- [tool.coverage.run]
158
- source = ["ultralytics/"]
159
- data_file = "tests/.coverage"
160
- omit = ["ultralytics/utils/callbacks/*"]
161
-
162
- [tool.isort]
163
- line_length = 120
164
- multi_line_output = 0
165
-
166
- [tool.yapf]
167
- based_on_style = "pep8"
168
- spaces_before_comment = 2
169
- column_limit = 120
170
- coalesce_brackets = true
171
- spaces_around_power_operator = true
172
- space_between_ending_comma_and_closing_bracket = true
173
- split_before_closing_bracket = false
174
- split_before_first_argument = false
175
-
176
- [tool.ruff]
177
- line-length = 120
178
-
179
- [tool.ruff.format]
180
- docstring-code-format = true
181
-
182
- [tool.ruff.lint.pydocstyle]
183
- convention = "google"
184
-
185
- [tool.docformatter]
186
- wrap-summaries = 120
187
- wrap-descriptions = 120
188
- pre-summary-newline = true
189
- close-quotes-on-newline = true
190
- in-place = true
191
-
192
- [tool.codespell]
193
- ignore-words-list = "grey,writeable,finalY,RepResNet,Idenfy,WIT,Smoot,EHR,ROUGE,ALS,iTerm,Carmel,FPR,Hach,Calle,ore,COO,MOT,crate,nd,ned,strack,dota,ane,segway,fo,gool,winn,commend,bloc,nam,afterall,skelton,goin"
194
- skip = "*.pt,*.pth,*.torchscript,*.onnx,*.tflite,*.pb,*.bin,*.param,*.mlmodel,*.engine,*.npy,*.data*,*.csv,*pnnx*,*venv*,*translat*,*lock*,__pycache__*,*.ico,*.jpg,*.png,*.webp,*.avif,*.mp4,*.mov,/runs,/.git,./docs/??/*.md,./docs/mkdocs_??.yml"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
vendor/ultralytics.egg-info/PKG-INFO DELETED
@@ -1,88 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: ultralytics
3
- Version: 8.4.21
4
- Summary: Ultralytics YOLO 🚀 for SOTA object detection, multi-object tracking, instance segmentation, pose estimation and image classification.
5
- Author-email: Glenn Jocher <glenn.jocher@ultralytics.com>, Jing Qiu <jing.qiu@ultralytics.com>
6
- Maintainer-email: Ultralytics <hello@ultralytics.com>
7
- License: AGPL-3.0
8
- Project-URL: Homepage, https://ultralytics.com
9
- Project-URL: Source, https://github.com/ultralytics/ultralytics
10
- Project-URL: Documentation, https://docs.ultralytics.com
11
- Project-URL: Bug Reports, https://github.com/ultralytics/ultralytics/issues
12
- Project-URL: Changelog, https://github.com/ultralytics/ultralytics/releases
13
- Keywords: machine-learning,deep-learning,computer-vision,ML,DL,AI,YOLO,YOLOv3,YOLOv5,YOLOv8,YOLOv9,YOLOv10,YOLO11,HUB,Ultralytics
14
- Classifier: Development Status :: 4 - Beta
15
- Classifier: Intended Audience :: Developers
16
- Classifier: Intended Audience :: Education
17
- Classifier: Intended Audience :: Science/Research
18
- Classifier: License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)
19
- Classifier: Programming Language :: Python :: 3
20
- Classifier: Programming Language :: Python :: 3.8
21
- Classifier: Programming Language :: Python :: 3.9
22
- Classifier: Programming Language :: Python :: 3.10
23
- Classifier: Programming Language :: Python :: 3.11
24
- Classifier: Programming Language :: Python :: 3.12
25
- Classifier: Topic :: Software Development
26
- Classifier: Topic :: Scientific/Engineering
27
- Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
28
- Classifier: Topic :: Scientific/Engineering :: Image Recognition
29
- Classifier: Operating System :: POSIX :: Linux
30
- Classifier: Operating System :: MacOS
31
- Classifier: Operating System :: Microsoft :: Windows
32
- Requires-Python: >=3.8
33
- Description-Content-Type: text/markdown
34
- Requires-Dist: numpy>=1.23.0
35
- Requires-Dist: matplotlib>=3.3.0
36
- Requires-Dist: opencv-python>=4.6.0
37
- Requires-Dist: pillow>=7.1.2
38
- Requires-Dist: pyyaml>=5.3.1
39
- Requires-Dist: requests>=2.23.0
40
- Requires-Dist: scipy>=1.4.1
41
- Requires-Dist: torch>=1.8.0
42
- Requires-Dist: torch!=2.4.0,>=1.8.0; sys_platform == "win32"
43
- Requires-Dist: torchvision>=0.9.0
44
- Requires-Dist: psutil>=5.8.0
45
- Requires-Dist: polars>=0.20.0
46
- Requires-Dist: ultralytics-thop>=2.0.18
47
- Provides-Extra: dev
48
- Requires-Dist: ipython; extra == "dev"
49
- Requires-Dist: pytest; extra == "dev"
50
- Requires-Dist: pytest-cov; extra == "dev"
51
- Requires-Dist: coverage[toml]; extra == "dev"
52
- Requires-Dist: zensical>=0.0.15; python_version >= "3.10" and extra == "dev"
53
- Requires-Dist: mkdocs-ultralytics-plugin>=0.2.4; extra == "dev"
54
- Requires-Dist: minijinja>=2.0.0; extra == "dev"
55
- Provides-Extra: export
56
- Requires-Dist: numpy<2.0.0; extra == "export"
57
- Requires-Dist: onnx>=1.12.0; platform_system != "Darwin" and extra == "export"
58
- Requires-Dist: onnx<1.18.0,>=1.12.0; platform_system == "Darwin" and extra == "export"
59
- Requires-Dist: onnxslim>=0.1.82; extra == "export"
60
- Requires-Dist: coremltools>=9.0; (platform_system != "Windows" and python_version <= "3.13") and extra == "export"
61
- Requires-Dist: scikit-learn>=1.3.2; (platform_system != "Windows" and python_version <= "3.13") and extra == "export"
62
- Requires-Dist: openvino>=2024.0.0; extra == "export"
63
- Requires-Dist: tensorflow<=2.19.0,>=2.0.0; extra == "export"
64
- Requires-Dist: tensorflowjs>=2.0.0; extra == "export"
65
- Requires-Dist: tensorstore>=0.1.63; (platform_machine == "aarch64" and python_version >= "3.9") and extra == "export"
66
- Requires-Dist: h5py!=3.11.0; platform_machine == "aarch64" and extra == "export"
67
- Requires-Dist: setuptools<=81.0.0; extra == "export"
68
- Requires-Dist: packaging>=26.0; (platform_machine == "aarch64" and platform_system == "Linux" and python_version >= "3.9") and extra == "export"
69
- Provides-Extra: solutions
70
- Requires-Dist: shapely>=2.0.0; extra == "solutions"
71
- Requires-Dist: streamlit>=1.51.0; python_version >= "3.10" and extra == "solutions"
72
- Requires-Dist: streamlit<1.51.0,>=1.29.0; (python_version < "3.10" and (python_version < "3.9" or platform_machine != "aarch64" or platform_system != "Linux")) and extra == "solutions"
73
- Requires-Dist: flask>=3.0.1; extra == "solutions"
74
- Provides-Extra: logging
75
- Requires-Dist: wandb; extra == "logging"
76
- Requires-Dist: tensorboard; extra == "logging"
77
- Requires-Dist: mlflow; extra == "logging"
78
- Provides-Extra: extra
79
- Requires-Dist: ipython; extra == "extra"
80
- Requires-Dist: albumentations>=1.4.6; extra == "extra"
81
- Requires-Dist: faster-coco-eval>=1.6.7; extra == "extra"
82
- Provides-Extra: typing
83
- Requires-Dist: scipy-stubs>=1.14.1.4; python_version >= "3.10" and extra == "typing"
84
- Requires-Dist: types-pillow; extra == "typing"
85
- Requires-Dist: types-psutil; extra == "typing"
86
- Requires-Dist: types-pyyaml; extra == "typing"
87
- Requires-Dist: types-requests; extra == "typing"
88
- Requires-Dist: types-shapely; extra == "typing"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
vendor/ultralytics.egg-info/SOURCES.txt DELETED
@@ -1,308 +0,0 @@
1
- pyproject.toml
2
- ultralytics/__init__.py
3
- ultralytics/py.typed
4
- ultralytics.egg-info/PKG-INFO
5
- ultralytics.egg-info/SOURCES.txt
6
- ultralytics.egg-info/dependency_links.txt
7
- ultralytics.egg-info/entry_points.txt
8
- ultralytics.egg-info/requires.txt
9
- ultralytics.egg-info/top_level.txt
10
- ultralytics/assets/bus.jpg
11
- ultralytics/assets/zidane.jpg
12
- ultralytics/cfg/__init__.py
13
- ultralytics/cfg/default.yaml
14
- ultralytics/cfg/datasets/Argoverse.yaml
15
- ultralytics/cfg/datasets/DOTAv1.5.yaml
16
- ultralytics/cfg/datasets/DOTAv1.yaml
17
- ultralytics/cfg/datasets/GlobalWheat2020.yaml
18
- ultralytics/cfg/datasets/HomeObjects-3K.yaml
19
- ultralytics/cfg/datasets/ImageNet.yaml
20
- ultralytics/cfg/datasets/Objects365.yaml
21
- ultralytics/cfg/datasets/SKU-110K.yaml
22
- ultralytics/cfg/datasets/TT100K.yaml
23
- ultralytics/cfg/datasets/VOC.yaml
24
- ultralytics/cfg/datasets/VisDrone.yaml
25
- ultralytics/cfg/datasets/african-wildlife.yaml
26
- ultralytics/cfg/datasets/brain-tumor.yaml
27
- ultralytics/cfg/datasets/carparts-seg.yaml
28
- ultralytics/cfg/datasets/coco-pose.yaml
29
- ultralytics/cfg/datasets/coco.yaml
30
- ultralytics/cfg/datasets/coco12-formats.yaml
31
- ultralytics/cfg/datasets/coco128-seg.yaml
32
- ultralytics/cfg/datasets/coco128.yaml
33
- ultralytics/cfg/datasets/coco8-grayscale.yaml
34
- ultralytics/cfg/datasets/coco8-multispectral.yaml
35
- ultralytics/cfg/datasets/coco8-pose.yaml
36
- ultralytics/cfg/datasets/coco8-seg.yaml
37
- ultralytics/cfg/datasets/coco8.yaml
38
- ultralytics/cfg/datasets/construction-ppe.yaml
39
- ultralytics/cfg/datasets/crack-seg.yaml
40
- ultralytics/cfg/datasets/dog-pose.yaml
41
- ultralytics/cfg/datasets/dota8-multispectral.yaml
42
- ultralytics/cfg/datasets/dota8.yaml
43
- ultralytics/cfg/datasets/hand-keypoints.yaml
44
- ultralytics/cfg/datasets/kitti.yaml
45
- ultralytics/cfg/datasets/lvis.yaml
46
- ultralytics/cfg/datasets/medical-pills.yaml
47
- ultralytics/cfg/datasets/open-images-v7.yaml
48
- ultralytics/cfg/datasets/package-seg.yaml
49
- ultralytics/cfg/datasets/signature.yaml
50
- ultralytics/cfg/datasets/tiger-pose.yaml
51
- ultralytics/cfg/datasets/xView.yaml
52
- ultralytics/cfg/models/11/yolo11-cls-resnet18.yaml
53
- ultralytics/cfg/models/11/yolo11-cls.yaml
54
- ultralytics/cfg/models/11/yolo11-obb.yaml
55
- ultralytics/cfg/models/11/yolo11-pose.yaml
56
- ultralytics/cfg/models/11/yolo11-seg.yaml
57
- ultralytics/cfg/models/11/yolo11.yaml
58
- ultralytics/cfg/models/11/yoloe-11-seg.yaml
59
- ultralytics/cfg/models/11/yoloe-11.yaml
60
- ultralytics/cfg/models/12/yolo12-cls.yaml
61
- ultralytics/cfg/models/12/yolo12-obb.yaml
62
- ultralytics/cfg/models/12/yolo12-pose.yaml
63
- ultralytics/cfg/models/12/yolo12-seg.yaml
64
- ultralytics/cfg/models/12/yolo12.yaml
65
- ultralytics/cfg/models/26/yolo26-cls.yaml
66
- ultralytics/cfg/models/26/yolo26-obb.yaml
67
- ultralytics/cfg/models/26/yolo26-p2.yaml
68
- ultralytics/cfg/models/26/yolo26-p6.yaml
69
- ultralytics/cfg/models/26/yolo26-pose.yaml
70
- ultralytics/cfg/models/26/yolo26-seg.yaml
71
- ultralytics/cfg/models/26/yolo26.yaml
72
- ultralytics/cfg/models/26/yoloe-26-seg.yaml
73
- ultralytics/cfg/models/26/yoloe-26.yaml
74
- ultralytics/cfg/models/rt-detr/rtdetr-l.yaml
75
- ultralytics/cfg/models/rt-detr/rtdetr-resnet101.yaml
76
- ultralytics/cfg/models/rt-detr/rtdetr-resnet50.yaml
77
- ultralytics/cfg/models/rt-detr/rtdetr-x.yaml
78
- ultralytics/cfg/models/v10/yolov10b.yaml
79
- ultralytics/cfg/models/v10/yolov10l.yaml
80
- ultralytics/cfg/models/v10/yolov10m.yaml
81
- ultralytics/cfg/models/v10/yolov10n.yaml
82
- ultralytics/cfg/models/v10/yolov10s.yaml
83
- ultralytics/cfg/models/v10/yolov10x.yaml
84
- ultralytics/cfg/models/v3/yolov3-spp.yaml
85
- ultralytics/cfg/models/v3/yolov3-tiny.yaml
86
- ultralytics/cfg/models/v3/yolov3.yaml
87
- ultralytics/cfg/models/v5/yolov5-p6.yaml
88
- ultralytics/cfg/models/v5/yolov5.yaml
89
- ultralytics/cfg/models/v6/yolov6.yaml
90
- ultralytics/cfg/models/v8/yoloe-v8-seg.yaml
91
- ultralytics/cfg/models/v8/yoloe-v8.yaml
92
- ultralytics/cfg/models/v8/yolov8-cls-resnet101.yaml
93
- ultralytics/cfg/models/v8/yolov8-cls-resnet50.yaml
94
- ultralytics/cfg/models/v8/yolov8-cls.yaml
95
- ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml
96
- ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml
97
- ultralytics/cfg/models/v8/yolov8-ghost.yaml
98
- ultralytics/cfg/models/v8/yolov8-obb.yaml
99
- ultralytics/cfg/models/v8/yolov8-p2.yaml
100
- ultralytics/cfg/models/v8/yolov8-p6.yaml
101
- ultralytics/cfg/models/v8/yolov8-pose-p6.yaml
102
- ultralytics/cfg/models/v8/yolov8-pose.yaml
103
- ultralytics/cfg/models/v8/yolov8-rtdetr.yaml
104
- ultralytics/cfg/models/v8/yolov8-seg-p6.yaml
105
- ultralytics/cfg/models/v8/yolov8-seg.yaml
106
- ultralytics/cfg/models/v8/yolov8-world.yaml
107
- ultralytics/cfg/models/v8/yolov8-worldv2.yaml
108
- ultralytics/cfg/models/v8/yolov8.yaml
109
- ultralytics/cfg/models/v9/yolov9c-seg.yaml
110
- ultralytics/cfg/models/v9/yolov9c.yaml
111
- ultralytics/cfg/models/v9/yolov9e-seg.yaml
112
- ultralytics/cfg/models/v9/yolov9e.yaml
113
- ultralytics/cfg/models/v9/yolov9m.yaml
114
- ultralytics/cfg/models/v9/yolov9s.yaml
115
- ultralytics/cfg/models/v9/yolov9t.yaml
116
- ultralytics/cfg/trackers/botsort.yaml
117
- ultralytics/cfg/trackers/bytetrack.yaml
118
- ultralytics/data/__init__.py
119
- ultralytics/data/annotator.py
120
- ultralytics/data/augment.py
121
- ultralytics/data/base.py
122
- ultralytics/data/build.py
123
- ultralytics/data/converter.py
124
- ultralytics/data/dataset.py
125
- ultralytics/data/loaders.py
126
- ultralytics/data/split.py
127
- ultralytics/data/split_dota.py
128
- ultralytics/data/utils.py
129
- ultralytics/data/scripts/download_weights.sh
130
- ultralytics/data/scripts/get_coco.sh
131
- ultralytics/data/scripts/get_coco128.sh
132
- ultralytics/data/scripts/get_imagenet.sh
133
- ultralytics/engine/__init__.py
134
- ultralytics/engine/exporter.py
135
- ultralytics/engine/model.py
136
- ultralytics/engine/predictor.py
137
- ultralytics/engine/results.py
138
- ultralytics/engine/trainer.py
139
- ultralytics/engine/tuner.py
140
- ultralytics/engine/validator.py
141
- ultralytics/hub/__init__.py
142
- ultralytics/hub/auth.py
143
- ultralytics/hub/session.py
144
- ultralytics/hub/utils.py
145
- ultralytics/hub/google/__init__.py
146
- ultralytics/models/__init__.py
147
- ultralytics/models/fastsam/__init__.py
148
- ultralytics/models/fastsam/model.py
149
- ultralytics/models/fastsam/predict.py
150
- ultralytics/models/fastsam/utils.py
151
- ultralytics/models/fastsam/val.py
152
- ultralytics/models/nas/__init__.py
153
- ultralytics/models/nas/model.py
154
- ultralytics/models/nas/predict.py
155
- ultralytics/models/nas/val.py
156
- ultralytics/models/rtdetr/__init__.py
157
- ultralytics/models/rtdetr/model.py
158
- ultralytics/models/rtdetr/predict.py
159
- ultralytics/models/rtdetr/train.py
160
- ultralytics/models/rtdetr/val.py
161
- ultralytics/models/sam/__init__.py
162
- ultralytics/models/sam/amg.py
163
- ultralytics/models/sam/build.py
164
- ultralytics/models/sam/build_sam3.py
165
- ultralytics/models/sam/model.py
166
- ultralytics/models/sam/predict.py
167
- ultralytics/models/sam/modules/__init__.py
168
- ultralytics/models/sam/modules/blocks.py
169
- ultralytics/models/sam/modules/decoders.py
170
- ultralytics/models/sam/modules/encoders.py
171
- ultralytics/models/sam/modules/memory_attention.py
172
- ultralytics/models/sam/modules/sam.py
173
- ultralytics/models/sam/modules/tiny_encoder.py
174
- ultralytics/models/sam/modules/transformer.py
175
- ultralytics/models/sam/modules/utils.py
176
- ultralytics/models/sam/sam3/__init__.py
177
- ultralytics/models/sam/sam3/decoder.py
178
- ultralytics/models/sam/sam3/encoder.py
179
- ultralytics/models/sam/sam3/geometry_encoders.py
180
- ultralytics/models/sam/sam3/maskformer_segmentation.py
181
- ultralytics/models/sam/sam3/model_misc.py
182
- ultralytics/models/sam/sam3/necks.py
183
- ultralytics/models/sam/sam3/sam3_image.py
184
- ultralytics/models/sam/sam3/text_encoder_ve.py
185
- ultralytics/models/sam/sam3/vitdet.py
186
- ultralytics/models/sam/sam3/vl_combiner.py
187
- ultralytics/models/utils/__init__.py
188
- ultralytics/models/utils/loss.py
189
- ultralytics/models/utils/ops.py
190
- ultralytics/models/yolo/__init__.py
191
- ultralytics/models/yolo/model.py
192
- ultralytics/models/yolo/classify/__init__.py
193
- ultralytics/models/yolo/classify/predict.py
194
- ultralytics/models/yolo/classify/train.py
195
- ultralytics/models/yolo/classify/val.py
196
- ultralytics/models/yolo/detect/__init__.py
197
- ultralytics/models/yolo/detect/predict.py
198
- ultralytics/models/yolo/detect/train.py
199
- ultralytics/models/yolo/detect/val.py
200
- ultralytics/models/yolo/obb/__init__.py
201
- ultralytics/models/yolo/obb/predict.py
202
- ultralytics/models/yolo/obb/train.py
203
- ultralytics/models/yolo/obb/val.py
204
- ultralytics/models/yolo/pose/__init__.py
205
- ultralytics/models/yolo/pose/predict.py
206
- ultralytics/models/yolo/pose/train.py
207
- ultralytics/models/yolo/pose/val.py
208
- ultralytics/models/yolo/segment/__init__.py
209
- ultralytics/models/yolo/segment/predict.py
210
- ultralytics/models/yolo/segment/train.py
211
- ultralytics/models/yolo/segment/val.py
212
- ultralytics/models/yolo/world/__init__.py
213
- ultralytics/models/yolo/world/train.py
214
- ultralytics/models/yolo/world/train_world.py
215
- ultralytics/models/yolo/yoloe/__init__.py
216
- ultralytics/models/yolo/yoloe/predict.py
217
- ultralytics/models/yolo/yoloe/train.py
218
- ultralytics/models/yolo/yoloe/train_seg.py
219
- ultralytics/models/yolo/yoloe/val.py
220
- ultralytics/nn/__init__.py
221
- ultralytics/nn/ablation.py
222
- ultralytics/nn/autobackend.py
223
- ultralytics/nn/prebackbone.py
224
- ultralytics/nn/prebackboneB.py
225
- ultralytics/nn/tasks.py
226
- ultralytics/nn/text_model.py
227
- ultralytics/nn/modules/__init__.py
228
- ultralytics/nn/modules/activation.py
229
- ultralytics/nn/modules/block.py
230
- ultralytics/nn/modules/conv.py
231
- ultralytics/nn/modules/head.py
232
- ultralytics/nn/modules/transformer.py
233
- ultralytics/nn/modules/utils.py
234
- ultralytics/optim/__init__.py
235
- ultralytics/optim/muon.py
236
- ultralytics/solutions/__init__.py
237
- ultralytics/solutions/ai_gym.py
238
- ultralytics/solutions/analytics.py
239
- ultralytics/solutions/config.py
240
- ultralytics/solutions/distance_calculation.py
241
- ultralytics/solutions/heatmap.py
242
- ultralytics/solutions/instance_segmentation.py
243
- ultralytics/solutions/object_blurrer.py
244
- ultralytics/solutions/object_counter.py
245
- ultralytics/solutions/object_cropper.py
246
- ultralytics/solutions/parking_management.py
247
- ultralytics/solutions/queue_management.py
248
- ultralytics/solutions/region_counter.py
249
- ultralytics/solutions/security_alarm.py
250
- ultralytics/solutions/similarity_search.py
251
- ultralytics/solutions/solutions.py
252
- ultralytics/solutions/speed_estimation.py
253
- ultralytics/solutions/streamlit_inference.py
254
- ultralytics/solutions/trackzone.py
255
- ultralytics/solutions/vision_eye.py
256
- ultralytics/solutions/templates/similarity-search.html
257
- ultralytics/trackers/__init__.py
258
- ultralytics/trackers/basetrack.py
259
- ultralytics/trackers/bot_sort.py
260
- ultralytics/trackers/byte_tracker.py
261
- ultralytics/trackers/track.py
262
- ultralytics/trackers/utils/__init__.py
263
- ultralytics/trackers/utils/gmc.py
264
- ultralytics/trackers/utils/kalman_filter.py
265
- ultralytics/trackers/utils/matching.py
266
- ultralytics/utils/__init__.py
267
- ultralytics/utils/autobatch.py
268
- ultralytics/utils/autodevice.py
269
- ultralytics/utils/benchmarks.py
270
- ultralytics/utils/checks.py
271
- ultralytics/utils/cpu.py
272
- ultralytics/utils/dist.py
273
- ultralytics/utils/downloads.py
274
- ultralytics/utils/errors.py
275
- ultralytics/utils/events.py
276
- ultralytics/utils/files.py
277
- ultralytics/utils/git.py
278
- ultralytics/utils/instance.py
279
- ultralytics/utils/logger.py
280
- ultralytics/utils/loss.py
281
- ultralytics/utils/metrics.py
282
- ultralytics/utils/nms.py
283
- ultralytics/utils/ops.py
284
- ultralytics/utils/patches.py
285
- ultralytics/utils/plotting.py
286
- ultralytics/utils/tal.py
287
- ultralytics/utils/torch_utils.py
288
- ultralytics/utils/tqdm.py
289
- ultralytics/utils/triton.py
290
- ultralytics/utils/tuner.py
291
- ultralytics/utils/uploads.py
292
- ultralytics/utils/callbacks/__init__.py
293
- ultralytics/utils/callbacks/base.py
294
- ultralytics/utils/callbacks/clearml.py
295
- ultralytics/utils/callbacks/comet.py
296
- ultralytics/utils/callbacks/dvc.py
297
- ultralytics/utils/callbacks/hub.py
298
- ultralytics/utils/callbacks/mlflow.py
299
- ultralytics/utils/callbacks/neptune.py
300
- ultralytics/utils/callbacks/platform.py
301
- ultralytics/utils/callbacks/raytune.py
302
- ultralytics/utils/callbacks/tensorboard.py
303
- ultralytics/utils/callbacks/wb.py
304
- ultralytics/utils/export/__init__.py
305
- ultralytics/utils/export/engine.py
306
- ultralytics/utils/export/executorch.py
307
- ultralytics/utils/export/imx.py
308
- ultralytics/utils/export/tensorflow.py
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
vendor/ultralytics.egg-info/dependency_links.txt DELETED
@@ -1 +0,0 @@
1
-
 
 
vendor/ultralytics.egg-info/entry_points.txt DELETED
@@ -1,3 +0,0 @@
1
- [console_scripts]
2
- ultralytics = ultralytics.cfg:entrypoint
3
- yolo = ultralytics.cfg:entrypoint
 
 
 
 
vendor/ultralytics.egg-info/requires.txt DELETED
@@ -1,83 +0,0 @@
1
- numpy>=1.23.0
2
- matplotlib>=3.3.0
3
- opencv-python>=4.6.0
4
- pillow>=7.1.2
5
- pyyaml>=5.3.1
6
- requests>=2.23.0
7
- scipy>=1.4.1
8
- torch>=1.8.0
9
- torchvision>=0.9.0
10
- psutil>=5.8.0
11
- polars>=0.20.0
12
- ultralytics-thop>=2.0.18
13
-
14
- [:sys_platform == "win32"]
15
- torch!=2.4.0,>=1.8.0
16
-
17
- [dev]
18
- ipython
19
- pytest
20
- pytest-cov
21
- coverage[toml]
22
- mkdocs-ultralytics-plugin>=0.2.4
23
- minijinja>=2.0.0
24
-
25
- [dev:python_version >= "3.10"]
26
- zensical>=0.0.15
27
-
28
- [export]
29
- numpy<2.0.0
30
- onnxslim>=0.1.82
31
- openvino>=2024.0.0
32
- tensorflow<=2.19.0,>=2.0.0
33
- tensorflowjs>=2.0.0
34
- setuptools<=81.0.0
35
-
36
- [export:platform_machine == "aarch64"]
37
- h5py!=3.11.0
38
-
39
- [export:platform_machine == "aarch64" and platform_system == "Linux" and python_version >= "3.9"]
40
- packaging>=26.0
41
-
42
- [export:platform_machine == "aarch64" and python_version >= "3.9"]
43
- tensorstore>=0.1.63
44
-
45
- [export:platform_system != "Darwin"]
46
- onnx>=1.12.0
47
-
48
- [export:platform_system != "Windows" and python_version <= "3.13"]
49
- coremltools>=9.0
50
- scikit-learn>=1.3.2
51
-
52
- [export:platform_system == "Darwin"]
53
- onnx<1.18.0,>=1.12.0
54
-
55
- [extra]
56
- ipython
57
- albumentations>=1.4.6
58
- faster-coco-eval>=1.6.7
59
-
60
- [logging]
61
- wandb
62
- tensorboard
63
- mlflow
64
-
65
- [solutions]
66
- shapely>=2.0.0
67
- flask>=3.0.1
68
-
69
- [solutions:python_version < "3.10" and (python_version < "3.9" or platform_machine != "aarch64" or platform_system != "Linux")]
70
- streamlit<1.51.0,>=1.29.0
71
-
72
- [solutions:python_version >= "3.10"]
73
- streamlit>=1.51.0
74
-
75
- [typing]
76
- types-pillow
77
- types-psutil
78
- types-pyyaml
79
- types-requests
80
- types-shapely
81
-
82
- [typing:python_version >= "3.10"]
83
- scipy-stubs>=1.14.1.4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
vendor/ultralytics.egg-info/top_level.txt DELETED
@@ -1 +0,0 @@
1
- ultralytics
 
 
vendor/ultralytics/__init__.py DELETED
@@ -1,48 +0,0 @@
1
- # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
-
3
- __version__ = "8.4.21"
4
-
5
- import importlib
6
- import os
7
- from typing import TYPE_CHECKING
8
-
9
- # Set ENV variables (place before imports)
10
- if not os.environ.get("OMP_NUM_THREADS"):
11
- os.environ["OMP_NUM_THREADS"] = "1" # default for reduced CPU utilization during training
12
-
13
- from ultralytics.utils import ASSETS, SETTINGS
14
- from ultralytics.utils.checks import check_yolo as checks
15
- from ultralytics.utils.downloads import download
16
-
17
- settings = SETTINGS
18
-
19
- MODELS = ("YOLO", "YOLOWorld", "YOLOE", "NAS", "SAM", "FastSAM", "RTDETR")
20
-
21
- __all__ = (
22
- "__version__",
23
- "ASSETS",
24
- *MODELS,
25
- "checks",
26
- "download",
27
- "settings",
28
- )
29
-
30
- if TYPE_CHECKING:
31
- # Enable hints for type checkers
32
- from ultralytics.models import YOLO, YOLOWorld, YOLOE, NAS, SAM, FastSAM, RTDETR # noqa
33
-
34
-
35
- def __getattr__(name: str):
36
- """Lazy-import model classes on first access."""
37
- if name in MODELS:
38
- return getattr(importlib.import_module("ultralytics.models"), name)
39
- raise AttributeError(f"module {__name__} has no attribute {name}")
40
-
41
-
42
- def __dir__():
43
- """Extend dir() to include lazily available model names for IDE autocompletion."""
44
- return sorted(set(globals()) | set(MODELS))
45
-
46
-
47
- if __name__ == "__main__":
48
- print(__version__)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
vendor/ultralytics/cfg/__init__.py DELETED
@@ -1,1039 +0,0 @@
1
- # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
-
3
- from __future__ import annotations
4
-
5
- import ast
6
- import shutil
7
- import subprocess
8
- import sys
9
- from pathlib import Path
10
- from types import SimpleNamespace
11
- from typing import Any
12
-
13
- from ultralytics import __version__
14
- from ultralytics.utils import (
15
- ASSETS,
16
- DEFAULT_CFG,
17
- DEFAULT_CFG_DICT,
18
- DEFAULT_CFG_PATH,
19
- FLOAT_OR_INT,
20
- IS_VSCODE,
21
- LOGGER,
22
- RANK,
23
- ROOT,
24
- RUNS_DIR,
25
- SETTINGS,
26
- SETTINGS_FILE,
27
- STR_OR_PATH,
28
- TESTS_RUNNING,
29
- YAML,
30
- IterableSimpleNamespace,
31
- checks,
32
- colorstr,
33
- deprecation_warn,
34
- vscode_msg,
35
- )
36
-
37
- # Define valid solutions
38
- SOLUTION_MAP = {
39
- "count": "ObjectCounter",
40
- "crop": "ObjectCropper",
41
- "blur": "ObjectBlurrer",
42
- "workout": "AIGym",
43
- "heatmap": "Heatmap",
44
- "isegment": "InstanceSegmentation",
45
- "visioneye": "VisionEye",
46
- "speed": "SpeedEstimator",
47
- "queue": "QueueManager",
48
- "analytics": "Analytics",
49
- "inference": "Inference",
50
- "trackzone": "TrackZone",
51
- "help": None,
52
- }
53
-
54
- # Define valid tasks and modes
55
- MODES = frozenset({"train", "val", "predict", "export", "track", "benchmark"})
56
- TASKS = frozenset({"detect", "segment", "classify", "pose", "obb"})
57
- TASK2DATA = {
58
- "detect": "coco8.yaml",
59
- "segment": "coco8-seg.yaml",
60
- "classify": "imagenet10",
61
- "pose": "coco8-pose.yaml",
62
- "obb": "dota8.yaml",
63
- }
64
- TASK2MODEL = {
65
- "detect": "yolo26n.pt",
66
- "segment": "yolo26n-seg.pt",
67
- "classify": "yolo26n-cls.pt",
68
- "pose": "yolo26n-pose.pt",
69
- "obb": "yolo26n-obb.pt",
70
- }
71
- TASK2METRIC = {
72
- "detect": "metrics/mAP50-95(B)",
73
- "segment": "metrics/mAP50-95(M)",
74
- "classify": "metrics/accuracy_top1",
75
- "pose": "metrics/mAP50-95(P)",
76
- "obb": "metrics/mAP50-95(B)",
77
- }
78
-
79
- ARGV = sys.argv or ["", ""] # sometimes sys.argv = []
80
- SOLUTIONS_HELP_MSG = f"""
81
- Arguments received: {["yolo", *ARGV[1:]]!s}. Ultralytics 'yolo solutions' usage overview:
82
-
83
- yolo solutions SOLUTION ARGS
84
-
85
- Where SOLUTION (optional) is one of {list(SOLUTION_MAP.keys())[:-1]}
86
- ARGS (optional) are any number of custom 'arg=value' pairs like 'show_in=True' that override defaults
87
- at https://docs.ultralytics.com/usage/cfg
88
-
89
- 1. Call object counting solution
90
- yolo solutions count source="path/to/video.mp4" region="[(20, 400), (1080, 400), (1080, 360), (20, 360)]"
91
-
92
- 2. Call heatmap solution
93
- yolo solutions heatmap colormap=cv2.COLORMAP_PARULA model=yolo26n.pt
94
-
95
- 3. Call queue management solution
96
- yolo solutions queue region="[(20, 400), (1080, 400), (1080, 360), (20, 360)]" model=yolo26n.pt
97
-
98
- 4. Call workout monitoring solution for push-ups
99
- yolo solutions workout model=yolo26n-pose.pt kpts=[6, 8, 10]
100
-
101
- 5. Generate analytical graphs
102
- yolo solutions analytics analytics_type="pie"
103
-
104
- 6. Track objects within specific zones
105
- yolo solutions trackzone source="path/to/video.mp4" region="[(150, 150), (1130, 150), (1130, 570), (150, 570)]"
106
-
107
- 7. Streamlit real-time webcam inference GUI
108
- yolo streamlit-predict
109
- """
110
- CLI_HELP_MSG = f"""
111
- Arguments received: {["yolo", *ARGV[1:]]!s}. Ultralytics 'yolo' commands use the following syntax:
112
-
113
- yolo TASK MODE ARGS
114
-
115
- Where TASK (optional) is one of {list(TASKS)}
116
- MODE (required) is one of {list(MODES)}
117
- ARGS (optional) are any number of custom 'arg=value' pairs like 'imgsz=320' that override defaults.
118
- See all ARGS at https://docs.ultralytics.com/usage/cfg or with 'yolo cfg'
119
-
120
- 1. Train a detection model for 10 epochs with an initial learning_rate of 0.01
121
- yolo train data=coco8.yaml model=yolo26n.pt epochs=10 lr0=0.01
122
-
123
- 2. Predict a YouTube video using a pretrained segmentation model at image size 320:
124
- yolo predict model=yolo26n-seg.pt source='https://youtu.be/LNwODJXcvt4' imgsz=320
125
-
126
- 3. Validate a pretrained detection model at batch-size 1 and image size 640:
127
- yolo val model=yolo26n.pt data=coco8.yaml batch=1 imgsz=640
128
-
129
- 4. Export a YOLO26n classification model to ONNX format at image size 224 by 128 (no TASK required)
130
- yolo export model=yolo26n-cls.pt format=onnx imgsz=224,128
131
-
132
- 5. Ultralytics solutions usage
133
- yolo solutions count or any of {list(SOLUTION_MAP.keys())[1:-1]} source="path/to/video.mp4"
134
-
135
- 6. Run special commands:
136
- yolo help
137
- yolo checks
138
- yolo version
139
- yolo settings
140
- yolo copy-cfg
141
- yolo cfg
142
- yolo solutions help
143
-
144
- Docs: https://docs.ultralytics.com
145
- Solutions: https://docs.ultralytics.com/solutions/
146
- Community: https://community.ultralytics.com
147
- GitHub: https://github.com/ultralytics/ultralytics
148
- """
149
-
150
- # Define keys for arg type checks
151
- CFG_FLOAT_KEYS = frozenset(
152
- { # integer or float arguments, i.e. x=2 and x=2.0
153
- "warmup_epochs",
154
- "box",
155
- "cls",
156
- "dfl",
157
- "degrees",
158
- "shear",
159
- "time",
160
- "workspace",
161
- "batch",
162
- "gaussian_noise_mean",
163
- }
164
- )
165
- CFG_FRACTION_KEYS = frozenset(
166
- { # fractional float arguments with 0.0<=values<=1.0
167
- "dropout",
168
- "lr0",
169
- "lrf",
170
- "momentum",
171
- "weight_decay",
172
- "warmup_momentum",
173
- "warmup_bias_lr",
174
- "hsv_h",
175
- "hsv_s",
176
- "hsv_v",
177
- "translate",
178
- "scale",
179
- "perspective",
180
- "flipud",
181
- "fliplr",
182
- "bgr",
183
- "mosaic",
184
- "mixup",
185
- "cutmix",
186
- "copy_paste",
187
- "gaussian_noise_p",
188
- "conf",
189
- "iou",
190
- "fraction",
191
- "multi_scale",
192
- "deeppcb_safe_fliplr",
193
- "deeppcb_safe_flipud",
194
- "deeppcb_safe_crop_p",
195
- "deeppcb_safe_crop_min_frac",
196
- "deeppcb_safe_translate",
197
- "deeppcb_safe_scale",
198
- }
199
- )
200
- CFG_INT_KEYS = frozenset(
201
- { # integer-only arguments
202
- "epochs",
203
- "patience",
204
- "workers",
205
- "seed",
206
- "close_mosaic",
207
- "mask_ratio",
208
- "max_det",
209
- "vid_stride",
210
- "line_width",
211
- "nbs",
212
- "save_period",
213
- }
214
- )
215
- CFG_BOOL_KEYS = frozenset(
216
- { # boolean-only arguments
217
- "save",
218
- "exist_ok",
219
- "verbose",
220
- "deterministic",
221
- "single_cls",
222
- "rect",
223
- "cos_lr",
224
- "overlap_mask",
225
- "val",
226
- "save_json",
227
- "half",
228
- "dnn",
229
- "plots",
230
- "show",
231
- "save_txt",
232
- "save_conf",
233
- "save_crop",
234
- "save_frames",
235
- "show_labels",
236
- "show_conf",
237
- "visualize",
238
- "augment",
239
- "agnostic_nms",
240
- "retina_masks",
241
- "show_boxes",
242
- "keras",
243
- "optimize",
244
- "int8",
245
- "dynamic",
246
- "simplify",
247
- "nms",
248
- "profile",
249
- "end2end",
250
- "prebackbone_input_only_non_geo_aug",
251
- "isdeeppcb",
252
- "deeppcb_safe_aug",
253
- "augment_train",
254
- }
255
- )
256
-
257
-
258
- def cfg2dict(cfg: str | Path | dict | SimpleNamespace) -> dict:
259
- """Convert a configuration object to a dictionary.
260
-
261
- Args:
262
- cfg (str | Path | dict | SimpleNamespace): Configuration object to be converted. Can be a file path, a string, a
263
- dictionary, or a SimpleNamespace object.
264
-
265
- Returns:
266
- (dict): Configuration object in dictionary format.
267
-
268
- Examples:
269
- Convert a YAML file path to a dictionary:
270
- >>> config_dict = cfg2dict("config.yaml")
271
-
272
- Convert a SimpleNamespace to a dictionary:
273
- >>> from types import SimpleNamespace
274
- >>> config_sn = SimpleNamespace(param1="value1", param2="value2")
275
- >>> config_dict = cfg2dict(config_sn)
276
-
277
- Pass through an already existing dictionary:
278
- >>> config_dict = cfg2dict({"param1": "value1", "param2": "value2"})
279
-
280
- Notes:
281
- - If cfg is a path or string, it's loaded as YAML and converted to a dictionary.
282
- - If cfg is a SimpleNamespace object, it's converted to a dictionary using vars().
283
- - If cfg is already a dictionary, it's returned unchanged.
284
- """
285
- if isinstance(cfg, STR_OR_PATH):
286
- cfg = YAML.load(cfg) # load dict
287
- elif isinstance(cfg, SimpleNamespace):
288
- cfg = vars(cfg) # convert to dict
289
- return cfg
290
-
291
-
292
- def get_cfg(
293
- cfg: str | Path | dict | SimpleNamespace = DEFAULT_CFG_DICT, overrides: dict | None = None
294
- ) -> SimpleNamespace:
295
- """Load and merge configuration data from a file or dictionary, with optional overrides.
296
-
297
- Args:
298
- cfg (str | Path | dict | SimpleNamespace): Configuration data source. Can be a file path, dictionary, or
299
- SimpleNamespace object.
300
- overrides (dict | None): Dictionary containing key-value pairs to override the base configuration.
301
-
302
- Returns:
303
- (SimpleNamespace): Namespace containing the merged configuration arguments.
304
-
305
- Examples:
306
- >>> from ultralytics.cfg import get_cfg
307
- >>> config = get_cfg() # Load default configuration
308
- >>> config_with_overrides = get_cfg("path/to/config.yaml", overrides={"epochs": 50, "batch_size": 16})
309
-
310
- Notes:
311
- - If both `cfg` and `overrides` are provided, the values in `overrides` will take precedence.
312
- - Special handling ensures alignment and correctness of the configuration, such as converting numeric
313
- `project` and `name` to strings and validating configuration keys and values.
314
- - The function performs type and value checks on the configuration data.
315
- """
316
- cfg = cfg2dict(cfg)
317
-
318
- # Merge overrides
319
- if overrides:
320
- overrides = cfg2dict(overrides)
321
- check_dict_alignment(cfg, overrides)
322
- cfg = {**cfg, **overrides} # merge cfg and overrides dicts (prefer overrides)
323
-
324
- # Special handling for numeric project/name
325
- for k in "project", "name":
326
- if k in cfg and isinstance(cfg[k], FLOAT_OR_INT):
327
- cfg[k] = str(cfg[k])
328
- if cfg.get("name") == "model": # assign model to 'name' arg
329
- cfg["name"] = str(cfg.get("model", "")).partition(".")[0]
330
- LOGGER.warning(f"'name=model' automatically updated to 'name={cfg['name']}'.")
331
-
332
- # Type and Value checks
333
- check_cfg(cfg)
334
-
335
- # Return instance
336
- return IterableSimpleNamespace(**cfg)
337
-
338
-
339
- def check_cfg(cfg: dict, hard: bool = True) -> None:
340
- """Check configuration argument types and values for the Ultralytics library.
341
-
342
- This function validates the types and values of configuration arguments, ensuring correctness and converting them if
343
- necessary. It checks for specific key types defined in global variables such as `CFG_FLOAT_KEYS`,
344
- `CFG_FRACTION_KEYS`, `CFG_INT_KEYS`, and `CFG_BOOL_KEYS`.
345
-
346
- Args:
347
- cfg (dict): Configuration dictionary to validate.
348
- hard (bool): If True, raises exceptions for invalid types and values; if False, attempts to convert them.
349
-
350
- Examples:
351
- >>> config = {
352
- ... "epochs": 50, # valid integer
353
- ... "lr0": 0.01, # valid float
354
- ... "momentum": 1.2, # invalid float (out of 0.0-1.0 range)
355
- ... "save": "true", # invalid bool
356
- ... }
357
- >>> check_cfg(config, hard=False)
358
- >>> print(config)
359
- {'epochs': 50, 'lr0': 0.01, 'momentum': 1.2, 'save': False} # corrected 'save' key
360
-
361
- Notes:
362
- - The function modifies the input dictionary in-place.
363
- - None values are ignored as they may be from optional arguments.
364
- - Fraction keys are checked to be within the range [0.0, 1.0].
365
- """
366
- for k, v in cfg.items():
367
- if v is not None: # None values may be from optional args
368
- if k in CFG_FLOAT_KEYS and not isinstance(v, FLOAT_OR_INT):
369
- if hard:
370
- raise TypeError(
371
- f"'{k}={v}' is of invalid type {type(v).__name__}. "
372
- f"Valid '{k}' types are int (i.e. '{k}=0') or float (i.e. '{k}=0.5')"
373
- )
374
- cfg[k] = float(v)
375
- elif k in CFG_FRACTION_KEYS:
376
- if not isinstance(v, FLOAT_OR_INT):
377
- if hard:
378
- raise TypeError(
379
- f"'{k}={v}' is of invalid type {type(v).__name__}. "
380
- f"Valid '{k}' types are int (i.e. '{k}=0') or float (i.e. '{k}=0.5')"
381
- )
382
- cfg[k] = v = float(v)
383
- if not (0.0 <= v <= 1.0):
384
- raise ValueError(f"'{k}={v}' is an invalid value. Valid '{k}' values are between 0.0 and 1.0.")
385
- elif k in CFG_INT_KEYS and not isinstance(v, int):
386
- if hard:
387
- raise TypeError(
388
- f"'{k}={v}' is of invalid type {type(v).__name__}. '{k}' must be an int (i.e. '{k}=8')"
389
- )
390
- cfg[k] = int(v)
391
- elif k in CFG_BOOL_KEYS and not isinstance(v, bool):
392
- if hard:
393
- raise TypeError(
394
- f"'{k}={v}' is of invalid type {type(v).__name__}. "
395
- f"'{k}' must be a bool (i.e. '{k}=True' or '{k}=False')"
396
- )
397
- cfg[k] = bool(v)
398
-
399
-
400
- def get_save_dir(args: SimpleNamespace, name: str | None = None) -> Path:
401
- """Return the directory path for saving outputs, derived from arguments or default settings.
402
-
403
- Args:
404
- args (SimpleNamespace): Namespace object containing configurations such as 'project', 'name', 'task', 'mode',
405
- and 'save_dir'.
406
- name (str | None): Optional name for the output directory. If not provided, it defaults to 'args.name' or the
407
- 'args.mode'.
408
-
409
- Returns:
410
- (Path): Directory path where outputs should be saved.
411
-
412
- Examples:
413
- >>> from types import SimpleNamespace
414
- >>> args = SimpleNamespace(project="my_project", task="detect", mode="train", exist_ok=True)
415
- >>> save_dir = get_save_dir(args)
416
- >>> print(save_dir)
417
- runs/detect/my_project/train
418
- """
419
- if getattr(args, "save_dir", None):
420
- save_dir = args.save_dir
421
- else:
422
- from ultralytics.utils.files import increment_path
423
-
424
- project = args.project or ""
425
- if not Path(project).is_absolute():
426
- project = (ROOT.parent / "tests/tmp/runs" if TESTS_RUNNING else RUNS_DIR) / args.task / project
427
- name = name or args.name or f"{args.mode}"
428
- save_dir = increment_path(Path(project) / name, exist_ok=args.exist_ok if RANK in {-1, 0} else True)
429
-
430
- return Path(save_dir).resolve() # resolve to display full path in console
431
-
432
-
433
- def _handle_deprecation(custom: dict) -> dict:
434
- """Handle deprecated configuration keys by mapping them to current equivalents with deprecation warnings.
435
-
436
- Args:
437
- custom (dict): Configuration dictionary potentially containing deprecated keys.
438
-
439
- Returns:
440
- (dict): Updated configuration dictionary with deprecated keys replaced.
441
-
442
- Examples:
443
- >>> custom_config = {"boxes": True, "hide_labels": "False", "line_thickness": 2}
444
- >>> _handle_deprecation(custom_config)
445
- >>> print(custom_config)
446
- {'show_boxes': True, 'show_labels': True, 'line_width': 2}
447
-
448
- Notes:
449
- This function modifies the input dictionary in-place, replacing deprecated keys with their current
450
- equivalents. It also handles value conversions where necessary, such as inverting boolean values for
451
- 'hide_labels' and 'hide_conf'.
452
- """
453
- deprecated_mappings = {
454
- "boxes": ("show_boxes", lambda v: v),
455
- "hide_labels": ("show_labels", lambda v: not bool(v)),
456
- "hide_conf": ("show_conf", lambda v: not bool(v)),
457
- "line_thickness": ("line_width", lambda v: v),
458
- }
459
- removed_keys = {"label_smoothing", "save_hybrid", "crop_fraction"}
460
-
461
- for old_key, (new_key, transform) in deprecated_mappings.items():
462
- if old_key not in custom:
463
- continue
464
- deprecation_warn(old_key, new_key)
465
- custom[new_key] = transform(custom.pop(old_key))
466
-
467
- for key in removed_keys:
468
- if key not in custom:
469
- continue
470
- deprecation_warn(key)
471
- custom.pop(key)
472
-
473
- return custom
474
-
475
-
476
- def check_dict_alignment(
477
- base: dict, custom: dict, e: Exception | None = None, allowed_custom_keys: set | None = None
478
- ) -> None:
479
- """Check alignment between custom and base configuration dictionaries, handling deprecated keys and providing error
480
- messages for mismatched keys.
481
-
482
- Args:
483
- base (dict): The base configuration dictionary containing valid keys.
484
- custom (dict): The custom configuration dictionary to be checked for alignment.
485
- e (Exception | None): Optional error instance passed by the calling function.
486
- allowed_custom_keys (set | None): Optional set of additional keys that are allowed in the custom dictionary.
487
-
488
- Raises:
489
- SystemExit: If mismatched keys are found between the custom and base dictionaries.
490
-
491
- Examples:
492
- >>> base_cfg = {"epochs": 50, "lr0": 0.01, "batch_size": 16}
493
- >>> custom_cfg = {"epoch": 100, "lr": 0.02, "batch_size": 32}
494
- >>> try:
495
- ... check_dict_alignment(base_cfg, custom_cfg)
496
- ... except SystemExit:
497
- ... print("Mismatched keys found")
498
-
499
- Notes:
500
- - Suggests corrections for mismatched keys based on similarity to valid keys.
501
- - Automatically replaces deprecated keys in the custom configuration with updated equivalents.
502
- - Prints detailed error messages for each mismatched key to help users correct their configurations.
503
- """
504
- custom = _handle_deprecation(custom)
505
- base_keys, custom_keys = (frozenset(x.keys()) for x in (base, custom))
506
- # Allow 'augmentations' as a valid custom parameter for custom Albumentations transforms
507
- if allowed_custom_keys is None:
508
- allowed_custom_keys = {"augmentations", "save_dir"}
509
- if mismatched := [k for k in custom_keys if k not in base_keys and k not in allowed_custom_keys]:
510
- from difflib import get_close_matches
511
-
512
- string = ""
513
- for x in mismatched:
514
- matches = get_close_matches(x, base_keys) # key list
515
- matches = [f"{k}={base[k]}" if base.get(k) is not None else k for k in matches]
516
- match_str = f"Similar arguments are i.e. {matches}." if matches else ""
517
- string += f"'{colorstr('red', 'bold', x)}' is not a valid YOLO argument. {match_str}\n"
518
- raise SyntaxError(string + CLI_HELP_MSG) from e
519
-
520
-
521
- def merge_equals_args(args: list[str]) -> list[str]:
522
- """Merge arguments around isolated '=' in a list of strings and join fragments with brackets.
523
-
524
- This function handles the following cases:
525
- 1. ['arg', '=', 'val'] becomes ['arg=val']
526
- 2. ['arg=', 'val'] becomes ['arg=val']
527
- 3. ['arg', '=val'] becomes ['arg=val']
528
- 4. Joins fragments with brackets, e.g., ['imgsz=[3,', '640,', '640]'] becomes ['imgsz=[3,640,640]']
529
-
530
- Args:
531
- args (list[str]): A list of strings where each element represents an argument or fragment.
532
-
533
- Returns:
534
- (list[str]): A list of strings where the arguments around isolated '=' are merged and fragments with brackets
535
- are joined.
536
-
537
- Examples:
538
- >>> args = ["arg1", "=", "value", "arg2=", "value2", "arg3", "=value3", "imgsz=[3,", "640,", "640]"]
539
- >>> merge_equals_args(args)
540
- ['arg1=value', 'arg2=value2', 'arg3=value3', 'imgsz=[3,640,640]']
541
- """
542
- new_args = []
543
- current = ""
544
- depth = 0
545
-
546
- i = 0
547
- while i < len(args):
548
- arg = args[i]
549
-
550
- # Handle equals sign merging
551
- if arg == "=" and 0 < i < len(args) - 1: # merge ['arg', '=', 'val']
552
- new_args[-1] += f"={args[i + 1]}"
553
- i += 2
554
- continue
555
- elif arg.endswith("=") and i < len(args) - 1 and "=" not in args[i + 1]: # merge ['arg=', 'val']
556
- new_args.append(f"{arg}{args[i + 1]}")
557
- i += 2
558
- continue
559
- elif arg.startswith("=") and i > 0: # merge ['arg', '=val']
560
- new_args[-1] += arg
561
- i += 1
562
- continue
563
-
564
- # Handle bracket joining
565
- depth += arg.count("[") - arg.count("]")
566
- current += arg
567
- if depth == 0:
568
- new_args.append(current)
569
- current = ""
570
-
571
- i += 1
572
-
573
- # Append any remaining current string
574
- if current:
575
- new_args.append(current)
576
-
577
- return new_args
578
-
579
-
580
- def handle_yolo_hub(args: list[str]) -> None:
581
- """Handle Ultralytics HUB command-line interface (CLI) commands for authentication.
582
-
583
- This function processes Ultralytics HUB CLI commands such as login and logout. It should be called when executing a
584
- script with arguments related to HUB authentication.
585
-
586
- Args:
587
- args (list[str]): A list of command line arguments. The first argument should be either 'login' or 'logout'. For
588
- 'login', an optional second argument can be the API key.
589
-
590
- Examples:
591
- $ yolo login YOUR_API_KEY
592
-
593
- Notes:
594
- - The function imports the 'hub' module from ultralytics to perform login and logout operations.
595
- - For the 'login' command, if no API key is provided, an empty string is passed to the login function.
596
- - The 'logout' command does not require any additional arguments.
597
- """
598
- from ultralytics import hub
599
-
600
- if args[0] == "login":
601
- key = args[1] if len(args) > 1 else ""
602
- # Log in to Ultralytics HUB using the provided API key
603
- hub.login(key)
604
- elif args[0] == "logout":
605
- # Log out from Ultralytics HUB
606
- hub.logout()
607
-
608
-
609
- def handle_yolo_settings(args: list[str]) -> None:
610
- """Handle YOLO settings command-line interface (CLI) commands.
611
-
612
- This function processes YOLO settings CLI commands such as reset and updating individual settings. It should be
613
- called when executing a script with arguments related to YOLO settings management.
614
-
615
- Args:
616
- args (list[str]): A list of command line arguments for YOLO settings management.
617
-
618
- Examples:
619
- >>> handle_yolo_settings(["reset"]) # Reset YOLO settings
620
- >>> handle_yolo_settings(["default_cfg_path=yolo26n.yaml"]) # Update a specific setting
621
-
622
- Notes:
623
- - If no arguments are provided, the function will display the current settings.
624
- - The 'reset' command will delete the existing settings file and create new default settings.
625
- - Other arguments are treated as key-value pairs to update specific settings.
626
- - The function will check for alignment between the provided settings and the existing ones.
627
- - After processing, the updated settings will be displayed.
628
- - For more information on handling YOLO settings, visit:
629
- https://docs.ultralytics.com/quickstart/#ultralytics-settings
630
- """
631
- url = "https://docs.ultralytics.com/quickstart/#ultralytics-settings" # help URL
632
- try:
633
- if any(args):
634
- if args[0] == "reset":
635
- SETTINGS_FILE.unlink() # delete the settings file
636
- SETTINGS.reset() # create new settings
637
- LOGGER.info("Settings reset successfully") # inform the user that settings have been reset
638
- else: # save a new setting
639
- new = dict(parse_key_value_pair(a) for a in args)
640
- check_dict_alignment(SETTINGS, new)
641
- SETTINGS.update(new)
642
- for k, v in new.items():
643
- LOGGER.info(f"✅ Updated '{k}={v}'")
644
-
645
- LOGGER.info(SETTINGS) # print the current settings
646
- LOGGER.info(f"💡 Learn more about Ultralytics Settings at {url}")
647
- except Exception as e:
648
- LOGGER.warning(f"settings error: '{e}'. Please see {url} for help.")
649
-
650
-
651
- def handle_yolo_solutions(args: list[str]) -> None:
652
- """Process YOLO solutions arguments and run the specified computer vision solutions pipeline.
653
-
654
- Args:
655
- args (list[str]): Command-line arguments for configuring and running the Ultralytics YOLO solutions.
656
-
657
- Examples:
658
- Run people counting solution with default settings:
659
- >>> handle_yolo_solutions(["count"])
660
-
661
- Run analytics with custom configuration:
662
- >>> handle_yolo_solutions(["analytics", "conf=0.25", "source=path/to/video.mp4"])
663
-
664
- Run inference with custom configuration, requires Streamlit version 1.29.0 or higher.
665
- >>> handle_yolo_solutions(["inference", "model=yolo26n.pt"])
666
-
667
- Notes:
668
- - Arguments can be provided in the format 'key=value' or as boolean flags
669
- - Available solutions are defined in SOLUTION_MAP with their respective classes and methods
670
- - If an invalid solution is provided, defaults to 'count' solution
671
- - Output videos are saved in 'runs/solution/{solution_name}' directory
672
- - For 'analytics' solution, frame numbers are tracked for generating analytical graphs
673
- - Video processing can be interrupted by pressing 'q'
674
- - Processes video frames sequentially and saves output in .avi format
675
- - If no source is specified, downloads and uses a default sample video
676
- - The inference solution will be launched using the 'streamlit run' command.
677
- - The Streamlit app file is located in the Ultralytics package directory.
678
- """
679
- from ultralytics.solutions.config import SolutionConfig
680
-
681
- full_args_dict = vars(SolutionConfig()) # arguments dictionary
682
- overrides = {}
683
-
684
- # check dictionary alignment
685
- for arg in merge_equals_args(args):
686
- arg = arg.lstrip("-").rstrip(",")
687
- if "=" in arg:
688
- try:
689
- k, v = parse_key_value_pair(arg)
690
- overrides[k] = v
691
- except (NameError, SyntaxError, ValueError, AssertionError) as e:
692
- check_dict_alignment(full_args_dict, {arg: ""}, e)
693
- elif arg in full_args_dict and isinstance(full_args_dict.get(arg), bool):
694
- overrides[arg] = True
695
- check_dict_alignment(full_args_dict, overrides) # dict alignment
696
-
697
- # Get solution name
698
- if not args:
699
- LOGGER.warning("No solution name provided. i.e `yolo solutions count`. Defaulting to 'count'.")
700
- args = ["count"]
701
- if args[0] == "help":
702
- LOGGER.info(SOLUTIONS_HELP_MSG)
703
- return # Early return for 'help' case
704
- elif args[0] in SOLUTION_MAP:
705
- solution_name = args.pop(0) # Extract the solution name directly
706
- else:
707
- LOGGER.warning(
708
- f"❌ '{args[0]}' is not a valid solution. 💡 Defaulting to 'count'.\n"
709
- f"🚀 Available solutions: {', '.join(list(SOLUTION_MAP.keys())[:-1])}\n"
710
- )
711
- solution_name = "count" # Default for invalid solution
712
-
713
- if solution_name == "inference":
714
- checks.check_requirements("streamlit>=1.29.0")
715
- LOGGER.info("💡 Loading Ultralytics live inference app...")
716
- subprocess.run(
717
- [ # Run subprocess with Streamlit custom argument
718
- "streamlit",
719
- "run",
720
- str(ROOT / "solutions/streamlit_inference.py"),
721
- "--server.headless",
722
- "true",
723
- overrides.pop("model", "yolo26n.pt"),
724
- ]
725
- )
726
- else:
727
- import cv2 # Only needed for cap and vw functionality
728
-
729
- from ultralytics import solutions
730
-
731
- solution = getattr(solutions, SOLUTION_MAP[solution_name])(is_cli=True, **overrides) # class i.e. ObjectCounter
732
-
733
- cap = cv2.VideoCapture(solution.CFG["source"]) # read the video file
734
- if solution_name != "crop":
735
- # extract width, height and fps of the video file, create save directory and initialize video writer
736
- w, h, fps = (
737
- int(cap.get(x)) for x in (cv2.CAP_PROP_FRAME_WIDTH, cv2.CAP_PROP_FRAME_HEIGHT, cv2.CAP_PROP_FPS)
738
- )
739
- if solution_name == "analytics": # analytical graphs follow fixed shape for output i.e w=1920, h=1080
740
- w, h = 1280, 720
741
- save_dir = get_save_dir(SimpleNamespace(task="solutions", name="exp", exist_ok=False, project=None))
742
- save_dir.mkdir(parents=True, exist_ok=True) # create the output directory i.e. runs/solutions/exp
743
- vw = cv2.VideoWriter(str(save_dir / f"{solution_name}.avi"), cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))
744
-
745
- try: # Process video frames
746
- f_n = 0 # frame number, required for analytical graphs
747
- while cap.isOpened():
748
- success, frame = cap.read()
749
- if not success:
750
- break
751
- results = solution(frame, f_n := f_n + 1) if solution_name == "analytics" else solution(frame)
752
- if solution_name != "crop":
753
- vw.write(results.plot_im)
754
- if solution.CFG["show"] and cv2.waitKey(1) & 0xFF == ord("q"):
755
- break
756
- finally:
757
- cap.release()
758
-
759
-
760
- def parse_key_value_pair(pair: str = "key=value") -> tuple:
761
- """Parse a key-value pair string into separate key and value components.
762
-
763
- Args:
764
- pair (str): A string containing a key-value pair in the format "key=value".
765
-
766
- Returns:
767
- key (str): The parsed key.
768
- value (str): The parsed value.
769
-
770
- Raises:
771
- AssertionError: If the value is missing or empty.
772
-
773
- Examples:
774
- >>> key, value = parse_key_value_pair("model=yolo26n.pt")
775
- >>> print(f"Key: {key}, Value: {value}")
776
- Key: model, Value: yolo26n.pt
777
-
778
- >>> key, value = parse_key_value_pair("epochs=100")
779
- >>> print(f"Key: {key}, Value: {value}")
780
- Key: epochs, Value: 100
781
-
782
- Notes:
783
- - The function splits the input string on the first '=' character.
784
- - Leading and trailing whitespace is removed from both key and value.
785
- - An assertion error is raised if the value is empty after stripping.
786
- """
787
- k, v = pair.split("=", 1) # split on first '=' sign
788
- k, v = k.strip(), v.strip() # remove spaces
789
- assert v, f"missing '{k}' value"
790
- return k, smart_value(v)
791
-
792
-
793
- def smart_value(v: str) -> Any:
794
- """Convert a string representation of a value to its appropriate Python type.
795
-
796
- This function attempts to convert a given string into a Python object of the most appropriate type. It handles
797
- conversions to None, bool, int, float, and other types that can be evaluated safely.
798
-
799
- Args:
800
- v (str): The string representation of the value to be converted.
801
-
802
- Returns:
803
- (Any): The converted value. The type can be None, bool, int, float, or the original string if no conversion is
804
- applicable.
805
-
806
- Examples:
807
- >>> smart_value("42")
808
- 42
809
- >>> smart_value("3.14")
810
- 3.14
811
- >>> smart_value("True")
812
- True
813
- >>> smart_value("None")
814
- None
815
- >>> smart_value("some_string")
816
- 'some_string'
817
-
818
- Notes:
819
- - The function uses a case-insensitive comparison for boolean and None values.
820
- - For other types, it attempts to use Python's ast.literal_eval() function for safe evaluation.
821
- - If no conversion is possible, the original string is returned.
822
- """
823
- v_lower = v.lower()
824
- if v_lower == "none":
825
- return None
826
- elif v_lower == "true":
827
- return True
828
- elif v_lower == "false":
829
- return False
830
- else:
831
- try:
832
- return ast.literal_eval(v)
833
- except Exception:
834
- return v
835
-
836
-
837
- def entrypoint(debug: str = "") -> None:
838
- """Ultralytics entrypoint function for parsing and executing command-line arguments.
839
-
840
- This function serves as the main entry point for the Ultralytics CLI, parsing command-line arguments and executing
841
- the corresponding tasks such as training, validation, prediction, exporting models, and more.
842
-
843
- Args:
844
- debug (str): Space-separated string of command-line arguments for debugging purposes.
845
-
846
- Examples:
847
- Train a detection model for 10 epochs with an initial learning_rate of 0.01:
848
- >>> entrypoint("train data=coco8.yaml model=yolo26n.pt epochs=10 lr0=0.01")
849
-
850
- Predict a YouTube video using a pretrained segmentation model at image size 320:
851
- >>> entrypoint("predict model=yolo26n-seg.pt source='https://youtu.be/LNwODJXcvt4' imgsz=320")
852
-
853
- Validate a pretrained detection model at batch-size 1 and image size 640:
854
- >>> entrypoint("val model=yolo26n.pt data=coco8.yaml batch=1 imgsz=640")
855
-
856
- Notes:
857
- - If no arguments are passed, the function will display the usage help message.
858
- - For a list of all available commands and their arguments, see the provided help messages and the
859
- Ultralytics documentation at https://docs.ultralytics.com.
860
- """
861
- args = (debug.split(" ") if debug else ARGV)[1:]
862
- if not args: # no arguments passed
863
- LOGGER.info(CLI_HELP_MSG)
864
- return
865
-
866
- special = {
867
- "checks": checks.collect_system_info,
868
- "version": lambda: LOGGER.info(__version__),
869
- "settings": lambda: handle_yolo_settings(args[1:]),
870
- "cfg": lambda: YAML.print(DEFAULT_CFG_PATH),
871
- "hub": lambda: handle_yolo_hub(args[1:]),
872
- "login": lambda: handle_yolo_hub(args),
873
- "logout": lambda: handle_yolo_hub(args),
874
- "copy-cfg": copy_default_cfg,
875
- "solutions": lambda: handle_yolo_solutions(args[1:]),
876
- "help": lambda: LOGGER.info(CLI_HELP_MSG), # help below hub for -h flag precedence
877
- }
878
- full_args_dict = {**DEFAULT_CFG_DICT, **{k: None for k in TASKS}, **{k: None for k in MODES}, **special}
879
-
880
- # Define common misuses of special commands, i.e. -h, -help, --help
881
- special.update({k[0]: v for k, v in special.items()}) # singular
882
- special.update({k[:-1]: v for k, v in special.items() if len(k) > 1 and k.endswith("s")}) # singular
883
- special = {**special, **{f"-{k}": v for k, v in special.items()}, **{f"--{k}": v for k, v in special.items()}}
884
-
885
- overrides = {} # basic overrides, i.e. imgsz=320
886
- for a in merge_equals_args(args): # merge spaces around '=' sign
887
- if a.startswith("--"):
888
- LOGGER.warning(f"argument '{a}' does not require leading dashes '--', updating to '{a[2:]}'.")
889
- a = a[2:]
890
- if a.endswith(","):
891
- LOGGER.warning(f"argument '{a}' does not require trailing comma ',', updating to '{a[:-1]}'.")
892
- a = a[:-1]
893
- if "=" in a:
894
- try:
895
- k, v = parse_key_value_pair(a)
896
- if k == "cfg" and v is not None: # custom.yaml passed
897
- LOGGER.info(f"Overriding {DEFAULT_CFG_PATH} with {v}")
898
- overrides = {k: val for k, val in YAML.load(checks.check_yaml(v)).items() if k != "cfg"}
899
- else:
900
- overrides[k] = v
901
- except (NameError, SyntaxError, ValueError, AssertionError) as e:
902
- check_dict_alignment(full_args_dict, {a: ""}, e)
903
-
904
- elif a in TASKS:
905
- overrides["task"] = a
906
- elif a in MODES:
907
- overrides["mode"] = a
908
- elif a.lower() in special:
909
- special[a.lower()]()
910
- return
911
- elif a in DEFAULT_CFG_DICT and isinstance(DEFAULT_CFG_DICT[a], bool):
912
- overrides[a] = True # auto-True for default bool args, i.e. 'yolo show' sets show=True
913
- elif a in DEFAULT_CFG_DICT:
914
- raise SyntaxError(
915
- f"'{colorstr('red', 'bold', a)}' is a valid YOLO argument but is missing an '=' sign "
916
- f"to set its value, i.e. try '{a}={DEFAULT_CFG_DICT[a]}'\n{CLI_HELP_MSG}"
917
- )
918
- else:
919
- check_dict_alignment(full_args_dict, {a: ""})
920
-
921
- # Check keys
922
- check_dict_alignment(full_args_dict, overrides)
923
-
924
- # Mode
925
- mode = overrides.get("mode")
926
- if mode is None:
927
- mode = DEFAULT_CFG.mode or "predict"
928
- LOGGER.warning(f"'mode' argument is missing. Valid modes are {list(MODES)}. Using default 'mode={mode}'.")
929
- elif mode not in MODES:
930
- raise ValueError(f"Invalid 'mode={mode}'. Valid modes are {list(MODES)}.\n{CLI_HELP_MSG}")
931
-
932
- # Task
933
- task = overrides.pop("task", None)
934
- if task:
935
- if task not in TASKS:
936
- if task == "track":
937
- LOGGER.warning(
938
- f"invalid 'task=track', setting 'task=detect' and 'mode=track'. Valid tasks are {list(TASKS)}.\n{CLI_HELP_MSG}."
939
- )
940
- task, mode = "detect", "track"
941
- else:
942
- raise ValueError(f"Invalid 'task={task}'. Valid tasks are {list(TASKS)}.\n{CLI_HELP_MSG}")
943
- if "model" not in overrides:
944
- overrides["model"] = TASK2MODEL[task]
945
-
946
- # Model
947
- model = overrides.pop("model", DEFAULT_CFG.model)
948
- if model is None:
949
- model = "yolo26n.pt"
950
- LOGGER.warning(f"'model' argument is missing. Using default 'model={model}'.")
951
- overrides["model"] = model
952
- stem = Path(model).stem.lower()
953
- if "rtdetr" in stem: # guess architecture
954
- from ultralytics import RTDETR
955
-
956
- model = RTDETR(model) # no task argument
957
- elif "fastsam" in stem:
958
- from ultralytics import FastSAM
959
-
960
- model = FastSAM(model)
961
- elif "sam_" in stem or "sam2_" in stem or "sam2.1_" in stem:
962
- from ultralytics import SAM
963
-
964
- model = SAM(model)
965
- else:
966
- from ultralytics import YOLO
967
-
968
- model = YOLO(model, task=task)
969
- if "yoloe" in stem or "world" in stem:
970
- cls_list = overrides.pop("classes", DEFAULT_CFG.classes)
971
- if cls_list is not None and isinstance(cls_list, str):
972
- model.set_classes(cls_list.split(",")) # convert "person, bus" -> ['person', ' bus'].
973
- # Task Update
974
- if task != model.task:
975
- if task:
976
- LOGGER.warning(
977
- f"conflicting 'task={task}' passed with 'task={model.task}' model. "
978
- f"Ignoring 'task={task}' and updating to 'task={model.task}' to match model."
979
- )
980
- task = model.task
981
-
982
- # Mode
983
- if mode in {"predict", "track"} and "source" not in overrides:
984
- overrides["source"] = (
985
- "https://ultralytics.com/images/boats.jpg" if task == "obb" else DEFAULT_CFG.source or ASSETS
986
- )
987
- LOGGER.warning(f"'source' argument is missing. Using default 'source={overrides['source']}'.")
988
- elif mode in {"train", "val"}:
989
- if "data" not in overrides and "resume" not in overrides:
990
- overrides["data"] = DEFAULT_CFG.data or TASK2DATA.get(task or DEFAULT_CFG.task, DEFAULT_CFG.data)
991
- LOGGER.warning(f"'data' argument is missing. Using default 'data={overrides['data']}'.")
992
- elif mode == "export":
993
- if "format" not in overrides:
994
- overrides["format"] = DEFAULT_CFG.format or "torchscript"
995
- LOGGER.warning(f"'format' argument is missing. Using default 'format={overrides['format']}'.")
996
-
997
- # Run command in python
998
- getattr(model, mode)(**overrides) # default args from model
999
-
1000
- # Show help
1001
- LOGGER.info(f"💡 Learn more at https://docs.ultralytics.com/modes/{mode}")
1002
-
1003
- # Recommend VS Code extension
1004
- if IS_VSCODE and SETTINGS.get("vscode_msg", True):
1005
- LOGGER.info(vscode_msg())
1006
-
1007
-
1008
- # Special modes --------------------------------------------------------------------------------------------------------
1009
- def copy_default_cfg() -> None:
1010
- """Copy the default configuration file and create a new one with '_copy' appended to its name.
1011
-
1012
- This function duplicates the existing default configuration file (DEFAULT_CFG_PATH) and saves it with '_copy'
1013
- appended to its name in the current working directory. It provides a convenient way to create a custom configuration
1014
- file based on the default settings.
1015
-
1016
- Examples:
1017
- >>> copy_default_cfg()
1018
- # Output: default.yaml copied to /path/to/current/directory/default_copy.yaml
1019
- # Example YOLO command with this new custom cfg:
1020
- # yolo cfg='/path/to/current/directory/default_copy.yaml' imgsz=320 batch=8
1021
-
1022
- Notes:
1023
- - The new configuration file is created in the current working directory.
1024
- - After copying, the function prints a message with the new file's location and an example
1025
- YOLO command demonstrating how to use the new configuration file.
1026
- - This function is useful for users who want to modify the default configuration without
1027
- altering the original file.
1028
- """
1029
- new_file = Path.cwd() / DEFAULT_CFG_PATH.name.replace(".yaml", "_copy.yaml")
1030
- shutil.copy2(DEFAULT_CFG_PATH, new_file)
1031
- LOGGER.info(
1032
- f"{DEFAULT_CFG_PATH} copied to {new_file}\n"
1033
- f"Example YOLO command with this new custom cfg:\n yolo cfg='{new_file}' imgsz=320 batch=8"
1034
- )
1035
-
1036
-
1037
- if __name__ == "__main__":
1038
- # Example: entrypoint(debug='yolo predict model=yolo26n.pt')
1039
- entrypoint(debug="")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
vendor/ultralytics/cfg/datasets/Argoverse.yaml DELETED
@@ -1,78 +0,0 @@
1
- # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
-
3
- # Argoverse-HD dataset (ring-front-center camera) by Argo AI: https://www.cs.cmu.edu/~mengtial/proj/streaming/
4
- # Documentation: https://docs.ultralytics.com/datasets/detect/argoverse/
5
- # Example usage: yolo train data=Argoverse.yaml
6
- # parent
7
- # ├── ultralytics
8
- # └── datasets
9
- # └── Argoverse ← downloads here (31.5 GB)
10
-
11
- # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
12
- path: Argoverse # dataset root dir
13
- train: Argoverse-1.1/images/train/ # train images (relative to 'path') 39384 images
14
- val: Argoverse-1.1/images/val/ # val images (relative to 'path') 15062 images
15
- test: Argoverse-1.1/images/test/ # test images (optional) https://eval.ai/web/challenges/challenge-page/800/overview
16
-
17
- # Classes
18
- names:
19
- 0: person
20
- 1: bicycle
21
- 2: car
22
- 3: motorcycle
23
- 4: bus
24
- 5: truck
25
- 6: traffic_light
26
- 7: stop_sign
27
-
28
- # Download script/URL (optional) ---------------------------------------------------------------------------------------
29
- download: |
30
- import json
31
- from pathlib import Path
32
-
33
- from ultralytics.utils import TQDM
34
- from ultralytics.utils.downloads import download
35
-
36
- def argoverse2yolo(annotation_file):
37
- """Convert Argoverse dataset annotations to YOLO format for object detection tasks."""
38
- labels = {}
39
- with open(annotation_file, encoding="utf-8") as f:
40
- a = json.load(f)
41
- for annot in TQDM(a["annotations"], desc=f"Converting {annotation_file} to YOLO format..."):
42
- img_id = annot["image_id"]
43
- img_name = a["images"][img_id]["name"]
44
- img_label_name = f"{Path(img_name).stem}.txt"
45
-
46
- cls = annot["category_id"] # instance class id
47
- x_center, y_center, width, height = annot["bbox"]
48
- x_center = (x_center + width / 2) / 1920.0 # offset and scale
49
- y_center = (y_center + height / 2) / 1200.0 # offset and scale
50
- width /= 1920.0 # scale
51
- height /= 1200.0 # scale
52
-
53
- img_dir = annotation_file.parents[2] / "Argoverse-1.1" / "labels" / a["seq_dirs"][a["images"][annot["image_id"]]["sid"]]
54
- if not img_dir.exists():
55
- img_dir.mkdir(parents=True, exist_ok=True)
56
-
57
- k = str(img_dir / img_label_name)
58
- if k not in labels:
59
- labels[k] = []
60
- labels[k].append(f"{cls} {x_center} {y_center} {width} {height}\n")
61
-
62
- for k in labels:
63
- with open(k, "w", encoding="utf-8") as f:
64
- f.writelines(labels[k])
65
-
66
-
67
- # Download 'https://argoverse-hd.s3.us-east-2.amazonaws.com/Argoverse-HD-Full.zip' (deprecated S3 link)
68
- dir = Path(yaml["path"]) # dataset root dir
69
- urls = ["https://drive.google.com/file/d/1st9qW3BeIwQsnR0t8mRpvbsSWIo16ACi/view?usp=drive_link"]
70
- print("\n\nWARNING: Argoverse dataset MUST be downloaded manually, autodownload will NOT work.")
71
- print(f"WARNING: Manually download Argoverse dataset '{urls[0]}' to '{dir}' and re-run your command.\n\n")
72
- # download(urls, dir=dir)
73
-
74
- # Convert
75
- annotations_dir = "Argoverse-HD/annotations/"
76
- (dir / "Argoverse-1.1" / "tracking").rename(dir / "Argoverse-1.1" / "images") # rename 'tracking' to 'images'
77
- for d in "train.json", "val.json":
78
- argoverse2yolo(dir / annotations_dir / d) # convert Argoverse annotations to YOLO labels
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
vendor/ultralytics/cfg/datasets/DOTAv1.5.yaml DELETED
@@ -1,37 +0,0 @@
1
- # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
-
3
- # DOTA 1.5 dataset https://captain-whu.github.io/DOTA/index.html for object detection in aerial images by Wuhan University
4
- # Documentation: https://docs.ultralytics.com/datasets/obb/dota-v2/
5
- # Example usage: yolo train model=yolov8n-obb.pt data=DOTAv1.5.yaml
6
- # parent
7
- # ├── ultralytics
8
- # └── datasets
9
- # └── dota1.5 ← downloads here (2 GB)
10
-
11
- # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
12
- path: DOTAv1.5 # dataset root dir
13
- train: images/train # train images (relative to 'path') 1411 images
14
- val: images/val # val images (relative to 'path') 458 images
15
- test: images/test # test images (optional) 937 images
16
-
17
- # Classes for DOTA 1.5
18
- names:
19
- 0: plane
20
- 1: ship
21
- 2: storage tank
22
- 3: baseball diamond
23
- 4: tennis court
24
- 5: basketball court
25
- 6: ground track field
26
- 7: harbor
27
- 8: bridge
28
- 9: large vehicle
29
- 10: small vehicle
30
- 11: helicopter
31
- 12: roundabout
32
- 13: soccer ball field
33
- 14: swimming pool
34
- 15: container crane
35
-
36
- # Download script/URL (optional)
37
- download: https://github.com/ultralytics/assets/releases/download/v0.0.0/DOTAv1.5.zip
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
vendor/ultralytics/cfg/datasets/DOTAv1.yaml DELETED
@@ -1,36 +0,0 @@
1
- # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
-
3
- # DOTA 1.0 dataset https://captain-whu.github.io/DOTA/index.html for object detection in aerial images by Wuhan University
4
- # Documentation: https://docs.ultralytics.com/datasets/obb/dota-v2/
5
- # Example usage: yolo train model=yolov8n-obb.pt data=DOTAv1.yaml
6
- # parent
7
- # ├── ultralytics
8
- # └── datasets
9
- # └── dota1 ← downloads here (2 GB)
10
-
11
- # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
12
- path: DOTAv1 # dataset root dir
13
- train: images/train # train images (relative to 'path') 1411 images
14
- val: images/val # val images (relative to 'path') 458 images
15
- test: images/test # test images (optional) 937 images
16
-
17
- # Classes for DOTA 1.0
18
- names:
19
- 0: plane
20
- 1: ship
21
- 2: storage tank
22
- 3: baseball diamond
23
- 4: tennis court
24
- 5: basketball court
25
- 6: ground track field
26
- 7: harbor
27
- 8: bridge
28
- 9: large vehicle
29
- 10: small vehicle
30
- 11: helicopter
31
- 12: roundabout
32
- 13: soccer ball field
33
- 14: swimming pool
34
-
35
- # Download script/URL (optional)
36
- download: https://github.com/ultralytics/assets/releases/download/v0.0.0/DOTAv1.zip
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
vendor/ultralytics/cfg/datasets/GlobalWheat2020.yaml DELETED
@@ -1,68 +0,0 @@
1
- # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
-
3
- # Global Wheat 2020 dataset https://www.global-wheat.com/ by University of Saskatchewan
4
- # Documentation: https://docs.ultralytics.com/datasets/detect/globalwheat2020/
5
- # Example usage: yolo train data=GlobalWheat2020.yaml
6
- # parent
7
- # ├── ultralytics
8
- # └── datasets
9
- # └── GlobalWheat2020 ← downloads here (7.0 GB)
10
-
11
- # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
12
- path: GlobalWheat2020 # dataset root dir
13
- train: # train images (relative to 'path') 3422 images
14
- - images/arvalis_1
15
- - images/arvalis_2
16
- - images/arvalis_3
17
- - images/ethz_1
18
- - images/rres_1
19
- - images/inrae_1
20
- - images/usask_1
21
- val: # val images (relative to 'path') 748 images (WARNING: train set contains ethz_1)
22
- - images/ethz_1
23
- test: # test images (optional) 1276 images
24
- - images/utokyo_1
25
- - images/utokyo_2
26
- - images/nau_1
27
- - images/uq_1
28
-
29
- # Classes
30
- names:
31
- 0: wheat_head
32
-
33
- # Download script/URL (optional) ---------------------------------------------------------------------------------------
34
- download: |
35
- from pathlib import Path
36
-
37
- from ultralytics.utils.downloads import download
38
-
39
- # Download
40
- dir = Path(yaml["path"]) # dataset root dir
41
- urls = [
42
- "https://zenodo.org/record/4298502/files/global-wheat-codalab-official.zip",
43
- "https://github.com/ultralytics/assets/releases/download/v0.0.0/GlobalWheat2020_labels.zip",
44
- ]
45
- download(urls, dir=dir)
46
-
47
- # Make Directories
48
- for p in "annotations", "images", "labels":
49
- (dir / p).mkdir(parents=True, exist_ok=True)
50
-
51
- # Move
52
- for p in (
53
- "arvalis_1",
54
- "arvalis_2",
55
- "arvalis_3",
56
- "ethz_1",
57
- "rres_1",
58
- "inrae_1",
59
- "usask_1",
60
- "utokyo_1",
61
- "utokyo_2",
62
- "nau_1",
63
- "uq_1",
64
- ):
65
- (dir / "global-wheat-codalab-official" / p).rename(dir / "images" / p) # move to /images
66
- f = (dir / "global-wheat-codalab-official" / p).with_suffix(".json") # json file
67
- if f.exists():
68
- f.rename((dir / "annotations" / p).with_suffix(".json")) # move to /annotations
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
vendor/ultralytics/cfg/datasets/HomeObjects-3K.yaml DELETED
@@ -1,32 +0,0 @@
1
- # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
-
3
- # HomeObjects-3K dataset by Ultralytics
4
- # Documentation: https://docs.ultralytics.com/datasets/detect/homeobjects-3k/
5
- # Example usage: yolo train data=HomeObjects-3K.yaml
6
- # parent
7
- # ├── ultralytics
8
- # └── datasets
9
- # └── homeobjects-3K ← downloads here (390 MB)
10
-
11
- # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
12
- path: homeobjects-3K # dataset root dir
13
- train: images/train # train images (relative to 'path') 2285 images
14
- val: images/val # val images (relative to 'path') 404 images
15
-
16
- # Classes
17
- names:
18
- 0: bed
19
- 1: sofa
20
- 2: chair
21
- 3: table
22
- 4: lamp
23
- 5: tv
24
- 6: laptop
25
- 7: wardrobe
26
- 8: window
27
- 9: door
28
- 10: potted plant
29
- 11: photo frame
30
-
31
- # Download script/URL (optional)
32
- download: https://github.com/ultralytics/assets/releases/download/v0.0.0/homeobjects-3K.zip
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
vendor/ultralytics/cfg/datasets/ImageNet.yaml DELETED
@@ -1,2025 +0,0 @@
1
- # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
-
3
- # ImageNet-1k dataset https://www.image-net.org/index.php by Stanford University
4
- # Simplified class names from https://github.com/anishathalye/imagenet-simple-labels
5
- # Documentation: https://docs.ultralytics.com/datasets/classify/imagenet/
6
- # Example usage: yolo train task=classify data=imagenet
7
- # parent
8
- # ├── ultralytics
9
- # └── datasets
10
- # └── imagenet ← downloads here (144 GB)
11
-
12
- # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
13
- path: imagenet # dataset root dir
14
- train: train # train images (relative to 'path') 1281167 images
15
- val: val # val images (relative to 'path') 50000 images
16
- test: # test images (optional)
17
-
18
- # Classes
19
- names:
20
- 0: tench
21
- 1: goldfish
22
- 2: great white shark
23
- 3: tiger shark
24
- 4: hammerhead shark
25
- 5: electric ray
26
- 6: stingray
27
- 7: cock
28
- 8: hen
29
- 9: ostrich
30
- 10: brambling
31
- 11: goldfinch
32
- 12: house finch
33
- 13: junco
34
- 14: indigo bunting
35
- 15: American robin
36
- 16: bulbul
37
- 17: jay
38
- 18: magpie
39
- 19: chickadee
40
- 20: American dipper
41
- 21: kite
42
- 22: bald eagle
43
- 23: vulture
44
- 24: great grey owl
45
- 25: fire salamander
46
- 26: smooth newt
47
- 27: newt
48
- 28: spotted salamander
49
- 29: axolotl
50
- 30: American bullfrog
51
- 31: tree frog
52
- 32: tailed frog
53
- 33: loggerhead sea turtle
54
- 34: leatherback sea turtle
55
- 35: mud turtle
56
- 36: terrapin
57
- 37: box turtle
58
- 38: banded gecko
59
- 39: green iguana
60
- 40: Carolina anole
61
- 41: desert grassland whiptail lizard
62
- 42: agama
63
- 43: frilled-necked lizard
64
- 44: alligator lizard
65
- 45: Gila monster
66
- 46: European green lizard
67
- 47: chameleon
68
- 48: Komodo dragon
69
- 49: Nile crocodile
70
- 50: American alligator
71
- 51: triceratops
72
- 52: worm snake
73
- 53: ring-necked snake
74
- 54: eastern hog-nosed snake
75
- 55: smooth green snake
76
- 56: kingsnake
77
- 57: garter snake
78
- 58: water snake
79
- 59: vine snake
80
- 60: night snake
81
- 61: boa constrictor
82
- 62: African rock python
83
- 63: Indian cobra
84
- 64: green mamba
85
- 65: sea snake
86
- 66: Saharan horned viper
87
- 67: eastern diamondback rattlesnake
88
- 68: sidewinder
89
- 69: trilobite
90
- 70: harvestman
91
- 71: scorpion
92
- 72: yellow garden spider
93
- 73: barn spider
94
- 74: European garden spider
95
- 75: southern black widow
96
- 76: tarantula
97
- 77: wolf spider
98
- 78: tick
99
- 79: centipede
100
- 80: black grouse
101
- 81: ptarmigan
102
- 82: ruffed grouse
103
- 83: prairie grouse
104
- 84: peacock
105
- 85: quail
106
- 86: partridge
107
- 87: grey parrot
108
- 88: macaw
109
- 89: sulphur-crested cockatoo
110
- 90: lorikeet
111
- 91: coucal
112
- 92: bee eater
113
- 93: hornbill
114
- 94: hummingbird
115
- 95: jacamar
116
- 96: toucan
117
- 97: duck
118
- 98: red-breasted merganser
119
- 99: goose
120
- 100: black swan
121
- 101: tusker
122
- 102: echidna
123
- 103: platypus
124
- 104: wallaby
125
- 105: koala
126
- 106: wombat
127
- 107: jellyfish
128
- 108: sea anemone
129
- 109: brain coral
130
- 110: flatworm
131
- 111: nematode
132
- 112: conch
133
- 113: snail
134
- 114: slug
135
- 115: sea slug
136
- 116: chiton
137
- 117: chambered nautilus
138
- 118: Dungeness crab
139
- 119: rock crab
140
- 120: fiddler crab
141
- 121: red king crab
142
- 122: American lobster
143
- 123: spiny lobster
144
- 124: crayfish
145
- 125: hermit crab
146
- 126: isopod
147
- 127: white stork
148
- 128: black stork
149
- 129: spoonbill
150
- 130: flamingo
151
- 131: little blue heron
152
- 132: great egret
153
- 133: bittern
154
- 134: crane (bird)
155
- 135: limpkin
156
- 136: common gallinule
157
- 137: American coot
158
- 138: bustard
159
- 139: ruddy turnstone
160
- 140: dunlin
161
- 141: common redshank
162
- 142: dowitcher
163
- 143: oystercatcher
164
- 144: pelican
165
- 145: king penguin
166
- 146: albatross
167
- 147: grey whale
168
- 148: killer whale
169
- 149: dugong
170
- 150: sea lion
171
- 151: Chihuahua
172
- 152: Japanese Chin
173
- 153: Maltese
174
- 154: Pekingese
175
- 155: Shih Tzu
176
- 156: King Charles Spaniel
177
- 157: Papillon
178
- 158: toy terrier
179
- 159: Rhodesian Ridgeback
180
- 160: Afghan Hound
181
- 161: Basset Hound
182
- 162: Beagle
183
- 163: Bloodhound
184
- 164: Bluetick Coonhound
185
- 165: Black and Tan Coonhound
186
- 166: Treeing Walker Coonhound
187
- 167: English foxhound
188
- 168: Redbone Coonhound
189
- 169: borzoi
190
- 170: Irish Wolfhound
191
- 171: Italian Greyhound
192
- 172: Whippet
193
- 173: Ibizan Hound
194
- 174: Norwegian Elkhound
195
- 175: Otterhound
196
- 176: Saluki
197
- 177: Scottish Deerhound
198
- 178: Weimaraner
199
- 179: Staffordshire Bull Terrier
200
- 180: American Staffordshire Terrier
201
- 181: Bedlington Terrier
202
- 182: Border Terrier
203
- 183: Kerry Blue Terrier
204
- 184: Irish Terrier
205
- 185: Norfolk Terrier
206
- 186: Norwich Terrier
207
- 187: Yorkshire Terrier
208
- 188: Wire Fox Terrier
209
- 189: Lakeland Terrier
210
- 190: Sealyham Terrier
211
- 191: Airedale Terrier
212
- 192: Cairn Terrier
213
- 193: Australian Terrier
214
- 194: Dandie Dinmont Terrier
215
- 195: Boston Terrier
216
- 196: Miniature Schnauzer
217
- 197: Giant Schnauzer
218
- 198: Standard Schnauzer
219
- 199: Scottish Terrier
220
- 200: Tibetan Terrier
221
- 201: Australian Silky Terrier
222
- 202: Soft-coated Wheaten Terrier
223
- 203: West Highland White Terrier
224
- 204: Lhasa Apso
225
- 205: Flat-Coated Retriever
226
- 206: Curly-coated Retriever
227
- 207: Golden Retriever
228
- 208: Labrador Retriever
229
- 209: Chesapeake Bay Retriever
230
- 210: German Shorthaired Pointer
231
- 211: Vizsla
232
- 212: English Setter
233
- 213: Irish Setter
234
- 214: Gordon Setter
235
- 215: Brittany
236
- 216: Clumber Spaniel
237
- 217: English Springer Spaniel
238
- 218: Welsh Springer Spaniel
239
- 219: Cocker Spaniels
240
- 220: Sussex Spaniel
241
- 221: Irish Water Spaniel
242
- 222: Kuvasz
243
- 223: Schipperke
244
- 224: Groenendael
245
- 225: Malinois
246
- 226: Briard
247
- 227: Australian Kelpie
248
- 228: Komondor
249
- 229: Old English Sheepdog
250
- 230: Shetland Sheepdog
251
- 231: collie
252
- 232: Border Collie
253
- 233: Bouvier des Flandres
254
- 234: Rottweiler
255
- 235: German Shepherd Dog
256
- 236: Dobermann
257
- 237: Miniature Pinscher
258
- 238: Greater Swiss Mountain Dog
259
- 239: Bernese Mountain Dog
260
- 240: Appenzeller Sennenhund
261
- 241: Entlebucher Sennenhund
262
- 242: Boxer
263
- 243: Bullmastiff
264
- 244: Tibetan Mastiff
265
- 245: French Bulldog
266
- 246: Great Dane
267
- 247: St. Bernard
268
- 248: husky
269
- 249: Alaskan Malamute
270
- 250: Siberian Husky
271
- 251: Dalmatian
272
- 252: Affenpinscher
273
- 253: Basenji
274
- 254: pug
275
- 255: Leonberger
276
- 256: Newfoundland
277
- 257: Pyrenean Mountain Dog
278
- 258: Samoyed
279
- 259: Pomeranian
280
- 260: Chow Chow
281
- 261: Keeshond
282
- 262: Griffon Bruxellois
283
- 263: Pembroke Welsh Corgi
284
- 264: Cardigan Welsh Corgi
285
- 265: Toy Poodle
286
- 266: Miniature Poodle
287
- 267: Standard Poodle
288
- 268: Mexican hairless dog
289
- 269: grey wolf
290
- 270: Alaskan tundra wolf
291
- 271: red wolf
292
- 272: coyote
293
- 273: dingo
294
- 274: dhole
295
- 275: African wild dog
296
- 276: hyena
297
- 277: red fox
298
- 278: kit fox
299
- 279: Arctic fox
300
- 280: grey fox
301
- 281: tabby cat
302
- 282: tiger cat
303
- 283: Persian cat
304
- 284: Siamese cat
305
- 285: Egyptian Mau
306
- 286: cougar
307
- 287: lynx
308
- 288: leopard
309
- 289: snow leopard
310
- 290: jaguar
311
- 291: lion
312
- 292: tiger
313
- 293: cheetah
314
- 294: brown bear
315
- 295: American black bear
316
- 296: polar bear
317
- 297: sloth bear
318
- 298: mongoose
319
- 299: meerkat
320
- 300: tiger beetle
321
- 301: ladybug
322
- 302: ground beetle
323
- 303: longhorn beetle
324
- 304: leaf beetle
325
- 305: dung beetle
326
- 306: rhinoceros beetle
327
- 307: weevil
328
- 308: fly
329
- 309: bee
330
- 310: ant
331
- 311: grasshopper
332
- 312: cricket
333
- 313: stick insect
334
- 314: cockroach
335
- 315: mantis
336
- 316: cicada
337
- 317: leafhopper
338
- 318: lacewing
339
- 319: dragonfly
340
- 320: damselfly
341
- 321: red admiral
342
- 322: ringlet
343
- 323: monarch butterfly
344
- 324: small white
345
- 325: sulfur butterfly
346
- 326: gossamer-winged butterfly
347
- 327: starfish
348
- 328: sea urchin
349
- 329: sea cucumber
350
- 330: cottontail rabbit
351
- 331: hare
352
- 332: Angora rabbit
353
- 333: hamster
354
- 334: porcupine
355
- 335: fox squirrel
356
- 336: marmot
357
- 337: beaver
358
- 338: guinea pig
359
- 339: common sorrel
360
- 340: zebra
361
- 341: pig
362
- 342: wild boar
363
- 343: warthog
364
- 344: hippopotamus
365
- 345: ox
366
- 346: water buffalo
367
- 347: bison
368
- 348: ram
369
- 349: bighorn sheep
370
- 350: Alpine ibex
371
- 351: hartebeest
372
- 352: impala
373
- 353: gazelle
374
- 354: dromedary
375
- 355: llama
376
- 356: weasel
377
- 357: mink
378
- 358: European polecat
379
- 359: black-footed ferret
380
- 360: otter
381
- 361: skunk
382
- 362: badger
383
- 363: armadillo
384
- 364: three-toed sloth
385
- 365: orangutan
386
- 366: gorilla
387
- 367: chimpanzee
388
- 368: gibbon
389
- 369: siamang
390
- 370: guenon
391
- 371: patas monkey
392
- 372: baboon
393
- 373: macaque
394
- 374: langur
395
- 375: black-and-white colobus
396
- 376: proboscis monkey
397
- 377: marmoset
398
- 378: white-headed capuchin
399
- 379: howler monkey
400
- 380: titi
401
- 381: Geoffroy's spider monkey
402
- 382: common squirrel monkey
403
- 383: ring-tailed lemur
404
- 384: indri
405
- 385: Asian elephant
406
- 386: African bush elephant
407
- 387: red panda
408
- 388: giant panda
409
- 389: snoek
410
- 390: eel
411
- 391: coho salmon
412
- 392: rock beauty
413
- 393: clownfish
414
- 394: sturgeon
415
- 395: garfish
416
- 396: lionfish
417
- 397: pufferfish
418
- 398: abacus
419
- 399: abaya
420
- 400: academic gown
421
- 401: accordion
422
- 402: acoustic guitar
423
- 403: aircraft carrier
424
- 404: airliner
425
- 405: airship
426
- 406: altar
427
- 407: ambulance
428
- 408: amphibious vehicle
429
- 409: analog clock
430
- 410: apiary
431
- 411: apron
432
- 412: waste container
433
- 413: assault rifle
434
- 414: backpack
435
- 415: bakery
436
- 416: balance beam
437
- 417: balloon
438
- 418: ballpoint pen
439
- 419: Band-Aid
440
- 420: banjo
441
- 421: baluster
442
- 422: barbell
443
- 423: barber chair
444
- 424: barbershop
445
- 425: barn
446
- 426: barometer
447
- 427: barrel
448
- 428: wheelbarrow
449
- 429: baseball
450
- 430: basketball
451
- 431: bassinet
452
- 432: bassoon
453
- 433: swimming cap
454
- 434: bath towel
455
- 435: bathtub
456
- 436: station wagon
457
- 437: lighthouse
458
- 438: beaker
459
- 439: military cap
460
- 440: beer bottle
461
- 441: beer glass
462
- 442: bell-cot
463
- 443: bib
464
- 444: tandem bicycle
465
- 445: bikini
466
- 446: ring binder
467
- 447: binoculars
468
- 448: birdhouse
469
- 449: boathouse
470
- 450: bobsleigh
471
- 451: bolo tie
472
- 452: poke bonnet
473
- 453: bookcase
474
- 454: bookstore
475
- 455: bottle cap
476
- 456: bow
477
- 457: bow tie
478
- 458: brass
479
- 459: bra
480
- 460: breakwater
481
- 461: breastplate
482
- 462: broom
483
- 463: bucket
484
- 464: buckle
485
- 465: bulletproof vest
486
- 466: high-speed train
487
- 467: butcher shop
488
- 468: taxicab
489
- 469: cauldron
490
- 470: candle
491
- 471: cannon
492
- 472: canoe
493
- 473: can opener
494
- 474: cardigan
495
- 475: car mirror
496
- 476: carousel
497
- 477: tool kit
498
- 478: carton
499
- 479: car wheel
500
- 480: automated teller machine
501
- 481: cassette
502
- 482: cassette player
503
- 483: castle
504
- 484: catamaran
505
- 485: CD player
506
- 486: cello
507
- 487: mobile phone
508
- 488: chain
509
- 489: chain-link fence
510
- 490: chain mail
511
- 491: chainsaw
512
- 492: chest
513
- 493: chiffonier
514
- 494: chime
515
- 495: china cabinet
516
- 496: Christmas stocking
517
- 497: church
518
- 498: movie theater
519
- 499: cleaver
520
- 500: cliff dwelling
521
- 501: cloak
522
- 502: clogs
523
- 503: cocktail shaker
524
- 504: coffee mug
525
- 505: coffeemaker
526
- 506: coil
527
- 507: combination lock
528
- 508: computer keyboard
529
- 509: confectionery store
530
- 510: container ship
531
- 511: convertible
532
- 512: corkscrew
533
- 513: cornet
534
- 514: cowboy boot
535
- 515: cowboy hat
536
- 516: cradle
537
- 517: crane (machine)
538
- 518: crash helmet
539
- 519: crate
540
- 520: infant bed
541
- 521: Crock Pot
542
- 522: croquet ball
543
- 523: crutch
544
- 524: cuirass
545
- 525: dam
546
- 526: desk
547
- 527: desktop computer
548
- 528: rotary dial telephone
549
- 529: diaper
550
- 530: digital clock
551
- 531: digital watch
552
- 532: dining table
553
- 533: dishcloth
554
- 534: dishwasher
555
- 535: disc brake
556
- 536: dock
557
- 537: dog sled
558
- 538: dome
559
- 539: doormat
560
- 540: drilling rig
561
- 541: drum
562
- 542: drumstick
563
- 543: dumbbell
564
- 544: Dutch oven
565
- 545: electric fan
566
- 546: electric guitar
567
- 547: electric locomotive
568
- 548: entertainment center
569
- 549: envelope
570
- 550: espresso machine
571
- 551: face powder
572
- 552: feather boa
573
- 553: filing cabinet
574
- 554: fireboat
575
- 555: fire engine
576
- 556: fire screen sheet
577
- 557: flagpole
578
- 558: flute
579
- 559: folding chair
580
- 560: football helmet
581
- 561: forklift
582
- 562: fountain
583
- 563: fountain pen
584
- 564: four-poster bed
585
- 565: freight car
586
- 566: French horn
587
- 567: frying pan
588
- 568: fur coat
589
- 569: garbage truck
590
- 570: gas mask
591
- 571: gas pump
592
- 572: goblet
593
- 573: go-kart
594
- 574: golf ball
595
- 575: golf cart
596
- 576: gondola
597
- 577: gong
598
- 578: gown
599
- 579: grand piano
600
- 580: greenhouse
601
- 581: grille
602
- 582: grocery store
603
- 583: guillotine
604
- 584: barrette
605
- 585: hair spray
606
- 586: half-track
607
- 587: hammer
608
- 588: hamper
609
- 589: hair dryer
610
- 590: hand-held computer
611
- 591: handkerchief
612
- 592: hard disk drive
613
- 593: harmonica
614
- 594: harp
615
- 595: harvester
616
- 596: hatchet
617
- 597: holster
618
- 598: home theater
619
- 599: honeycomb
620
- 600: hook
621
- 601: hoop skirt
622
- 602: horizontal bar
623
- 603: horse-drawn vehicle
624
- 604: hourglass
625
- 605: iPod
626
- 606: clothes iron
627
- 607: jack-o'-lantern
628
- 608: jeans
629
- 609: jeep
630
- 610: T-shirt
631
- 611: jigsaw puzzle
632
- 612: pulled rickshaw
633
- 613: joystick
634
- 614: kimono
635
- 615: knee pad
636
- 616: knot
637
- 617: lab coat
638
- 618: ladle
639
- 619: lampshade
640
- 620: laptop computer
641
- 621: lawn mower
642
- 622: lens cap
643
- 623: paper knife
644
- 624: library
645
- 625: lifeboat
646
- 626: lighter
647
- 627: limousine
648
- 628: ocean liner
649
- 629: lipstick
650
- 630: slip-on shoe
651
- 631: lotion
652
- 632: speaker
653
- 633: loupe
654
- 634: sawmill
655
- 635: magnetic compass
656
- 636: mail bag
657
- 637: mailbox
658
- 638: tights
659
- 639: tank suit
660
- 640: manhole cover
661
- 641: maraca
662
- 642: marimba
663
- 643: mask
664
- 644: match
665
- 645: maypole
666
- 646: maze
667
- 647: measuring cup
668
- 648: medicine chest
669
- 649: megalith
670
- 650: microphone
671
- 651: microwave oven
672
- 652: military uniform
673
- 653: milk can
674
- 654: minibus
675
- 655: miniskirt
676
- 656: minivan
677
- 657: missile
678
- 658: mitten
679
- 659: mixing bowl
680
- 660: mobile home
681
- 661: Model T
682
- 662: modem
683
- 663: monastery
684
- 664: monitor
685
- 665: moped
686
- 666: mortar
687
- 667: square academic cap
688
- 668: mosque
689
- 669: mosquito net
690
- 670: scooter
691
- 671: mountain bike
692
- 672: tent
693
- 673: computer mouse
694
- 674: mousetrap
695
- 675: moving van
696
- 676: muzzle
697
- 677: nail
698
- 678: neck brace
699
- 679: necklace
700
- 680: nipple
701
- 681: notebook computer
702
- 682: obelisk
703
- 683: oboe
704
- 684: ocarina
705
- 685: odometer
706
- 686: oil filter
707
- 687: organ
708
- 688: oscilloscope
709
- 689: overskirt
710
- 690: bullock cart
711
- 691: oxygen mask
712
- 692: packet
713
- 693: paddle
714
- 694: paddle wheel
715
- 695: padlock
716
- 696: paintbrush
717
- 697: pajamas
718
- 698: palace
719
- 699: pan flute
720
- 700: paper towel
721
- 701: parachute
722
- 702: parallel bars
723
- 703: park bench
724
- 704: parking meter
725
- 705: passenger car
726
- 706: patio
727
- 707: payphone
728
- 708: pedestal
729
- 709: pencil case
730
- 710: pencil sharpener
731
- 711: perfume
732
- 712: Petri dish
733
- 713: photocopier
734
- 714: plectrum
735
- 715: Pickelhaube
736
- 716: picket fence
737
- 717: pickup truck
738
- 718: pier
739
- 719: piggy bank
740
- 720: pill bottle
741
- 721: pillow
742
- 722: ping-pong ball
743
- 723: pinwheel
744
- 724: pirate ship
745
- 725: pitcher
746
- 726: hand plane
747
- 727: planetarium
748
- 728: plastic bag
749
- 729: plate rack
750
- 730: plow
751
- 731: plunger
752
- 732: Polaroid camera
753
- 733: pole
754
- 734: police van
755
- 735: poncho
756
- 736: billiard table
757
- 737: soda bottle
758
- 738: pot
759
- 739: potter's wheel
760
- 740: power drill
761
- 741: prayer rug
762
- 742: printer
763
- 743: prison
764
- 744: projectile
765
- 745: projector
766
- 746: hockey puck
767
- 747: punching bag
768
- 748: purse
769
- 749: quill
770
- 750: quilt
771
- 751: race car
772
- 752: racket
773
- 753: radiator
774
- 754: radio
775
- 755: radio telescope
776
- 756: rain barrel
777
- 757: recreational vehicle
778
- 758: reel
779
- 759: reflex camera
780
- 760: refrigerator
781
- 761: remote control
782
- 762: restaurant
783
- 763: revolver
784
- 764: rifle
785
- 765: rocking chair
786
- 766: rotisserie
787
- 767: eraser
788
- 768: rugby ball
789
- 769: ruler
790
- 770: running shoe
791
- 771: safe
792
- 772: safety pin
793
- 773: salt shaker
794
- 774: sandal
795
- 775: sarong
796
- 776: saxophone
797
- 777: scabbard
798
- 778: weighing scale
799
- 779: school bus
800
- 780: schooner
801
- 781: scoreboard
802
- 782: CRT screen
803
- 783: screw
804
- 784: screwdriver
805
- 785: seat belt
806
- 786: sewing machine
807
- 787: shield
808
- 788: shoe store
809
- 789: shoji
810
- 790: shopping basket
811
- 791: shopping cart
812
- 792: shovel
813
- 793: shower cap
814
- 794: shower curtain
815
- 795: ski
816
- 796: ski mask
817
- 797: sleeping bag
818
- 798: slide rule
819
- 799: sliding door
820
- 800: slot machine
821
- 801: snorkel
822
- 802: snowmobile
823
- 803: snowplow
824
- 804: soap dispenser
825
- 805: soccer ball
826
- 806: sock
827
- 807: solar thermal collector
828
- 808: sombrero
829
- 809: soup bowl
830
- 810: space bar
831
- 811: space heater
832
- 812: space shuttle
833
- 813: spatula
834
- 814: motorboat
835
- 815: spider web
836
- 816: spindle
837
- 817: sports car
838
- 818: spotlight
839
- 819: stage
840
- 820: steam locomotive
841
- 821: through arch bridge
842
- 822: steel drum
843
- 823: stethoscope
844
- 824: scarf
845
- 825: stone wall
846
- 826: stopwatch
847
- 827: stove
848
- 828: strainer
849
- 829: tram
850
- 830: stretcher
851
- 831: couch
852
- 832: stupa
853
- 833: submarine
854
- 834: suit
855
- 835: sundial
856
- 836: sunglass
857
- 837: sunglasses
858
- 838: sunscreen
859
- 839: suspension bridge
860
- 840: mop
861
- 841: sweatshirt
862
- 842: swimsuit
863
- 843: swing
864
- 844: switch
865
- 845: syringe
866
- 846: table lamp
867
- 847: tank
868
- 848: tape player
869
- 849: teapot
870
- 850: teddy bear
871
- 851: television
872
- 852: tennis ball
873
- 853: thatched roof
874
- 854: front curtain
875
- 855: thimble
876
- 856: threshing machine
877
- 857: throne
878
- 858: tile roof
879
- 859: toaster
880
- 860: tobacco shop
881
- 861: toilet seat
882
- 862: torch
883
- 863: totem pole
884
- 864: tow truck
885
- 865: toy store
886
- 866: tractor
887
- 867: semi-trailer truck
888
- 868: tray
889
- 869: trench coat
890
- 870: tricycle
891
- 871: trimaran
892
- 872: tripod
893
- 873: triumphal arch
894
- 874: trolleybus
895
- 875: trombone
896
- 876: tub
897
- 877: turnstile
898
- 878: typewriter keyboard
899
- 879: umbrella
900
- 880: unicycle
901
- 881: upright piano
902
- 882: vacuum cleaner
903
- 883: vase
904
- 884: vault
905
- 885: velvet
906
- 886: vending machine
907
- 887: vestment
908
- 888: viaduct
909
- 889: violin
910
- 890: volleyball
911
- 891: waffle iron
912
- 892: wall clock
913
- 893: wallet
914
- 894: wardrobe
915
- 895: military aircraft
916
- 896: sink
917
- 897: washing machine
918
- 898: water bottle
919
- 899: water jug
920
- 900: water tower
921
- 901: whiskey jug
922
- 902: whistle
923
- 903: wig
924
- 904: window screen
925
- 905: window shade
926
- 906: Windsor tie
927
- 907: wine bottle
928
- 908: wing
929
- 909: wok
930
- 910: wooden spoon
931
- 911: wool
932
- 912: split-rail fence
933
- 913: shipwreck
934
- 914: yawl
935
- 915: yurt
936
- 916: website
937
- 917: comic book
938
- 918: crossword
939
- 919: traffic sign
940
- 920: traffic light
941
- 921: dust jacket
942
- 922: menu
943
- 923: plate
944
- 924: guacamole
945
- 925: consomme
946
- 926: hot pot
947
- 927: trifle
948
- 928: ice cream
949
- 929: ice pop
950
- 930: baguette
951
- 931: bagel
952
- 932: pretzel
953
- 933: cheeseburger
954
- 934: hot dog
955
- 935: mashed potato
956
- 936: cabbage
957
- 937: broccoli
958
- 938: cauliflower
959
- 939: zucchini
960
- 940: spaghetti squash
961
- 941: acorn squash
962
- 942: butternut squash
963
- 943: cucumber
964
- 944: artichoke
965
- 945: bell pepper
966
- 946: cardoon
967
- 947: mushroom
968
- 948: Granny Smith
969
- 949: strawberry
970
- 950: orange
971
- 951: lemon
972
- 952: fig
973
- 953: pineapple
974
- 954: banana
975
- 955: jackfruit
976
- 956: custard apple
977
- 957: pomegranate
978
- 958: hay
979
- 959: carbonara
980
- 960: chocolate syrup
981
- 961: dough
982
- 962: meatloaf
983
- 963: pizza
984
- 964: pot pie
985
- 965: burrito
986
- 966: red wine
987
- 967: espresso
988
- 968: cup
989
- 969: eggnog
990
- 970: alp
991
- 971: bubble
992
- 972: cliff
993
- 973: coral reef
994
- 974: geyser
995
- 975: lakeshore
996
- 976: promontory
997
- 977: shoal
998
- 978: seashore
999
- 979: valley
1000
- 980: volcano
1001
- 981: baseball player
1002
- 982: bridegroom
1003
- 983: scuba diver
1004
- 984: rapeseed
1005
- 985: daisy
1006
- 986: yellow lady's slipper
1007
- 987: corn
1008
- 988: acorn
1009
- 989: rose hip
1010
- 990: horse chestnut seed
1011
- 991: coral fungus
1012
- 992: agaric
1013
- 993: gyromitra
1014
- 994: stinkhorn mushroom
1015
- 995: earth star
1016
- 996: hen-of-the-woods
1017
- 997: bolete
1018
- 998: ear
1019
- 999: toilet paper
1020
-
1021
- # Imagenet class codes to human-readable names
1022
- map:
1023
- n01440764: tench
1024
- n01443537: goldfish
1025
- n01484850: great_white_shark
1026
- n01491361: tiger_shark
1027
- n01494475: hammerhead
1028
- n01496331: electric_ray
1029
- n01498041: stingray
1030
- n01514668: cock
1031
- n01514859: hen
1032
- n01518878: ostrich
1033
- n01530575: brambling
1034
- n01531178: goldfinch
1035
- n01532829: house_finch
1036
- n01534433: junco
1037
- n01537544: indigo_bunting
1038
- n01558993: robin
1039
- n01560419: bulbul
1040
- n01580077: jay
1041
- n01582220: magpie
1042
- n01592084: chickadee
1043
- n01601694: water_ouzel
1044
- n01608432: kite
1045
- n01614925: bald_eagle
1046
- n01616318: vulture
1047
- n01622779: great_grey_owl
1048
- n01629819: European_fire_salamander
1049
- n01630670: common_newt
1050
- n01631663: eft
1051
- n01632458: spotted_salamander
1052
- n01632777: axolotl
1053
- n01641577: bullfrog
1054
- n01644373: tree_frog
1055
- n01644900: tailed_frog
1056
- n01664065: loggerhead
1057
- n01665541: leatherback_turtle
1058
- n01667114: mud_turtle
1059
- n01667778: terrapin
1060
- n01669191: box_turtle
1061
- n01675722: banded_gecko
1062
- n01677366: common_iguana
1063
- n01682714: American_chameleon
1064
- n01685808: whiptail
1065
- n01687978: agama
1066
- n01688243: frilled_lizard
1067
- n01689811: alligator_lizard
1068
- n01692333: Gila_monster
1069
- n01693334: green_lizard
1070
- n01694178: African_chameleon
1071
- n01695060: Komodo_dragon
1072
- n01697457: African_crocodile
1073
- n01698640: American_alligator
1074
- n01704323: triceratops
1075
- n01728572: thunder_snake
1076
- n01728920: ringneck_snake
1077
- n01729322: hognose_snake
1078
- n01729977: green_snake
1079
- n01734418: king_snake
1080
- n01735189: garter_snake
1081
- n01737021: water_snake
1082
- n01739381: vine_snake
1083
- n01740131: night_snake
1084
- n01742172: boa_constrictor
1085
- n01744401: rock_python
1086
- n01748264: Indian_cobra
1087
- n01749939: green_mamba
1088
- n01751748: sea_snake
1089
- n01753488: horned_viper
1090
- n01755581: diamondback
1091
- n01756291: sidewinder
1092
- n01768244: trilobite
1093
- n01770081: harvestman
1094
- n01770393: scorpion
1095
- n01773157: black_and_gold_garden_spider
1096
- n01773549: barn_spider
1097
- n01773797: garden_spider
1098
- n01774384: black_widow
1099
- n01774750: tarantula
1100
- n01775062: wolf_spider
1101
- n01776313: tick
1102
- n01784675: centipede
1103
- n01795545: black_grouse
1104
- n01796340: ptarmigan
1105
- n01797886: ruffed_grouse
1106
- n01798484: prairie_chicken
1107
- n01806143: peacock
1108
- n01806567: quail
1109
- n01807496: partridge
1110
- n01817953: African_grey
1111
- n01818515: macaw
1112
- n01819313: sulphur-crested_cockatoo
1113
- n01820546: lorikeet
1114
- n01824575: coucal
1115
- n01828970: bee_eater
1116
- n01829413: hornbill
1117
- n01833805: hummingbird
1118
- n01843065: jacamar
1119
- n01843383: toucan
1120
- n01847000: drake
1121
- n01855032: red-breasted_merganser
1122
- n01855672: goose
1123
- n01860187: black_swan
1124
- n01871265: tusker
1125
- n01872401: echidna
1126
- n01873310: platypus
1127
- n01877812: wallaby
1128
- n01882714: koala
1129
- n01883070: wombat
1130
- n01910747: jellyfish
1131
- n01914609: sea_anemone
1132
- n01917289: brain_coral
1133
- n01924916: flatworm
1134
- n01930112: nematode
1135
- n01943899: conch
1136
- n01944390: snail
1137
- n01945685: slug
1138
- n01950731: sea_slug
1139
- n01955084: chiton
1140
- n01968897: chambered_nautilus
1141
- n01978287: Dungeness_crab
1142
- n01978455: rock_crab
1143
- n01980166: fiddler_crab
1144
- n01981276: king_crab
1145
- n01983481: American_lobster
1146
- n01984695: spiny_lobster
1147
- n01985128: crayfish
1148
- n01986214: hermit_crab
1149
- n01990800: isopod
1150
- n02002556: white_stork
1151
- n02002724: black_stork
1152
- n02006656: spoonbill
1153
- n02007558: flamingo
1154
- n02009229: little_blue_heron
1155
- n02009912: American_egret
1156
- n02011460: bittern
1157
- n02012849: crane_(bird)
1158
- n02013706: limpkin
1159
- n02017213: European_gallinule
1160
- n02018207: American_coot
1161
- n02018795: bustard
1162
- n02025239: ruddy_turnstone
1163
- n02027492: red-backed_sandpiper
1164
- n02028035: redshank
1165
- n02033041: dowitcher
1166
- n02037110: oystercatcher
1167
- n02051845: pelican
1168
- n02056570: king_penguin
1169
- n02058221: albatross
1170
- n02066245: grey_whale
1171
- n02071294: killer_whale
1172
- n02074367: dugong
1173
- n02077923: sea_lion
1174
- n02085620: Chihuahua
1175
- n02085782: Japanese_spaniel
1176
- n02085936: Maltese_dog
1177
- n02086079: Pekinese
1178
- n02086240: Shih-Tzu
1179
- n02086646: Blenheim_spaniel
1180
- n02086910: papillon
1181
- n02087046: toy_terrier
1182
- n02087394: Rhodesian_ridgeback
1183
- n02088094: Afghan_hound
1184
- n02088238: basset
1185
- n02088364: beagle
1186
- n02088466: bloodhound
1187
- n02088632: bluetick
1188
- n02089078: black-and-tan_coonhound
1189
- n02089867: Walker_hound
1190
- n02089973: English_foxhound
1191
- n02090379: redbone
1192
- n02090622: borzoi
1193
- n02090721: Irish_wolfhound
1194
- n02091032: Italian_greyhound
1195
- n02091134: whippet
1196
- n02091244: Ibizan_hound
1197
- n02091467: Norwegian_elkhound
1198
- n02091635: otterhound
1199
- n02091831: Saluki
1200
- n02092002: Scottish_deerhound
1201
- n02092339: Weimaraner
1202
- n02093256: Staffordshire_bullterrier
1203
- n02093428: American_Staffordshire_terrier
1204
- n02093647: Bedlington_terrier
1205
- n02093754: Border_terrier
1206
- n02093859: Kerry_blue_terrier
1207
- n02093991: Irish_terrier
1208
- n02094114: Norfolk_terrier
1209
- n02094258: Norwich_terrier
1210
- n02094433: Yorkshire_terrier
1211
- n02095314: wire-haired_fox_terrier
1212
- n02095570: Lakeland_terrier
1213
- n02095889: Sealyham_terrier
1214
- n02096051: Airedale
1215
- n02096177: cairn
1216
- n02096294: Australian_terrier
1217
- n02096437: Dandie_Dinmont
1218
- n02096585: Boston_bull
1219
- n02097047: miniature_schnauzer
1220
- n02097130: giant_schnauzer
1221
- n02097209: standard_schnauzer
1222
- n02097298: Scotch_terrier
1223
- n02097474: Tibetan_terrier
1224
- n02097658: silky_terrier
1225
- n02098105: soft-coated_wheaten_terrier
1226
- n02098286: West_Highland_white_terrier
1227
- n02098413: Lhasa
1228
- n02099267: flat-coated_retriever
1229
- n02099429: curly-coated_retriever
1230
- n02099601: golden_retriever
1231
- n02099712: Labrador_retriever
1232
- n02099849: Chesapeake_Bay_retriever
1233
- n02100236: German_short-haired_pointer
1234
- n02100583: vizsla
1235
- n02100735: English_setter
1236
- n02100877: Irish_setter
1237
- n02101006: Gordon_setter
1238
- n02101388: Brittany_spaniel
1239
- n02101556: clumber
1240
- n02102040: English_springer
1241
- n02102177: Welsh_springer_spaniel
1242
- n02102318: cocker_spaniel
1243
- n02102480: Sussex_spaniel
1244
- n02102973: Irish_water_spaniel
1245
- n02104029: kuvasz
1246
- n02104365: schipperke
1247
- n02105056: groenendael
1248
- n02105162: malinois
1249
- n02105251: briard
1250
- n02105412: kelpie
1251
- n02105505: komondor
1252
- n02105641: Old_English_sheepdog
1253
- n02105855: Shetland_sheepdog
1254
- n02106030: collie
1255
- n02106166: Border_collie
1256
- n02106382: Bouvier_des_Flandres
1257
- n02106550: Rottweiler
1258
- n02106662: German_shepherd
1259
- n02107142: Doberman
1260
- n02107312: miniature_pinscher
1261
- n02107574: Greater_Swiss_Mountain_dog
1262
- n02107683: Bernese_mountain_dog
1263
- n02107908: Appenzeller
1264
- n02108000: EntleBucher
1265
- n02108089: boxer
1266
- n02108422: bull_mastiff
1267
- n02108551: Tibetan_mastiff
1268
- n02108915: French_bulldog
1269
- n02109047: Great_Dane
1270
- n02109525: Saint_Bernard
1271
- n02109961: Eskimo_dog
1272
- n02110063: malamute
1273
- n02110185: Siberian_husky
1274
- n02110341: dalmatian
1275
- n02110627: affenpinscher
1276
- n02110806: basenji
1277
- n02110958: pug
1278
- n02111129: Leonberg
1279
- n02111277: Newfoundland
1280
- n02111500: Great_Pyrenees
1281
- n02111889: Samoyed
1282
- n02112018: Pomeranian
1283
- n02112137: chow
1284
- n02112350: keeshond
1285
- n02112706: Brabancon_griffon
1286
- n02113023: Pembroke
1287
- n02113186: Cardigan
1288
- n02113624: toy_poodle
1289
- n02113712: miniature_poodle
1290
- n02113799: standard_poodle
1291
- n02113978: Mexican_hairless
1292
- n02114367: timber_wolf
1293
- n02114548: white_wolf
1294
- n02114712: red_wolf
1295
- n02114855: coyote
1296
- n02115641: dingo
1297
- n02115913: dhole
1298
- n02116738: African_hunting_dog
1299
- n02117135: hyena
1300
- n02119022: red_fox
1301
- n02119789: kit_fox
1302
- n02120079: Arctic_fox
1303
- n02120505: grey_fox
1304
- n02123045: tabby
1305
- n02123159: tiger_cat
1306
- n02123394: Persian_cat
1307
- n02123597: Siamese_cat
1308
- n02124075: Egyptian_cat
1309
- n02125311: cougar
1310
- n02127052: lynx
1311
- n02128385: leopard
1312
- n02128757: snow_leopard
1313
- n02128925: jaguar
1314
- n02129165: lion
1315
- n02129604: tiger
1316
- n02130308: cheetah
1317
- n02132136: brown_bear
1318
- n02133161: American_black_bear
1319
- n02134084: ice_bear
1320
- n02134418: sloth_bear
1321
- n02137549: mongoose
1322
- n02138441: meerkat
1323
- n02165105: tiger_beetle
1324
- n02165456: ladybug
1325
- n02167151: ground_beetle
1326
- n02168699: long-horned_beetle
1327
- n02169497: leaf_beetle
1328
- n02172182: dung_beetle
1329
- n02174001: rhinoceros_beetle
1330
- n02177972: weevil
1331
- n02190166: fly
1332
- n02206856: bee
1333
- n02219486: ant
1334
- n02226429: grasshopper
1335
- n02229544: cricket
1336
- n02231487: walking_stick
1337
- n02233338: cockroach
1338
- n02236044: mantis
1339
- n02256656: cicada
1340
- n02259212: leafhopper
1341
- n02264363: lacewing
1342
- n02268443: dragonfly
1343
- n02268853: damselfly
1344
- n02276258: admiral
1345
- n02277742: ringlet
1346
- n02279972: monarch
1347
- n02280649: cabbage_butterfly
1348
- n02281406: sulphur_butterfly
1349
- n02281787: lycaenid
1350
- n02317335: starfish
1351
- n02319095: sea_urchin
1352
- n02321529: sea_cucumber
1353
- n02325366: wood_rabbit
1354
- n02326432: hare
1355
- n02328150: Angora
1356
- n02342885: hamster
1357
- n02346627: porcupine
1358
- n02356798: fox_squirrel
1359
- n02361337: marmot
1360
- n02363005: beaver
1361
- n02364673: guinea_pig
1362
- n02389026: sorrel
1363
- n02391049: zebra
1364
- n02395406: hog
1365
- n02396427: wild_boar
1366
- n02397096: warthog
1367
- n02398521: hippopotamus
1368
- n02403003: ox
1369
- n02408429: water_buffalo
1370
- n02410509: bison
1371
- n02412080: ram
1372
- n02415577: bighorn
1373
- n02417914: ibex
1374
- n02422106: hartebeest
1375
- n02422699: impala
1376
- n02423022: gazelle
1377
- n02437312: Arabian_camel
1378
- n02437616: llama
1379
- n02441942: weasel
1380
- n02442845: mink
1381
- n02443114: polecat
1382
- n02443484: black-footed_ferret
1383
- n02444819: otter
1384
- n02445715: skunk
1385
- n02447366: badger
1386
- n02454379: armadillo
1387
- n02457408: three-toed_sloth
1388
- n02480495: orangutan
1389
- n02480855: gorilla
1390
- n02481823: chimpanzee
1391
- n02483362: gibbon
1392
- n02483708: siamang
1393
- n02484975: guenon
1394
- n02486261: patas
1395
- n02486410: baboon
1396
- n02487347: macaque
1397
- n02488291: langur
1398
- n02488702: colobus
1399
- n02489166: proboscis_monkey
1400
- n02490219: marmoset
1401
- n02492035: capuchin
1402
- n02492660: howler_monkey
1403
- n02493509: titi
1404
- n02493793: spider_monkey
1405
- n02494079: squirrel_monkey
1406
- n02497673: Madagascar_cat
1407
- n02500267: indri
1408
- n02504013: Indian_elephant
1409
- n02504458: African_elephant
1410
- n02509815: lesser_panda
1411
- n02510455: giant_panda
1412
- n02514041: barracouta
1413
- n02526121: eel
1414
- n02536864: coho
1415
- n02606052: rock_beauty
1416
- n02607072: anemone_fish
1417
- n02640242: sturgeon
1418
- n02641379: gar
1419
- n02643566: lionfish
1420
- n02655020: puffer
1421
- n02666196: abacus
1422
- n02667093: abaya
1423
- n02669723: academic_gown
1424
- n02672831: accordion
1425
- n02676566: acoustic_guitar
1426
- n02687172: aircraft_carrier
1427
- n02690373: airliner
1428
- n02692877: airship
1429
- n02699494: altar
1430
- n02701002: ambulance
1431
- n02704792: amphibian
1432
- n02708093: analog_clock
1433
- n02727426: apiary
1434
- n02730930: apron
1435
- n02747177: ashcan
1436
- n02749479: assault_rifle
1437
- n02769748: backpack
1438
- n02776631: bakery
1439
- n02777292: balance_beam
1440
- n02782093: balloon
1441
- n02783161: ballpoint
1442
- n02786058: Band_Aid
1443
- n02787622: banjo
1444
- n02788148: bannister
1445
- n02790996: barbell
1446
- n02791124: barber_chair
1447
- n02791270: barbershop
1448
- n02793495: barn
1449
- n02794156: barometer
1450
- n02795169: barrel
1451
- n02797295: barrow
1452
- n02799071: baseball
1453
- n02802426: basketball
1454
- n02804414: bassinet
1455
- n02804610: bassoon
1456
- n02807133: bathing_cap
1457
- n02808304: bath_towel
1458
- n02808440: bathtub
1459
- n02814533: beach_wagon
1460
- n02814860: beacon
1461
- n02815834: beaker
1462
- n02817516: bearskin
1463
- n02823428: beer_bottle
1464
- n02823750: beer_glass
1465
- n02825657: bell_cote
1466
- n02834397: bib
1467
- n02835271: bicycle-built-for-two
1468
- n02837789: bikini
1469
- n02840245: binder
1470
- n02841315: binoculars
1471
- n02843684: birdhouse
1472
- n02859443: boathouse
1473
- n02860847: bobsled
1474
- n02865351: bolo_tie
1475
- n02869837: bonnet
1476
- n02870880: bookcase
1477
- n02871525: bookshop
1478
- n02877765: bottlecap
1479
- n02879718: bow
1480
- n02883205: bow_tie
1481
- n02892201: brass
1482
- n02892767: brassiere
1483
- n02894605: breakwater
1484
- n02895154: breastplate
1485
- n02906734: broom
1486
- n02909870: bucket
1487
- n02910353: buckle
1488
- n02916936: bulletproof_vest
1489
- n02917067: bullet_train
1490
- n02927161: butcher_shop
1491
- n02930766: cab
1492
- n02939185: caldron
1493
- n02948072: candle
1494
- n02950826: cannon
1495
- n02951358: canoe
1496
- n02951585: can_opener
1497
- n02963159: cardigan
1498
- n02965783: car_mirror
1499
- n02966193: carousel
1500
- n02966687: carpenter's_kit
1501
- n02971356: carton
1502
- n02974003: car_wheel
1503
- n02977058: cash_machine
1504
- n02978881: cassette
1505
- n02979186: cassette_player
1506
- n02980441: castle
1507
- n02981792: catamaran
1508
- n02988304: CD_player
1509
- n02992211: cello
1510
- n02992529: cellular_telephone
1511
- n02999410: chain
1512
- n03000134: chainlink_fence
1513
- n03000247: chain_mail
1514
- n03000684: chain_saw
1515
- n03014705: chest
1516
- n03016953: chiffonier
1517
- n03017168: chime
1518
- n03018349: china_cabinet
1519
- n03026506: Christmas_stocking
1520
- n03028079: church
1521
- n03032252: cinema
1522
- n03041632: cleaver
1523
- n03042490: cliff_dwelling
1524
- n03045698: cloak
1525
- n03047690: clog
1526
- n03062245: cocktail_shaker
1527
- n03063599: coffee_mug
1528
- n03063689: coffeepot
1529
- n03065424: coil
1530
- n03075370: combination_lock
1531
- n03085013: computer_keyboard
1532
- n03089624: confectionery
1533
- n03095699: container_ship
1534
- n03100240: convertible
1535
- n03109150: corkscrew
1536
- n03110669: cornet
1537
- n03124043: cowboy_boot
1538
- n03124170: cowboy_hat
1539
- n03125729: cradle
1540
- n03126707: crane_(machine)
1541
- n03127747: crash_helmet
1542
- n03127925: crate
1543
- n03131574: crib
1544
- n03133878: Crock_Pot
1545
- n03134739: croquet_ball
1546
- n03141823: crutch
1547
- n03146219: cuirass
1548
- n03160309: dam
1549
- n03179701: desk
1550
- n03180011: desktop_computer
1551
- n03187595: dial_telephone
1552
- n03188531: diaper
1553
- n03196217: digital_clock
1554
- n03197337: digital_watch
1555
- n03201208: dining_table
1556
- n03207743: dishrag
1557
- n03207941: dishwasher
1558
- n03208938: disk_brake
1559
- n03216828: dock
1560
- n03218198: dogsled
1561
- n03220513: dome
1562
- n03223299: doormat
1563
- n03240683: drilling_platform
1564
- n03249569: drum
1565
- n03250847: drumstick
1566
- n03255030: dumbbell
1567
- n03259280: Dutch_oven
1568
- n03271574: electric_fan
1569
- n03272010: electric_guitar
1570
- n03272562: electric_locomotive
1571
- n03290653: entertainment_center
1572
- n03291819: envelope
1573
- n03297495: espresso_maker
1574
- n03314780: face_powder
1575
- n03325584: feather_boa
1576
- n03337140: file
1577
- n03344393: fireboat
1578
- n03345487: fire_engine
1579
- n03347037: fire_screen
1580
- n03355925: flagpole
1581
- n03372029: flute
1582
- n03376595: folding_chair
1583
- n03379051: football_helmet
1584
- n03384352: forklift
1585
- n03388043: fountain
1586
- n03388183: fountain_pen
1587
- n03388549: four-poster
1588
- n03393912: freight_car
1589
- n03394916: French_horn
1590
- n03400231: frying_pan
1591
- n03404251: fur_coat
1592
- n03417042: garbage_truck
1593
- n03424325: gasmask
1594
- n03425413: gas_pump
1595
- n03443371: goblet
1596
- n03444034: go-kart
1597
- n03445777: golf_ball
1598
- n03445924: golfcart
1599
- n03447447: gondola
1600
- n03447721: gong
1601
- n03450230: gown
1602
- n03452741: grand_piano
1603
- n03457902: greenhouse
1604
- n03459775: grille
1605
- n03461385: grocery_store
1606
- n03467068: guillotine
1607
- n03476684: hair_slide
1608
- n03476991: hair_spray
1609
- n03478589: half_track
1610
- n03481172: hammer
1611
- n03482405: hamper
1612
- n03483316: hand_blower
1613
- n03485407: hand-held_computer
1614
- n03485794: handkerchief
1615
- n03492542: hard_disc
1616
- n03494278: harmonica
1617
- n03495258: harp
1618
- n03496892: harvester
1619
- n03498962: hatchet
1620
- n03527444: holster
1621
- n03529860: home_theater
1622
- n03530642: honeycomb
1623
- n03532672: hook
1624
- n03534580: hoopskirt
1625
- n03535780: horizontal_bar
1626
- n03538406: horse_cart
1627
- n03544143: hourglass
1628
- n03584254: iPod
1629
- n03584829: iron
1630
- n03590841: jack-o'-lantern
1631
- n03594734: jean
1632
- n03594945: jeep
1633
- n03595614: jersey
1634
- n03598930: jigsaw_puzzle
1635
- n03599486: jinrikisha
1636
- n03602883: joystick
1637
- n03617480: kimono
1638
- n03623198: knee_pad
1639
- n03627232: knot
1640
- n03630383: lab_coat
1641
- n03633091: ladle
1642
- n03637318: lampshade
1643
- n03642806: laptop
1644
- n03649909: lawn_mower
1645
- n03657121: lens_cap
1646
- n03658185: letter_opener
1647
- n03661043: library
1648
- n03662601: lifeboat
1649
- n03666591: lighter
1650
- n03670208: limousine
1651
- n03673027: liner
1652
- n03676483: lipstick
1653
- n03680355: Loafer
1654
- n03690938: lotion
1655
- n03691459: loudspeaker
1656
- n03692522: loupe
1657
- n03697007: lumbermill
1658
- n03706229: magnetic_compass
1659
- n03709823: mailbag
1660
- n03710193: mailbox
1661
- n03710637: maillot_(tights)
1662
- n03710721: maillot_(tank_suit)
1663
- n03717622: manhole_cover
1664
- n03720891: maraca
1665
- n03721384: marimba
1666
- n03724870: mask
1667
- n03729826: matchstick
1668
- n03733131: maypole
1669
- n03733281: maze
1670
- n03733805: measuring_cup
1671
- n03742115: medicine_chest
1672
- n03743016: megalith
1673
- n03759954: microphone
1674
- n03761084: microwave
1675
- n03763968: military_uniform
1676
- n03764736: milk_can
1677
- n03769881: minibus
1678
- n03770439: miniskirt
1679
- n03770679: minivan
1680
- n03773504: missile
1681
- n03775071: mitten
1682
- n03775546: mixing_bowl
1683
- n03776460: mobile_home
1684
- n03777568: Model_T
1685
- n03777754: modem
1686
- n03781244: monastery
1687
- n03782006: monitor
1688
- n03785016: moped
1689
- n03786901: mortar
1690
- n03787032: mortarboard
1691
- n03788195: mosque
1692
- n03788365: mosquito_net
1693
- n03791053: motor_scooter
1694
- n03792782: mountain_bike
1695
- n03792972: mountain_tent
1696
- n03793489: mouse
1697
- n03794056: mousetrap
1698
- n03796401: moving_van
1699
- n03803284: muzzle
1700
- n03804744: nail
1701
- n03814639: neck_brace
1702
- n03814906: necklace
1703
- n03825788: nipple
1704
- n03832673: notebook
1705
- n03837869: obelisk
1706
- n03838899: oboe
1707
- n03840681: ocarina
1708
- n03841143: odometer
1709
- n03843555: oil_filter
1710
- n03854065: organ
1711
- n03857828: oscilloscope
1712
- n03866082: overskirt
1713
- n03868242: oxcart
1714
- n03868863: oxygen_mask
1715
- n03871628: packet
1716
- n03873416: paddle
1717
- n03874293: paddlewheel
1718
- n03874599: padlock
1719
- n03876231: paintbrush
1720
- n03877472: pajama
1721
- n03877845: palace
1722
- n03884397: panpipe
1723
- n03887697: paper_towel
1724
- n03888257: parachute
1725
- n03888605: parallel_bars
1726
- n03891251: park_bench
1727
- n03891332: parking_meter
1728
- n03895866: passenger_car
1729
- n03899768: patio
1730
- n03902125: pay-phone
1731
- n03903868: pedestal
1732
- n03908618: pencil_box
1733
- n03908714: pencil_sharpener
1734
- n03916031: perfume
1735
- n03920288: Petri_dish
1736
- n03924679: photocopier
1737
- n03929660: pick
1738
- n03929855: pickelhaube
1739
- n03930313: picket_fence
1740
- n03930630: pickup
1741
- n03933933: pier
1742
- n03935335: piggy_bank
1743
- n03937543: pill_bottle
1744
- n03938244: pillow
1745
- n03942813: ping-pong_ball
1746
- n03944341: pinwheel
1747
- n03947888: pirate
1748
- n03950228: pitcher
1749
- n03954731: plane
1750
- n03956157: planetarium
1751
- n03958227: plastic_bag
1752
- n03961711: plate_rack
1753
- n03967562: plow
1754
- n03970156: plunger
1755
- n03976467: Polaroid_camera
1756
- n03976657: pole
1757
- n03977966: police_van
1758
- n03980874: poncho
1759
- n03982430: pool_table
1760
- n03983396: pop_bottle
1761
- n03991062: pot
1762
- n03992509: potter's_wheel
1763
- n03995372: power_drill
1764
- n03998194: prayer_rug
1765
- n04004767: printer
1766
- n04005630: prison
1767
- n04008634: projectile
1768
- n04009552: projector
1769
- n04019541: puck
1770
- n04023962: punching_bag
1771
- n04026417: purse
1772
- n04033901: quill
1773
- n04033995: quilt
1774
- n04037443: racer
1775
- n04039381: racket
1776
- n04040759: radiator
1777
- n04041544: radio
1778
- n04044716: radio_telescope
1779
- n04049303: rain_barrel
1780
- n04065272: recreational_vehicle
1781
- n04067472: reel
1782
- n04069434: reflex_camera
1783
- n04070727: refrigerator
1784
- n04074963: remote_control
1785
- n04081281: restaurant
1786
- n04086273: revolver
1787
- n04090263: rifle
1788
- n04099969: rocking_chair
1789
- n04111531: rotisserie
1790
- n04116512: rubber_eraser
1791
- n04118538: rugby_ball
1792
- n04118776: rule
1793
- n04120489: running_shoe
1794
- n04125021: safe
1795
- n04127249: safety_pin
1796
- n04131690: saltshaker
1797
- n04133789: sandal
1798
- n04136333: sarong
1799
- n04141076: sax
1800
- n04141327: scabbard
1801
- n04141975: scale
1802
- n04146614: school_bus
1803
- n04147183: schooner
1804
- n04149813: scoreboard
1805
- n04152593: screen
1806
- n04153751: screw
1807
- n04154565: screwdriver
1808
- n04162706: seat_belt
1809
- n04179913: sewing_machine
1810
- n04192698: shield
1811
- n04200800: shoe_shop
1812
- n04201297: shoji
1813
- n04204238: shopping_basket
1814
- n04204347: shopping_cart
1815
- n04208210: shovel
1816
- n04209133: shower_cap
1817
- n04209239: shower_curtain
1818
- n04228054: ski
1819
- n04229816: ski_mask
1820
- n04235860: sleeping_bag
1821
- n04238763: slide_rule
1822
- n04239074: sliding_door
1823
- n04243546: slot
1824
- n04251144: snorkel
1825
- n04252077: snowmobile
1826
- n04252225: snowplow
1827
- n04254120: soap_dispenser
1828
- n04254680: soccer_ball
1829
- n04254777: sock
1830
- n04258138: solar_dish
1831
- n04259630: sombrero
1832
- n04263257: soup_bowl
1833
- n04264628: space_bar
1834
- n04265275: space_heater
1835
- n04266014: space_shuttle
1836
- n04270147: spatula
1837
- n04273569: speedboat
1838
- n04275548: spider_web
1839
- n04277352: spindle
1840
- n04285008: sports_car
1841
- n04286575: spotlight
1842
- n04296562: stage
1843
- n04310018: steam_locomotive
1844
- n04311004: steel_arch_bridge
1845
- n04311174: steel_drum
1846
- n04317175: stethoscope
1847
- n04325704: stole
1848
- n04326547: stone_wall
1849
- n04328186: stopwatch
1850
- n04330267: stove
1851
- n04332243: strainer
1852
- n04335435: streetcar
1853
- n04336792: stretcher
1854
- n04344873: studio_couch
1855
- n04346328: stupa
1856
- n04347754: submarine
1857
- n04350905: suit
1858
- n04355338: sundial
1859
- n04355933: sunglass
1860
- n04356056: sunglasses
1861
- n04357314: sunscreen
1862
- n04366367: suspension_bridge
1863
- n04367480: swab
1864
- n04370456: sweatshirt
1865
- n04371430: swimming_trunks
1866
- n04371774: swing
1867
- n04372370: switch
1868
- n04376876: syringe
1869
- n04380533: table_lamp
1870
- n04389033: tank
1871
- n04392985: tape_player
1872
- n04398044: teapot
1873
- n04399382: teddy
1874
- n04404412: television
1875
- n04409515: tennis_ball
1876
- n04417672: thatch
1877
- n04418357: theater_curtain
1878
- n04423845: thimble
1879
- n04428191: thresher
1880
- n04429376: throne
1881
- n04435653: tile_roof
1882
- n04442312: toaster
1883
- n04443257: tobacco_shop
1884
- n04447861: toilet_seat
1885
- n04456115: torch
1886
- n04458633: totem_pole
1887
- n04461696: tow_truck
1888
- n04462240: toyshop
1889
- n04465501: tractor
1890
- n04467665: trailer_truck
1891
- n04476259: tray
1892
- n04479046: trench_coat
1893
- n04482393: tricycle
1894
- n04483307: trimaran
1895
- n04485082: tripod
1896
- n04486054: triumphal_arch
1897
- n04487081: trolleybus
1898
- n04487394: trombone
1899
- n04493381: tub
1900
- n04501370: turnstile
1901
- n04505470: typewriter_keyboard
1902
- n04507155: umbrella
1903
- n04509417: unicycle
1904
- n04515003: upright
1905
- n04517823: vacuum
1906
- n04522168: vase
1907
- n04523525: vault
1908
- n04525038: velvet
1909
- n04525305: vending_machine
1910
- n04532106: vestment
1911
- n04532670: viaduct
1912
- n04536866: violin
1913
- n04540053: volleyball
1914
- n04542943: waffle_iron
1915
- n04548280: wall_clock
1916
- n04548362: wallet
1917
- n04550184: wardrobe
1918
- n04552348: warplane
1919
- n04553703: washbasin
1920
- n04554684: washer
1921
- n04557648: water_bottle
1922
- n04560804: water_jug
1923
- n04562935: water_tower
1924
- n04579145: whiskey_jug
1925
- n04579432: whistle
1926
- n04584207: wig
1927
- n04589890: window_screen
1928
- n04590129: window_shade
1929
- n04591157: Windsor_tie
1930
- n04591713: wine_bottle
1931
- n04592741: wing
1932
- n04596742: wok
1933
- n04597913: wooden_spoon
1934
- n04599235: wool
1935
- n04604644: worm_fence
1936
- n04606251: wreck
1937
- n04612504: yawl
1938
- n04613696: yurt
1939
- n06359193: web_site
1940
- n06596364: comic_book
1941
- n06785654: crossword_puzzle
1942
- n06794110: street_sign
1943
- n06874185: traffic_light
1944
- n07248320: book_jacket
1945
- n07565083: menu
1946
- n07579787: plate
1947
- n07583066: guacamole
1948
- n07584110: consomme
1949
- n07590611: hot_pot
1950
- n07613480: trifle
1951
- n07614500: ice_cream
1952
- n07615774: ice_lolly
1953
- n07684084: French_loaf
1954
- n07693725: bagel
1955
- n07695742: pretzel
1956
- n07697313: cheeseburger
1957
- n07697537: hotdog
1958
- n07711569: mashed_potato
1959
- n07714571: head_cabbage
1960
- n07714990: broccoli
1961
- n07715103: cauliflower
1962
- n07716358: zucchini
1963
- n07716906: spaghetti_squash
1964
- n07717410: acorn_squash
1965
- n07717556: butternut_squash
1966
- n07718472: cucumber
1967
- n07718747: artichoke
1968
- n07720875: bell_pepper
1969
- n07730033: cardoon
1970
- n07734744: mushroom
1971
- n07742313: Granny_Smith
1972
- n07745940: strawberry
1973
- n07747607: orange
1974
- n07749582: lemon
1975
- n07753113: fig
1976
- n07753275: pineapple
1977
- n07753592: banana
1978
- n07754684: jackfruit
1979
- n07760859: custard_apple
1980
- n07768694: pomegranate
1981
- n07802026: hay
1982
- n07831146: carbonara
1983
- n07836838: chocolate_sauce
1984
- n07860988: dough
1985
- n07871810: meat_loaf
1986
- n07873807: pizza
1987
- n07875152: potpie
1988
- n07880968: burrito
1989
- n07892512: red_wine
1990
- n07920052: espresso
1991
- n07930864: cup
1992
- n07932039: eggnog
1993
- n09193705: alp
1994
- n09229709: bubble
1995
- n09246464: cliff
1996
- n09256479: coral_reef
1997
- n09288635: geyser
1998
- n09332890: lakeside
1999
- n09399592: promontory
2000
- n09421951: sandbar
2001
- n09428293: seashore
2002
- n09468604: valley
2003
- n09472597: volcano
2004
- n09835506: ballplayer
2005
- n10148035: groom
2006
- n10565667: scuba_diver
2007
- n11879895: rapeseed
2008
- n11939491: daisy
2009
- n12057211: yellow_lady's_slipper
2010
- n12144580: corn
2011
- n12267677: acorn
2012
- n12620546: hip
2013
- n12768682: buckeye
2014
- n12985857: coral_fungus
2015
- n12998815: agaric
2016
- n13037406: gyromitra
2017
- n13040303: stinkhorn
2018
- n13044778: earthstar
2019
- n13052670: hen-of-the-woods
2020
- n13054560: bolete
2021
- n13133613: ear
2022
- n15075141: toilet_tissue
2023
-
2024
- # Download script/URL (optional)
2025
- download: ultralytics/data/scripts/get_imagenet.sh
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
vendor/ultralytics/cfg/datasets/Objects365.yaml DELETED
@@ -1,447 +0,0 @@
1
- # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
-
3
- # Objects365 dataset https://www.objects365.org/ by Megvii
4
- # Documentation: https://docs.ultralytics.com/datasets/detect/objects365/
5
- # Example usage: yolo train data=Objects365.yaml
6
- # parent
7
- # ├── ultralytics
8
- # └── datasets
9
- # └── Objects365 ← downloads here (712 GB = 367G data + 345G zips)
10
-
11
- # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
12
- path: Objects365 # dataset root dir
13
- train: images/train # train images (relative to 'path') 1742289 images
14
- val: images/val # val images (relative to 'path') 80000 images
15
- test: # test images (optional)
16
-
17
- # Classes
18
- names:
19
- 0: Person
20
- 1: Sneakers
21
- 2: Chair
22
- 3: Other Shoes
23
- 4: Hat
24
- 5: Car
25
- 6: Lamp
26
- 7: Glasses
27
- 8: Bottle
28
- 9: Desk
29
- 10: Cup
30
- 11: Street Lights
31
- 12: Cabinet/shelf
32
- 13: Handbag/Satchel
33
- 14: Bracelet
34
- 15: Plate
35
- 16: Picture/Frame
36
- 17: Helmet
37
- 18: Book
38
- 19: Gloves
39
- 20: Storage box
40
- 21: Boat
41
- 22: Leather Shoes
42
- 23: Flower
43
- 24: Bench
44
- 25: Potted Plant
45
- 26: Bowl/Basin
46
- 27: Flag
47
- 28: Pillow
48
- 29: Boots
49
- 30: Vase
50
- 31: Microphone
51
- 32: Necklace
52
- 33: Ring
53
- 34: SUV
54
- 35: Wine Glass
55
- 36: Belt
56
- 37: Monitor/TV
57
- 38: Backpack
58
- 39: Umbrella
59
- 40: Traffic Light
60
- 41: Speaker
61
- 42: Watch
62
- 43: Tie
63
- 44: Trash bin Can
64
- 45: Slippers
65
- 46: Bicycle
66
- 47: Stool
67
- 48: Barrel/bucket
68
- 49: Van
69
- 50: Couch
70
- 51: Sandals
71
- 52: Basket
72
- 53: Drum
73
- 54: Pen/Pencil
74
- 55: Bus
75
- 56: Wild Bird
76
- 57: High Heels
77
- 58: Motorcycle
78
- 59: Guitar
79
- 60: Carpet
80
- 61: Cell Phone
81
- 62: Bread
82
- 63: Camera
83
- 64: Canned
84
- 65: Truck
85
- 66: Traffic cone
86
- 67: Cymbal
87
- 68: Lifesaver
88
- 69: Towel
89
- 70: Stuffed Toy
90
- 71: Candle
91
- 72: Sailboat
92
- 73: Laptop
93
- 74: Awning
94
- 75: Bed
95
- 76: Faucet
96
- 77: Tent
97
- 78: Horse
98
- 79: Mirror
99
- 80: Power outlet
100
- 81: Sink
101
- 82: Apple
102
- 83: Air Conditioner
103
- 84: Knife
104
- 85: Hockey Stick
105
- 86: Paddle
106
- 87: Pickup Truck
107
- 88: Fork
108
- 89: Traffic Sign
109
- 90: Balloon
110
- 91: Tripod
111
- 92: Dog
112
- 93: Spoon
113
- 94: Clock
114
- 95: Pot
115
- 96: Cow
116
- 97: Cake
117
- 98: Dining Table
118
- 99: Sheep
119
- 100: Hanger
120
- 101: Blackboard/Whiteboard
121
- 102: Napkin
122
- 103: Other Fish
123
- 104: Orange/Tangerine
124
- 105: Toiletry
125
- 106: Keyboard
126
- 107: Tomato
127
- 108: Lantern
128
- 109: Machinery Vehicle
129
- 110: Fan
130
- 111: Green Vegetables
131
- 112: Banana
132
- 113: Baseball Glove
133
- 114: Airplane
134
- 115: Mouse
135
- 116: Train
136
- 117: Pumpkin
137
- 118: Soccer
138
- 119: Skiboard
139
- 120: Luggage
140
- 121: Nightstand
141
- 122: Tea pot
142
- 123: Telephone
143
- 124: Trolley
144
- 125: Head Phone
145
- 126: Sports Car
146
- 127: Stop Sign
147
- 128: Dessert
148
- 129: Scooter
149
- 130: Stroller
150
- 131: Crane
151
- 132: Remote
152
- 133: Refrigerator
153
- 134: Oven
154
- 135: Lemon
155
- 136: Duck
156
- 137: Baseball Bat
157
- 138: Surveillance Camera
158
- 139: Cat
159
- 140: Jug
160
- 141: Broccoli
161
- 142: Piano
162
- 143: Pizza
163
- 144: Elephant
164
- 145: Skateboard
165
- 146: Surfboard
166
- 147: Gun
167
- 148: Skating and Skiing shoes
168
- 149: Gas stove
169
- 150: Donut
170
- 151: Bow Tie
171
- 152: Carrot
172
- 153: Toilet
173
- 154: Kite
174
- 155: Strawberry
175
- 156: Other Balls
176
- 157: Shovel
177
- 158: Pepper
178
- 159: Computer Box
179
- 160: Toilet Paper
180
- 161: Cleaning Products
181
- 162: Chopsticks
182
- 163: Microwave
183
- 164: Pigeon
184
- 165: Baseball
185
- 166: Cutting/chopping Board
186
- 167: Coffee Table
187
- 168: Side Table
188
- 169: Scissors
189
- 170: Marker
190
- 171: Pie
191
- 172: Ladder
192
- 173: Snowboard
193
- 174: Cookies
194
- 175: Radiator
195
- 176: Fire Hydrant
196
- 177: Basketball
197
- 178: Zebra
198
- 179: Grape
199
- 180: Giraffe
200
- 181: Potato
201
- 182: Sausage
202
- 183: Tricycle
203
- 184: Violin
204
- 185: Egg
205
- 186: Fire Extinguisher
206
- 187: Candy
207
- 188: Fire Truck
208
- 189: Billiards
209
- 190: Converter
210
- 191: Bathtub
211
- 192: Wheelchair
212
- 193: Golf Club
213
- 194: Briefcase
214
- 195: Cucumber
215
- 196: Cigar/Cigarette
216
- 197: Paint Brush
217
- 198: Pear
218
- 199: Heavy Truck
219
- 200: Hamburger
220
- 201: Extractor
221
- 202: Extension Cord
222
- 203: Tong
223
- 204: Tennis Racket
224
- 205: Folder
225
- 206: American Football
226
- 207: earphone
227
- 208: Mask
228
- 209: Kettle
229
- 210: Tennis
230
- 211: Ship
231
- 212: Swing
232
- 213: Coffee Machine
233
- 214: Slide
234
- 215: Carriage
235
- 216: Onion
236
- 217: Green beans
237
- 218: Projector
238
- 219: Frisbee
239
- 220: Washing Machine/Drying Machine
240
- 221: Chicken
241
- 222: Printer
242
- 223: Watermelon
243
- 224: Saxophone
244
- 225: Tissue
245
- 226: Toothbrush
246
- 227: Ice cream
247
- 228: Hot-air balloon
248
- 229: Cello
249
- 230: French Fries
250
- 231: Scale
251
- 232: Trophy
252
- 233: Cabbage
253
- 234: Hot dog
254
- 235: Blender
255
- 236: Peach
256
- 237: Rice
257
- 238: Wallet/Purse
258
- 239: Volleyball
259
- 240: Deer
260
- 241: Goose
261
- 242: Tape
262
- 243: Tablet
263
- 244: Cosmetics
264
- 245: Trumpet
265
- 246: Pineapple
266
- 247: Golf Ball
267
- 248: Ambulance
268
- 249: Parking meter
269
- 250: Mango
270
- 251: Key
271
- 252: Hurdle
272
- 253: Fishing Rod
273
- 254: Medal
274
- 255: Flute
275
- 256: Brush
276
- 257: Penguin
277
- 258: Megaphone
278
- 259: Corn
279
- 260: Lettuce
280
- 261: Garlic
281
- 262: Swan
282
- 263: Helicopter
283
- 264: Green Onion
284
- 265: Sandwich
285
- 266: Nuts
286
- 267: Speed Limit Sign
287
- 268: Induction Cooker
288
- 269: Broom
289
- 270: Trombone
290
- 271: Plum
291
- 272: Rickshaw
292
- 273: Goldfish
293
- 274: Kiwi fruit
294
- 275: Router/modem
295
- 276: Poker Card
296
- 277: Toaster
297
- 278: Shrimp
298
- 279: Sushi
299
- 280: Cheese
300
- 281: Notepaper
301
- 282: Cherry
302
- 283: Pliers
303
- 284: CD
304
- 285: Pasta
305
- 286: Hammer
306
- 287: Cue
307
- 288: Avocado
308
- 289: Hami melon
309
- 290: Flask
310
- 291: Mushroom
311
- 292: Screwdriver
312
- 293: Soap
313
- 294: Recorder
314
- 295: Bear
315
- 296: Eggplant
316
- 297: Board Eraser
317
- 298: Coconut
318
- 299: Tape Measure/Ruler
319
- 300: Pig
320
- 301: Showerhead
321
- 302: Globe
322
- 303: Chips
323
- 304: Steak
324
- 305: Crosswalk Sign
325
- 306: Stapler
326
- 307: Camel
327
- 308: Formula 1
328
- 309: Pomegranate
329
- 310: Dishwasher
330
- 311: Crab
331
- 312: Hoverboard
332
- 313: Meatball
333
- 314: Rice Cooker
334
- 315: Tuba
335
- 316: Calculator
336
- 317: Papaya
337
- 318: Antelope
338
- 319: Parrot
339
- 320: Seal
340
- 321: Butterfly
341
- 322: Dumbbell
342
- 323: Donkey
343
- 324: Lion
344
- 325: Urinal
345
- 326: Dolphin
346
- 327: Electric Drill
347
- 328: Hair Dryer
348
- 329: Egg tart
349
- 330: Jellyfish
350
- 331: Treadmill
351
- 332: Lighter
352
- 333: Grapefruit
353
- 334: Game board
354
- 335: Mop
355
- 336: Radish
356
- 337: Baozi
357
- 338: Target
358
- 339: French
359
- 340: Spring Rolls
360
- 341: Monkey
361
- 342: Rabbit
362
- 343: Pencil Case
363
- 344: Yak
364
- 345: Red Cabbage
365
- 346: Binoculars
366
- 347: Asparagus
367
- 348: Barbell
368
- 349: Scallop
369
- 350: Noddles
370
- 351: Comb
371
- 352: Dumpling
372
- 353: Oyster
373
- 354: Table Tennis paddle
374
- 355: Cosmetics Brush/Eyeliner Pencil
375
- 356: Chainsaw
376
- 357: Eraser
377
- 358: Lobster
378
- 359: Durian
379
- 360: Okra
380
- 361: Lipstick
381
- 362: Cosmetics Mirror
382
- 363: Curling
383
- 364: Table Tennis
384
-
385
- # Download script/URL (optional) ---------------------------------------------------------------------------------------
386
- download: |
387
- from concurrent.futures import ThreadPoolExecutor
388
- from pathlib import Path
389
-
390
- import numpy as np
391
-
392
- from ultralytics.utils import TQDM
393
- from ultralytics.utils.checks import check_requirements
394
- from ultralytics.utils.downloads import download
395
- from ultralytics.utils.ops import xyxy2xywhn
396
-
397
- check_requirements("faster-coco-eval")
398
- from faster_coco_eval import COCO
399
-
400
- # Train, Val Splits
401
- dir = Path(yaml["path"])
402
- for split, patches in [("train", 50 + 1), ("val", 43 + 1)]:
403
- print(f"Processing {split} in {patches} patches ...")
404
- images, labels = dir / "images" / split, dir / "labels" / split
405
- images.mkdir(parents=True, exist_ok=True)
406
- labels.mkdir(parents=True, exist_ok=True)
407
-
408
- # Download
409
- url = f"https://dorc.ks3-cn-beijing.ksyun.com/data-set/2020Objects365%E6%95%B0%E6%8D%AE%E9%9B%86/{split}/"
410
- if split == "train":
411
- download([f"{url}zhiyuan_objv2_{split}.tar.gz"], dir=dir) # annotations json
412
- download([f"{url}patch{i}.tar.gz" for i in range(patches)], dir=images, threads=17) # 51 patches / 17 threads = 3
413
- elif split == "val":
414
- download([f"{url}zhiyuan_objv2_{split}.json"], dir=dir) # annotations json
415
- download([f"{url}images/v1/patch{i}.tar.gz" for i in range(15 + 1)], dir=images, threads=16)
416
- download([f"{url}images/v2/patch{i}.tar.gz" for i in range(16, patches)], dir=images, threads=16)
417
-
418
- # Move
419
- files = list(images.rglob("*.jpg"))
420
- with ThreadPoolExecutor(max_workers=16) as executor:
421
- list(TQDM(executor.map(lambda f: f.rename(images / f.name), files), total=len(files), desc=f"Moving {split} images"))
422
-
423
- # Labels
424
- coco = COCO(dir / f"zhiyuan_objv2_{split}.json")
425
- names = [x["name"] for x in coco.loadCats(coco.getCatIds())]
426
- for cid, cat in enumerate(names):
427
- catIds = coco.getCatIds(catNms=[cat])
428
- imgIds = coco.getImgIds(catIds=catIds)
429
-
430
- def process_annotation(im):
431
- """Process and write annotations for a single image."""
432
- try:
433
- width, height = im["width"], im["height"]
434
- path = Path(im["file_name"])
435
- with open(labels / path.with_suffix(".txt").name, "a", encoding="utf-8") as file:
436
- annIds = coco.getAnnIds(imgIds=im["id"], catIds=catIds, iscrowd=None)
437
- for a in coco.loadAnns(annIds):
438
- x, y, w, h = a["bbox"] # bounding box in xywh (xy top-left corner)
439
- xyxy = np.array([x, y, x + w, y + h])[None] # pixels(1,4)
440
- x, y, w, h = xyxy2xywhn(xyxy, w=width, h=height, clip=True)[0] # normalized and clipped
441
- file.write(f"{cid} {x:.5f} {y:.5f} {w:.5f} {h:.5f}\n")
442
- except Exception as e:
443
- print(e)
444
-
445
- images_list = coco.loadImgs(imgIds)
446
- with ThreadPoolExecutor(max_workers=16) as executor:
447
- list(TQDM(executor.map(process_annotation, images_list), total=len(images_list), desc=f"Class {cid + 1}/{len(names)} {cat}"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
vendor/ultralytics/cfg/datasets/SKU-110K.yaml DELETED
@@ -1,58 +0,0 @@
1
- # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
-
3
- # SKU-110K retail items dataset https://github.com/eg4000/SKU110K_CVPR19 by Trax Retail
4
- # Documentation: https://docs.ultralytics.com/datasets/detect/sku-110k/
5
- # Example usage: yolo train data=SKU-110K.yaml
6
- # parent
7
- # ├── ultralytics
8
- # └── datasets
9
- # └── SKU-110K ← downloads here (13.6 GB)
10
-
11
- # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
12
- path: SKU-110K # dataset root dir
13
- train: train.txt # train images (relative to 'path') 8219 images
14
- val: val.txt # val images (relative to 'path') 588 images
15
- test: test.txt # test images (optional) 2936 images
16
-
17
- # Classes
18
- names:
19
- 0: object
20
-
21
- # Download script/URL (optional) ---------------------------------------------------------------------------------------
22
- download: |
23
- import shutil
24
- from pathlib import Path
25
-
26
- import numpy as np
27
- import polars as pl
28
-
29
- from ultralytics.utils import TQDM
30
- from ultralytics.utils.downloads import download
31
- from ultralytics.utils.ops import xyxy2xywh
32
-
33
- # Download
34
- dir = Path(yaml["path"]) # dataset root dir
35
- parent = Path(dir.parent) # download dir
36
- urls = ["http://trax-geometry.s3.amazonaws.com/cvpr_challenge/SKU110K_fixed.tar.gz"]
37
- download(urls, dir=parent)
38
-
39
- # Rename directories
40
- if dir.exists():
41
- shutil.rmtree(dir)
42
- (parent / "SKU110K_fixed").rename(dir) # rename dir
43
- (dir / "labels").mkdir(parents=True, exist_ok=True) # create labels dir
44
-
45
- # Convert labels
46
- names = "image", "x1", "y1", "x2", "y2", "class", "image_width", "image_height" # column names
47
- for d in "annotations_train.csv", "annotations_val.csv", "annotations_test.csv":
48
- x = pl.read_csv(dir / "annotations" / d, has_header=False, new_columns=names, infer_schema_length=None).to_numpy() # annotations
49
- images, unique_images = x[:, 0], np.unique(x[:, 0])
50
- with open((dir / d).with_suffix(".txt").__str__().replace("annotations_", ""), "w", encoding="utf-8") as f:
51
- f.writelines(f"./images/{s}\n" for s in unique_images)
52
- for im in TQDM(unique_images, desc=f"Converting {dir / d}"):
53
- cls = 0 # single-class dataset
54
- with open((dir / "labels" / im).with_suffix(".txt"), "a", encoding="utf-8") as f:
55
- for r in x[images == im]:
56
- w, h = r[6], r[7] # image width, height
57
- xywh = xyxy2xywh(np.array([[r[1] / w, r[2] / h, r[3] / w, r[4] / h]]))[0] # instance
58
- f.write(f"{cls} {xywh[0]:.5f} {xywh[1]:.5f} {xywh[2]:.5f} {xywh[3]:.5f}\n") # write label
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
vendor/ultralytics/cfg/datasets/TT100K.yaml DELETED
@@ -1,346 +0,0 @@
1
- # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
-
3
- # Tsinghua-Tencent 100K (TT100K) dataset https://cg.cs.tsinghua.edu.cn/traffic-sign/ by Tsinghua University
4
- # Documentation: https://cg.cs.tsinghua.edu.cn/traffic-sign/tutorial.html
5
- # Paper: Traffic-Sign Detection and Classification in the Wild (CVPR 2016)
6
- # License: CC BY-NC 2.0 license for non-commercial use only
7
- # Example usage: yolo train data=TT100K.yaml
8
- # parent
9
- # ├── ultralytics
10
- # └── datasets
11
- # └── TT100K ← downloads here (~18 GB)
12
-
13
- # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
14
- path: TT100K # dataset root dir
15
- train: images/train # train images (relative to 'path') 6105 images
16
- val: images/val # val images (relative to 'path') 7641 images (original 'other' split)
17
- test: images/test # test images (relative to 'path') 3071 images
18
-
19
- # Classes (221 traffic sign categories, 45 with sufficient training instances)
20
- names:
21
- 0: pl5
22
- 1: pl10
23
- 2: pl15
24
- 3: pl20
25
- 4: pl25
26
- 5: pl30
27
- 6: pl40
28
- 7: pl50
29
- 8: pl60
30
- 9: pl70
31
- 10: pl80
32
- 11: pl90
33
- 12: pl100
34
- 13: pl110
35
- 14: pl120
36
- 15: pm5
37
- 16: pm10
38
- 17: pm13
39
- 18: pm15
40
- 19: pm20
41
- 20: pm25
42
- 21: pm30
43
- 22: pm35
44
- 23: pm40
45
- 24: pm46
46
- 25: pm50
47
- 26: pm55
48
- 27: pm8
49
- 28: pn
50
- 29: pne
51
- 30: ph4
52
- 31: ph4.5
53
- 32: ph5
54
- 33: ps
55
- 34: pg
56
- 35: ph1.5
57
- 36: ph2
58
- 37: ph2.1
59
- 38: ph2.2
60
- 39: ph2.4
61
- 40: ph2.5
62
- 41: ph2.8
63
- 42: ph2.9
64
- 43: ph3
65
- 44: ph3.2
66
- 45: ph3.5
67
- 46: ph3.8
68
- 47: ph4.2
69
- 48: ph4.3
70
- 49: ph4.8
71
- 50: ph5.3
72
- 51: ph5.5
73
- 52: pb
74
- 53: pr10
75
- 54: pr100
76
- 55: pr20
77
- 56: pr30
78
- 57: pr40
79
- 58: pr45
80
- 59: pr50
81
- 60: pr60
82
- 61: pr70
83
- 62: pr80
84
- 63: pr90
85
- 64: p1
86
- 65: p2
87
- 66: p3
88
- 67: p4
89
- 68: p5
90
- 69: p6
91
- 70: p7
92
- 71: p8
93
- 72: p9
94
- 73: p10
95
- 74: p11
96
- 75: p12
97
- 76: p13
98
- 77: p14
99
- 78: p15
100
- 79: p16
101
- 80: p17
102
- 81: p18
103
- 82: p19
104
- 83: p20
105
- 84: p21
106
- 85: p22
107
- 86: p23
108
- 87: p24
109
- 88: p25
110
- 89: p26
111
- 90: p27
112
- 91: p28
113
- 92: pa8
114
- 93: pa10
115
- 94: pa12
116
- 95: pa13
117
- 96: pa14
118
- 97: pb5
119
- 98: pc
120
- 99: pg
121
- 100: ph1
122
- 101: ph1.3
123
- 102: ph1.5
124
- 103: ph2
125
- 104: ph3
126
- 105: ph4
127
- 106: ph5
128
- 107: pi
129
- 108: pl0
130
- 109: pl4
131
- 110: pl5
132
- 111: pl8
133
- 112: pl10
134
- 113: pl15
135
- 114: pl20
136
- 115: pl25
137
- 116: pl30
138
- 117: pl35
139
- 118: pl40
140
- 119: pl50
141
- 120: pl60
142
- 121: pl65
143
- 122: pl70
144
- 123: pl80
145
- 124: pl90
146
- 125: pl100
147
- 126: pl110
148
- 127: pl120
149
- 128: pm2
150
- 129: pm8
151
- 130: pm10
152
- 131: pm13
153
- 132: pm15
154
- 133: pm20
155
- 134: pm25
156
- 135: pm30
157
- 136: pm35
158
- 137: pm40
159
- 138: pm46
160
- 139: pm50
161
- 140: pm55
162
- 141: pn
163
- 142: pne
164
- 143: po
165
- 144: pr10
166
- 145: pr100
167
- 146: pr20
168
- 147: pr30
169
- 148: pr40
170
- 149: pr45
171
- 150: pr50
172
- 151: pr60
173
- 152: pr70
174
- 153: pr80
175
- 154: ps
176
- 155: w1
177
- 156: w2
178
- 157: w3
179
- 158: w5
180
- 159: w8
181
- 160: w10
182
- 161: w12
183
- 162: w13
184
- 163: w16
185
- 164: w18
186
- 165: w20
187
- 166: w21
188
- 167: w22
189
- 168: w24
190
- 169: w28
191
- 170: w30
192
- 171: w31
193
- 172: w32
194
- 173: w34
195
- 174: w35
196
- 175: w37
197
- 176: w38
198
- 177: w41
199
- 178: w42
200
- 179: w43
201
- 180: w44
202
- 181: w45
203
- 182: w46
204
- 183: w47
205
- 184: w48
206
- 185: w49
207
- 186: w50
208
- 187: w51
209
- 188: w52
210
- 189: w53
211
- 190: w54
212
- 191: w55
213
- 192: w56
214
- 193: w57
215
- 194: w58
216
- 195: w59
217
- 196: w60
218
- 197: w62
219
- 198: w63
220
- 199: w66
221
- 200: i1
222
- 201: i2
223
- 202: i3
224
- 203: i4
225
- 204: i5
226
- 205: i6
227
- 206: i7
228
- 207: i8
229
- 208: i9
230
- 209: i10
231
- 210: i11
232
- 211: i12
233
- 212: i13
234
- 213: i14
235
- 214: i15
236
- 215: il60
237
- 216: il80
238
- 217: il100
239
- 218: il110
240
- 219: io
241
- 220: ip
242
-
243
- # Download script/URL (optional) ---------------------------------------------------------------------------------------
244
- download: |
245
- import json
246
- import shutil
247
- from pathlib import Path
248
-
249
- from PIL import Image
250
-
251
- from ultralytics.utils import TQDM
252
- from ultralytics.utils.downloads import download
253
-
254
-
255
- def tt100k2yolo(dir):
256
- """Convert TT100K annotations to YOLO format with images/{split} and labels/{split} structure."""
257
- data_dir = dir / "data"
258
- anno_file = data_dir / "annotations.json"
259
-
260
- print("Loading annotations...")
261
- with open(anno_file, encoding="utf-8") as f:
262
- data = json.load(f)
263
-
264
- # Build class name to index mapping from yaml
265
- names = yaml["names"]
266
- class_to_idx = {v: k for k, v in names.items()}
267
-
268
- # Create directories
269
- for split in ["train", "val", "test"]:
270
- (dir / "images" / split).mkdir(parents=True, exist_ok=True)
271
- (dir / "labels" / split).mkdir(parents=True, exist_ok=True)
272
-
273
- print("Converting annotations to YOLO format...")
274
- skipped = 0
275
- for img_id, img_data in TQDM(data["imgs"].items(), desc="Processing"):
276
- img_path_str = img_data["path"]
277
- if "train" in img_path_str:
278
- split = "train"
279
- elif "test" in img_path_str:
280
- split = "test"
281
- else:
282
- split = "val"
283
-
284
- # Source and destination paths
285
- src_img = data_dir / img_path_str
286
- if not src_img.exists():
287
- continue
288
-
289
- dst_img = dir / "images" / split / src_img.name
290
-
291
- # Get image dimensions
292
- try:
293
- with Image.open(src_img) as img:
294
- img_width, img_height = img.size
295
- except Exception as e:
296
- print(f"Error reading {src_img}: {e}")
297
- continue
298
-
299
- # Copy image to destination
300
- shutil.copy2(src_img, dst_img)
301
-
302
- # Convert annotations
303
- label_file = dir / "labels" / split / f"{src_img.stem}.txt"
304
- lines = []
305
-
306
- for obj in img_data.get("objects", []):
307
- category = obj["category"]
308
- if category not in class_to_idx:
309
- skipped += 1
310
- continue
311
-
312
- bbox = obj["bbox"]
313
- xmin, ymin = bbox["xmin"], bbox["ymin"]
314
- xmax, ymax = bbox["xmax"], bbox["ymax"]
315
-
316
- # Convert to YOLO format (normalized center coordinates and dimensions)
317
- x_center = ((xmin + xmax) / 2.0) / img_width
318
- y_center = ((ymin + ymax) / 2.0) / img_height
319
- width = (xmax - xmin) / img_width
320
- height = (ymax - ymin) / img_height
321
-
322
- # Clip to valid range
323
- x_center = max(0, min(1, x_center))
324
- y_center = max(0, min(1, y_center))
325
- width = max(0, min(1, width))
326
- height = max(0, min(1, height))
327
-
328
- cls_idx = class_to_idx[category]
329
- lines.append(f"{cls_idx} {x_center:.6f} {y_center:.6f} {width:.6f} {height:.6f}\n")
330
-
331
- # Write label file
332
- if lines:
333
- label_file.write_text("".join(lines), encoding="utf-8")
334
-
335
- if skipped:
336
- print(f"Skipped {skipped} annotations with unknown categories")
337
- print("Conversion complete!")
338
-
339
-
340
- # Download
341
- dir = Path(yaml["path"]) # dataset root dir
342
- urls = ["https://cg.cs.tsinghua.edu.cn/traffic-sign/data_model_code/data.zip"]
343
- download(urls, dir=dir, curl=True, threads=1)
344
-
345
- # Convert
346
- tt100k2yolo(dir)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
vendor/ultralytics/cfg/datasets/VOC.yaml DELETED
@@ -1,102 +0,0 @@
1
- # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
-
3
- # PASCAL VOC dataset http://host.robots.ox.ac.uk/pascal/VOC by University of Oxford
4
- # Documentation: https://docs.ultralytics.com/datasets/detect/voc/
5
- # Example usage: yolo train data=VOC.yaml
6
- # parent
7
- # ├── ultralytics
8
- # └── datasets
9
- # └── VOC ← downloads here (2.8 GB)
10
-
11
- # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
12
- path: VOC
13
- train: # train images (relative to 'path') 16551 images
14
- - images/train2012
15
- - images/train2007
16
- - images/val2012
17
- - images/val2007
18
- val: # val images (relative to 'path') 4952 images
19
- - images/test2007
20
- test: # test images (optional)
21
- - images/test2007
22
-
23
- # Classes
24
- names:
25
- 0: aeroplane
26
- 1: bicycle
27
- 2: bird
28
- 3: boat
29
- 4: bottle
30
- 5: bus
31
- 6: car
32
- 7: cat
33
- 8: chair
34
- 9: cow
35
- 10: diningtable
36
- 11: dog
37
- 12: horse
38
- 13: motorbike
39
- 14: person
40
- 15: pottedplant
41
- 16: sheep
42
- 17: sofa
43
- 18: train
44
- 19: tvmonitor
45
-
46
- # Download script/URL (optional) ---------------------------------------------------------------------------------------
47
- download: |
48
- import xml.etree.ElementTree as ET
49
- from pathlib import Path
50
-
51
- from ultralytics.utils.downloads import download
52
- from ultralytics.utils import ASSETS_URL, TQDM
53
-
54
- def convert_label(path, lb_path, year, image_id):
55
- """Converts XML annotations from VOC format to YOLO format by extracting bounding boxes and class IDs."""
56
-
57
- def convert_box(size, box):
58
- dw, dh = 1.0 / size[0], 1.0 / size[1]
59
- x, y, w, h = (box[0] + box[1]) / 2.0 - 1, (box[2] + box[3]) / 2.0 - 1, box[1] - box[0], box[3] - box[2]
60
- return x * dw, y * dh, w * dw, h * dh
61
-
62
- with open(path / f"VOC{year}/Annotations/{image_id}.xml") as in_file, open(lb_path, "w", encoding="utf-8") as out_file:
63
- tree = ET.parse(in_file)
64
- root = tree.getroot()
65
- size = root.find("size")
66
- w = int(size.find("width").text)
67
- h = int(size.find("height").text)
68
-
69
- names = list(yaml["names"].values()) # names list
70
- for obj in root.iter("object"):
71
- cls = obj.find("name").text
72
- if cls in names and int(obj.find("difficult").text) != 1:
73
- xmlbox = obj.find("bndbox")
74
- bb = convert_box((w, h), [float(xmlbox.find(x).text) for x in ("xmin", "xmax", "ymin", "ymax")])
75
- cls_id = names.index(cls) # class id
76
- out_file.write(" ".join(str(a) for a in (cls_id, *bb)) + "\n")
77
-
78
-
79
- # Download
80
- dir = Path(yaml["path"]) # dataset root dir
81
- urls = [
82
- f"{ASSETS_URL}/VOCtrainval_06-Nov-2007.zip", # 446MB, 5012 images
83
- f"{ASSETS_URL}/VOCtest_06-Nov-2007.zip", # 438MB, 4953 images
84
- f"{ASSETS_URL}/VOCtrainval_11-May-2012.zip", # 1.95GB, 17126 images
85
- ]
86
- download(urls, dir=dir / "images", threads=3, exist_ok=True) # download and unzip over existing (required)
87
-
88
- # Convert
89
- path = dir / "images/VOCdevkit"
90
- for year, image_set in ("2012", "train"), ("2012", "val"), ("2007", "train"), ("2007", "val"), ("2007", "test"):
91
- imgs_path = dir / "images" / f"{image_set}{year}"
92
- lbs_path = dir / "labels" / f"{image_set}{year}"
93
- imgs_path.mkdir(exist_ok=True, parents=True)
94
- lbs_path.mkdir(exist_ok=True, parents=True)
95
-
96
- with open(path / f"VOC{year}/ImageSets/Main/{image_set}.txt") as f:
97
- image_ids = f.read().strip().split()
98
- for id in TQDM(image_ids, desc=f"{image_set}{year}"):
99
- f = path / f"VOC{year}/JPEGImages/{id}.jpg" # old img path
100
- lb_path = (lbs_path / f.name).with_suffix(".txt") # new label path
101
- f.rename(imgs_path / f.name) # move image
102
- convert_label(path, lb_path, year, id) # convert labels to YOLO format
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
vendor/ultralytics/cfg/datasets/VisDrone.yaml DELETED
@@ -1,87 +0,0 @@
1
- # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
-
3
- # VisDrone2019-DET dataset https://github.com/VisDrone/VisDrone-Dataset by Tianjin University
4
- # Documentation: https://docs.ultralytics.com/datasets/detect/visdrone/
5
- # Example usage: yolo train data=VisDrone.yaml
6
- # parent
7
- # ├── ultralytics
8
- # └── datasets
9
- # └── VisDrone ← downloads here (2.3 GB)
10
-
11
- # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
12
- path: VisDrone # dataset root dir
13
- train: images/train # train images (relative to 'path') 6471 images
14
- val: images/val # val images (relative to 'path') 548 images
15
- test: images/test # test-dev images (optional) 1610 images
16
-
17
- # Classes
18
- names:
19
- 0: pedestrian
20
- 1: people
21
- 2: bicycle
22
- 3: car
23
- 4: van
24
- 5: truck
25
- 6: tricycle
26
- 7: awning-tricycle
27
- 8: bus
28
- 9: motor
29
-
30
- # Download script/URL (optional) ---------------------------------------------------------------------------------------
31
- download: |
32
- import os
33
- from pathlib import Path
34
- import shutil
35
-
36
- from ultralytics.utils.downloads import download
37
- from ultralytics.utils import ASSETS_URL, TQDM
38
-
39
-
40
- def visdrone2yolo(dir, split, source_name=None):
41
- """Convert VisDrone annotations to YOLO format with images/{split} and labels/{split} structure."""
42
- from PIL import Image
43
-
44
- source_dir = dir / (source_name or f"VisDrone2019-DET-{split}")
45
- images_dir = dir / "images" / split
46
- labels_dir = dir / "labels" / split
47
- labels_dir.mkdir(parents=True, exist_ok=True)
48
-
49
- # Move images to new structure
50
- if (source_images_dir := source_dir / "images").exists():
51
- images_dir.mkdir(parents=True, exist_ok=True)
52
- for img in source_images_dir.glob("*.jpg"):
53
- img.rename(images_dir / img.name)
54
-
55
- for f in TQDM((source_dir / "annotations").glob("*.txt"), desc=f"Converting {split}"):
56
- img_size = Image.open(images_dir / f.with_suffix(".jpg").name).size
57
- dw, dh = 1.0 / img_size[0], 1.0 / img_size[1]
58
- lines = []
59
-
60
- with open(f, encoding="utf-8") as file:
61
- for row in [x.split(",") for x in file.read().strip().splitlines()]:
62
- if row[4] != "0": # Skip ignored regions
63
- x, y, w, h = map(int, row[:4])
64
- cls = int(row[5]) - 1
65
- # Convert to YOLO format
66
- x_center, y_center = (x + w / 2) * dw, (y + h / 2) * dh
67
- w_norm, h_norm = w * dw, h * dh
68
- lines.append(f"{cls} {x_center:.6f} {y_center:.6f} {w_norm:.6f} {h_norm:.6f}\n")
69
-
70
- (labels_dir / f.name).write_text("".join(lines), encoding="utf-8")
71
-
72
-
73
- # Download (ignores test-challenge split)
74
- dir = Path(yaml["path"]) # dataset root dir
75
- urls = [
76
- f"{ASSETS_URL}/VisDrone2019-DET-train.zip",
77
- f"{ASSETS_URL}/VisDrone2019-DET-val.zip",
78
- f"{ASSETS_URL}/VisDrone2019-DET-test-dev.zip",
79
- # f"{ASSETS_URL}/VisDrone2019-DET-test-challenge.zip",
80
- ]
81
- download(urls, dir=dir, threads=4)
82
-
83
- # Convert
84
- splits = {"VisDrone2019-DET-train": "train", "VisDrone2019-DET-val": "val", "VisDrone2019-DET-test-dev": "test"}
85
- for folder, split in splits.items():
86
- visdrone2yolo(dir, split, folder) # convert VisDrone annotations to YOLO labels
87
- shutil.rmtree(dir / folder) # cleanup original directory
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
vendor/ultralytics/cfg/datasets/african-wildlife.yaml DELETED
@@ -1,25 +0,0 @@
1
- # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
-
3
- # African Wildlife dataset by Ultralytics
4
- # Documentation: https://docs.ultralytics.com/datasets/detect/african-wildlife/
5
- # Example usage: yolo train data=african-wildlife.yaml
6
- # parent
7
- # ├── ultralytics
8
- # └── datasets
9
- # └── african-wildlife ← downloads here (100 MB)
10
-
11
- # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
12
- path: african-wildlife # dataset root dir
13
- train: images/train # train images (relative to 'path') 1052 images
14
- val: images/val # val images (relative to 'path') 225 images
15
- test: images/test # test images (relative to 'path') 227 images
16
-
17
- # Classes
18
- names:
19
- 0: buffalo
20
- 1: elephant
21
- 2: rhino
22
- 3: zebra
23
-
24
- # Download script/URL (optional)
25
- download: https://github.com/ultralytics/assets/releases/download/v0.0.0/african-wildlife.zip
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
vendor/ultralytics/cfg/datasets/brain-tumor.yaml DELETED
@@ -1,22 +0,0 @@
1
- # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
-
3
- # Brain-tumor dataset by Ultralytics
4
- # Documentation: https://docs.ultralytics.com/datasets/detect/brain-tumor/
5
- # Example usage: yolo train data=brain-tumor.yaml
6
- # parent
7
- # ├── ultralytics
8
- # └── datasets
9
- # └── brain-tumor ← downloads here (4.21 MB)
10
-
11
- # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
12
- path: brain-tumor # dataset root dir
13
- train: images/train # train images (relative to 'path') 893 images
14
- val: images/val # val images (relative to 'path') 223 images
15
-
16
- # Classes
17
- names:
18
- 0: negative
19
- 1: positive
20
-
21
- # Download script/URL (optional)
22
- download: https://github.com/ultralytics/assets/releases/download/v0.0.0/brain-tumor.zip
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
vendor/ultralytics/cfg/datasets/carparts-seg.yaml DELETED
@@ -1,44 +0,0 @@
1
- # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
-
3
- # Carparts-seg dataset by Ultralytics
4
- # Documentation: https://docs.ultralytics.com/datasets/segment/carparts-seg/
5
- # Example usage: yolo train data=carparts-seg.yaml
6
- # parent
7
- # ├── ultralytics
8
- # └── datasets
9
- # └── carparts-seg ← downloads here (133 MB)
10
-
11
- # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
12
- path: carparts-seg # dataset root dir
13
- train: images/train # train images (relative to 'path') 3516 images
14
- val: images/val # val images (relative to 'path') 276 images
15
- test: images/test # test images (relative to 'path') 401 images
16
-
17
- # Classes
18
- names:
19
- 0: back_bumper
20
- 1: back_door
21
- 2: back_glass
22
- 3: back_left_door
23
- 4: back_left_light
24
- 5: back_light
25
- 6: back_right_door
26
- 7: back_right_light
27
- 8: front_bumper
28
- 9: front_door
29
- 10: front_glass
30
- 11: front_left_door
31
- 12: front_left_light
32
- 13: front_light
33
- 14: front_right_door
34
- 15: front_right_light
35
- 16: hood
36
- 17: left_mirror
37
- 18: object
38
- 19: right_mirror
39
- 20: tailgate
40
- 21: trunk
41
- 22: wheel
42
-
43
- # Download script/URL (optional)
44
- download: https://github.com/ultralytics/assets/releases/download/v0.0.0/carparts-seg.zip
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
vendor/ultralytics/cfg/datasets/coco-pose.yaml DELETED
@@ -1,64 +0,0 @@
1
- # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
-
3
- # COCO 2017 Keypoints dataset https://cocodataset.org by Microsoft
4
- # Documentation: https://docs.ultralytics.com/datasets/pose/coco/
5
- # Example usage: yolo train data=coco-pose.yaml
6
- # parent
7
- # ├── ultralytics
8
- # └── datasets
9
- # └── coco-pose ← downloads here (20.1 GB)
10
-
11
- # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
12
- path: coco-pose # dataset root dir
13
- train: train2017.txt # train images (relative to 'path') 56599 images
14
- val: val2017.txt # val images (relative to 'path') 2346 images
15
- test: test-dev2017.txt # 20288 of 40670 images, submit to https://codalab.lisn.upsaclay.fr/competitions/7403
16
-
17
- # Keypoints
18
- kpt_shape: [17, 3] # number of keypoints, number of dims (2 for x,y or 3 for x,y,visible)
19
- flip_idx: [0, 2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13, 16, 15]
20
-
21
- # Classes
22
- names:
23
- 0: person
24
-
25
- # Keypoint names per class
26
- kpt_names:
27
- 0:
28
- - nose
29
- - left_eye
30
- - right_eye
31
- - left_ear
32
- - right_ear
33
- - left_shoulder
34
- - right_shoulder
35
- - left_elbow
36
- - right_elbow
37
- - left_wrist
38
- - right_wrist
39
- - left_hip
40
- - right_hip
41
- - left_knee
42
- - right_knee
43
- - left_ankle
44
- - right_ankle
45
-
46
- # Download script/URL (optional)
47
- download: |
48
- from pathlib import Path
49
-
50
- from ultralytics.utils import ASSETS_URL
51
- from ultralytics.utils.downloads import download
52
-
53
- # Download labels
54
- dir = Path(yaml["path"]) # dataset root dir
55
-
56
- urls = [f"{ASSETS_URL}/coco2017labels-pose.zip"]
57
- download(urls, dir=dir.parent)
58
- # Download data
59
- urls = [
60
- "http://images.cocodataset.org/zips/train2017.zip", # 19G, 118k images
61
- "http://images.cocodataset.org/zips/val2017.zip", # 1G, 5k images
62
- "http://images.cocodataset.org/zips/test2017.zip", # 7G, 41k images (optional)
63
- ]
64
- download(urls, dir=dir / "images", threads=3)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
vendor/ultralytics/cfg/datasets/coco.yaml DELETED
@@ -1,118 +0,0 @@
1
- # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
-
3
- # COCO 2017 dataset https://cocodataset.org by Microsoft
4
- # Documentation: https://docs.ultralytics.com/datasets/detect/coco/
5
- # Example usage: yolo train data=coco.yaml
6
- # parent
7
- # ├── ultralytics
8
- # └── datasets
9
- # └── coco ← downloads here (20.1 GB)
10
-
11
- # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
12
- path: coco # dataset root dir
13
- train: train2017.txt # train images (relative to 'path') 118287 images
14
- val: val2017.txt # val images (relative to 'path') 5000 images
15
- test: test-dev2017.txt # 20288 of 40670 images, submit to https://competitions.codalab.org/competitions/20794
16
-
17
- # Classes
18
- names:
19
- 0: person
20
- 1: bicycle
21
- 2: car
22
- 3: motorcycle
23
- 4: airplane
24
- 5: bus
25
- 6: train
26
- 7: truck
27
- 8: boat
28
- 9: traffic light
29
- 10: fire hydrant
30
- 11: stop sign
31
- 12: parking meter
32
- 13: bench
33
- 14: bird
34
- 15: cat
35
- 16: dog
36
- 17: horse
37
- 18: sheep
38
- 19: cow
39
- 20: elephant
40
- 21: bear
41
- 22: zebra
42
- 23: giraffe
43
- 24: backpack
44
- 25: umbrella
45
- 26: handbag
46
- 27: tie
47
- 28: suitcase
48
- 29: frisbee
49
- 30: skis
50
- 31: snowboard
51
- 32: sports ball
52
- 33: kite
53
- 34: baseball bat
54
- 35: baseball glove
55
- 36: skateboard
56
- 37: surfboard
57
- 38: tennis racket
58
- 39: bottle
59
- 40: wine glass
60
- 41: cup
61
- 42: fork
62
- 43: knife
63
- 44: spoon
64
- 45: bowl
65
- 46: banana
66
- 47: apple
67
- 48: sandwich
68
- 49: orange
69
- 50: broccoli
70
- 51: carrot
71
- 52: hot dog
72
- 53: pizza
73
- 54: donut
74
- 55: cake
75
- 56: chair
76
- 57: couch
77
- 58: potted plant
78
- 59: bed
79
- 60: dining table
80
- 61: toilet
81
- 62: tv
82
- 63: laptop
83
- 64: mouse
84
- 65: remote
85
- 66: keyboard
86
- 67: cell phone
87
- 68: microwave
88
- 69: oven
89
- 70: toaster
90
- 71: sink
91
- 72: refrigerator
92
- 73: book
93
- 74: clock
94
- 75: vase
95
- 76: scissors
96
- 77: teddy bear
97
- 78: hair drier
98
- 79: toothbrush
99
-
100
- # Download script/URL (optional)
101
- download: |
102
- from pathlib import Path
103
-
104
- from ultralytics.utils import ASSETS_URL
105
- from ultralytics.utils.downloads import download
106
-
107
- # Download labels
108
- segments = True # segment or box labels
109
- dir = Path(yaml["path"]) # dataset root dir
110
- urls = [ASSETS_URL + ("/coco2017labels-segments.zip" if segments else "/coco2017labels.zip")] # labels
111
- download(urls, dir=dir.parent)
112
- # Download data
113
- urls = [
114
- "http://images.cocodataset.org/zips/train2017.zip", # 19G, 118k images
115
- "http://images.cocodataset.org/zips/val2017.zip", # 1G, 5k images
116
- "http://images.cocodataset.org/zips/test2017.zip", # 7G, 41k images (optional)
117
- ]
118
- download(urls, dir=dir / "images", threads=3)