trackflow-python-cuda 0.7.0__cp310-abi3-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- Cargo.lock +132 -0
- LICENSE +202 -0
- README.md +364 -0
- trackflow/__init__.py +93 -0
- trackflow/_accel.py +36 -0
- trackflow/_native.pyd +0 -0
- trackflow/benchmark.py +266 -0
- trackflow/boosttrack.py +476 -0
- trackflow/cli.py +705 -0
- trackflow/detector.py +912 -0
- trackflow/homography.py +240 -0
- trackflow/inspector.py +479 -0
- trackflow/inspector_ui.html +538 -0
- trackflow/lines.py +125 -0
- trackflow/mask_fallback.py +1025 -0
- trackflow/models.py +491 -0
- trackflow/nltrack.py +1107 -0
- trackflow/ocsort.py +406 -0
- trackflow/pipeline.py +1473 -0
- trackflow/postprocess.py +2068 -0
- trackflow/privacy.py +266 -0
- trackflow/py.typed +1 -0
- trackflow/reid.py +985 -0
- trackflow/sam2_adapter.py +222 -0
- trackflow/sinks.py +440 -0
- trackflow/tracker.py +1331 -0
- trackflow/types.py +241 -0
- trackflow_python_cuda-0.7.0.dist-info/METADATA +420 -0
- trackflow_python_cuda-0.7.0.dist-info/RECORD +33 -0
- trackflow_python_cuda-0.7.0.dist-info/WHEEL +4 -0
- trackflow_python_cuda-0.7.0.dist-info/entry_points.txt +3 -0
- trackflow_python_cuda-0.7.0.dist-info/licenses/LICENSE +202 -0
- trackflow_python_cuda-0.7.0.dist-info/sboms/trackflow-native.cyclonedx.json +536 -0
trackflow/detector.py
ADDED
|
@@ -0,0 +1,912 @@
|
|
|
1
|
+
"""Detector adapters for ONNX Runtime and optional Hugging Face Transformers models."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import contextlib
|
|
6
|
+
import ctypes
|
|
7
|
+
import functools
|
|
8
|
+
import hashlib
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import platform
|
|
12
|
+
import shutil
|
|
13
|
+
import site
|
|
14
|
+
import subprocess
|
|
15
|
+
import sys
|
|
16
|
+
from collections.abc import Sequence
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Any, Protocol
|
|
19
|
+
|
|
20
|
+
import cv2
|
|
21
|
+
import numpy as np
|
|
22
|
+
import onnxruntime as ort
|
|
23
|
+
|
|
24
|
+
from trackflow._accel import native_module
|
|
25
|
+
from trackflow.models import MODEL_REGISTRY, Precision, resolve_detector_artifacts
|
|
26
|
+
from trackflow.types import Detection
|
|
27
|
+
|
|
28
|
+
DEFAULT_COCO_LABELS: dict[int, str] = {
|
|
29
|
+
0: "person",
|
|
30
|
+
1: "bicycle",
|
|
31
|
+
2: "car",
|
|
32
|
+
3: "motorbike",
|
|
33
|
+
4: "aeroplane",
|
|
34
|
+
5: "bus",
|
|
35
|
+
6: "train",
|
|
36
|
+
7: "truck",
|
|
37
|
+
8: "boat",
|
|
38
|
+
9: "traffic light",
|
|
39
|
+
10: "fire hydrant",
|
|
40
|
+
11: "stop sign",
|
|
41
|
+
12: "parking meter",
|
|
42
|
+
13: "bench",
|
|
43
|
+
14: "bird",
|
|
44
|
+
15: "cat",
|
|
45
|
+
16: "dog",
|
|
46
|
+
17: "horse",
|
|
47
|
+
18: "sheep",
|
|
48
|
+
19: "cow",
|
|
49
|
+
20: "elephant",
|
|
50
|
+
21: "bear",
|
|
51
|
+
22: "zebra",
|
|
52
|
+
23: "giraffe",
|
|
53
|
+
24: "backpack",
|
|
54
|
+
25: "umbrella",
|
|
55
|
+
26: "handbag",
|
|
56
|
+
27: "tie",
|
|
57
|
+
28: "suitcase",
|
|
58
|
+
29: "frisbee",
|
|
59
|
+
30: "skis",
|
|
60
|
+
31: "snowboard",
|
|
61
|
+
32: "sports ball",
|
|
62
|
+
33: "kite",
|
|
63
|
+
34: "baseball bat",
|
|
64
|
+
35: "baseball glove",
|
|
65
|
+
36: "skateboard",
|
|
66
|
+
37: "surfboard",
|
|
67
|
+
38: "tennis racket",
|
|
68
|
+
39: "bottle",
|
|
69
|
+
40: "wine glass",
|
|
70
|
+
41: "cup",
|
|
71
|
+
42: "fork",
|
|
72
|
+
43: "knife",
|
|
73
|
+
44: "spoon",
|
|
74
|
+
45: "bowl",
|
|
75
|
+
46: "banana",
|
|
76
|
+
47: "apple",
|
|
77
|
+
48: "sandwich",
|
|
78
|
+
49: "orange",
|
|
79
|
+
50: "broccoli",
|
|
80
|
+
51: "carrot",
|
|
81
|
+
52: "hot dog",
|
|
82
|
+
53: "pizza",
|
|
83
|
+
54: "donut",
|
|
84
|
+
55: "cake",
|
|
85
|
+
56: "chair",
|
|
86
|
+
57: "sofa",
|
|
87
|
+
58: "pottedplant",
|
|
88
|
+
59: "bed",
|
|
89
|
+
60: "diningtable",
|
|
90
|
+
61: "toilet",
|
|
91
|
+
62: "tvmonitor",
|
|
92
|
+
63: "laptop",
|
|
93
|
+
64: "mouse",
|
|
94
|
+
65: "remote",
|
|
95
|
+
66: "keyboard",
|
|
96
|
+
67: "cell phone",
|
|
97
|
+
68: "microwave",
|
|
98
|
+
69: "oven",
|
|
99
|
+
70: "toaster",
|
|
100
|
+
71: "sink",
|
|
101
|
+
72: "refrigerator",
|
|
102
|
+
73: "book",
|
|
103
|
+
74: "clock",
|
|
104
|
+
75: "vase",
|
|
105
|
+
76: "scissors",
|
|
106
|
+
77: "teddy bear",
|
|
107
|
+
78: "hair drier",
|
|
108
|
+
79: "toothbrush",
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class Detector(Protocol):
|
|
113
|
+
"""A detector accepts one BGR uint8 frame and returns pixel-space xyxy boxes."""
|
|
114
|
+
|
|
115
|
+
def detect(self, frame_bgr: np.ndarray) -> list[Detection]: ...
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
_COCO_ALIASES = {
|
|
119
|
+
"motorbike": "motorcycle",
|
|
120
|
+
"aeroplane": "airplane",
|
|
121
|
+
"sofa": "couch",
|
|
122
|
+
"pottedplant": "potted plant",
|
|
123
|
+
"diningtable": "dining table",
|
|
124
|
+
"tvmonitor": "tv",
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _class_key(name: str) -> str:
|
|
129
|
+
name = name.strip().lower()
|
|
130
|
+
return _COCO_ALIASES.get(name, name)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _allowed_classes(classes: Sequence[str] | None) -> set[str] | None:
|
|
134
|
+
if isinstance(classes, str):
|
|
135
|
+
classes = classes.split(",")
|
|
136
|
+
names = {_class_key(c) for c in classes or () if c.strip()}
|
|
137
|
+
if not names or names.intersection({"*", "all"}):
|
|
138
|
+
return None
|
|
139
|
+
return names
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
_CUDA_INSTALL_HINT = (
|
|
143
|
+
"Run with NVIDIA CUDA support: `uvx trackflow-python-cuda run <video>` "
|
|
144
|
+
"(or `pip install trackflow-python-cuda` in a clean environment without CPU `onnxruntime`)."
|
|
145
|
+
)
|
|
146
|
+
_TRT_INSTALL_HINT = (
|
|
147
|
+
"Run with NVIDIA TensorRT support (Python 3.11+): `uvx trackflow-python-tensorrt run <video>` "
|
|
148
|
+
"(or `pip install trackflow-python-tensorrt` in a clean environment without CPU `onnxruntime`)."
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def detect_nvidia_gpu() -> str | None:
|
|
153
|
+
"""Return ``'<name>, <driver>'`` from ``nvidia-smi`` when an NVIDIA GPU is present."""
|
|
154
|
+
if shutil.which("nvidia-smi") is None:
|
|
155
|
+
return None
|
|
156
|
+
try:
|
|
157
|
+
res = subprocess.run(
|
|
158
|
+
["nvidia-smi", "--query-gpu=name,driver_version", "--format=csv,noheader"],
|
|
159
|
+
capture_output=True,
|
|
160
|
+
text=True,
|
|
161
|
+
timeout=1.5,
|
|
162
|
+
check=False,
|
|
163
|
+
)
|
|
164
|
+
except Exception:
|
|
165
|
+
return None
|
|
166
|
+
if res.returncode != 0:
|
|
167
|
+
return None
|
|
168
|
+
first = next((line.strip() for line in res.stdout.splitlines() if line.strip()), None)
|
|
169
|
+
return first or None
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
@functools.lru_cache(maxsize=1)
|
|
173
|
+
def preload_gpu_libraries() -> tuple[str, ...]:
|
|
174
|
+
"""Preload pip-bundled CUDA, cuDNN, and TensorRT libraries so LD_LIBRARY_PATH is unneeded."""
|
|
175
|
+
available = ort.get_available_providers()
|
|
176
|
+
if (
|
|
177
|
+
"CUDAExecutionProvider" not in available
|
|
178
|
+
and "TensorrtExecutionProvider" not in available
|
|
179
|
+
):
|
|
180
|
+
return ()
|
|
181
|
+
if hasattr(ort, "preload_dlls"):
|
|
182
|
+
with contextlib.suppress(Exception):
|
|
183
|
+
ort.preload_dlls(cuda=True, cudnn=True, msvc=(os.name == "nt"))
|
|
184
|
+
|
|
185
|
+
loaded: list[str] = []
|
|
186
|
+
seen_dirs: set[Path] = set()
|
|
187
|
+
search_roots: list[str] = []
|
|
188
|
+
with contextlib.suppress(Exception):
|
|
189
|
+
search_roots.extend(site.getsitepackages())
|
|
190
|
+
with contextlib.suppress(Exception):
|
|
191
|
+
user_site = site.getusersitepackages()
|
|
192
|
+
if user_site:
|
|
193
|
+
search_roots.append(user_site)
|
|
194
|
+
|
|
195
|
+
for root in search_roots:
|
|
196
|
+
root_path = Path(root)
|
|
197
|
+
if not root_path.is_dir():
|
|
198
|
+
continue
|
|
199
|
+
for lib_dir in sorted(root_path.glob("tensorrt*libs")):
|
|
200
|
+
if not lib_dir.is_dir() or lib_dir in seen_dirs:
|
|
201
|
+
continue
|
|
202
|
+
seen_dirs.add(lib_dir)
|
|
203
|
+
if os.name == "nt":
|
|
204
|
+
if hasattr(os, "add_dll_directory"):
|
|
205
|
+
with contextlib.suppress(OSError):
|
|
206
|
+
os.add_dll_directory(str(lib_dir))
|
|
207
|
+
for dll in sorted(lib_dir.glob("nvinfer*.dll")):
|
|
208
|
+
loaded.append(dll.name)
|
|
209
|
+
continue
|
|
210
|
+
# Load core nvinfer before plugin and onnxparser so shared symbols resolve in order.
|
|
211
|
+
for pat in ("libnvinfer.so.*", "libnvinfer_plugin.so.*", "libnvonnxparser.so.*"):
|
|
212
|
+
for so in sorted(lib_dir.glob(pat)):
|
|
213
|
+
if so.is_symlink():
|
|
214
|
+
continue
|
|
215
|
+
with contextlib.suppress(OSError):
|
|
216
|
+
ctypes.CDLL(str(so), mode=ctypes.RTLD_GLOBAL)
|
|
217
|
+
loaded.append(so.name)
|
|
218
|
+
return tuple(loaded)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _trt_cache_paths(
|
|
222
|
+
onnx_path: Path, *, trt_fp16: bool, cache_dir: str | Path | None = None
|
|
223
|
+
) -> tuple[Path, Path]:
|
|
224
|
+
"""Return ``(engine_dir, timing_cache_dir)`` for persistent TensorRT engine caching."""
|
|
225
|
+
if cache_dir is not None:
|
|
226
|
+
root = Path(cache_dir) / "trt_cache"
|
|
227
|
+
else:
|
|
228
|
+
env_dir = os.environ.get("TRACKFLOW_TRT_CACHE_DIR", "").strip()
|
|
229
|
+
root = Path(env_dir) if env_dir else Path.home() / ".cache" / "trackflow" / "trt_cache"
|
|
230
|
+
resolved = onnx_path.resolve()
|
|
231
|
+
key_parts = [str(resolved), "fp16" if trt_fp16 else "fp32"]
|
|
232
|
+
with contextlib.suppress(OSError):
|
|
233
|
+
st = resolved.stat()
|
|
234
|
+
key_parts.extend([str(st.st_size), str(st.st_mtime_ns)])
|
|
235
|
+
digest = hashlib.sha256("|".join(key_parts).encode("utf-8")).hexdigest()[:12]
|
|
236
|
+
engine_dir = root / f"{onnx_path.stem}_{digest}_{'fp16' if trt_fp16 else 'fp32'}"
|
|
237
|
+
return engine_dir, root
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def select_providers(device: str = "auto") -> list[str]:
|
|
241
|
+
"""Choose ONNX Runtime execution providers based on requested device."""
|
|
242
|
+
available = ort.get_available_providers()
|
|
243
|
+
req = device.lower().strip()
|
|
244
|
+
|
|
245
|
+
options = {
|
|
246
|
+
"cpu": ["CPUExecutionProvider"],
|
|
247
|
+
"cuda": ["CUDAExecutionProvider", "CPUExecutionProvider"],
|
|
248
|
+
"coreml": ["CoreMLExecutionProvider", "CPUExecutionProvider"],
|
|
249
|
+
"tensorrt": ["TensorrtExecutionProvider", "CUDAExecutionProvider", "CPUExecutionProvider"],
|
|
250
|
+
}
|
|
251
|
+
if req != "auto":
|
|
252
|
+
if req not in options:
|
|
253
|
+
raise ValueError(
|
|
254
|
+
f"Unknown ONNX device {device!r}. Choose auto, cpu, coreml, cuda, or tensorrt."
|
|
255
|
+
)
|
|
256
|
+
if options[req][0] not in available:
|
|
257
|
+
hint = ""
|
|
258
|
+
if req == "cuda":
|
|
259
|
+
hint = f" {_CUDA_INSTALL_HINT}"
|
|
260
|
+
elif req == "tensorrt":
|
|
261
|
+
hint = f" {_TRT_INSTALL_HINT}"
|
|
262
|
+
raise ValueError(
|
|
263
|
+
f"{device} requires {options[req][0]}. Available providers: {available}.{hint}"
|
|
264
|
+
)
|
|
265
|
+
return [p for p in options[req] if p in available]
|
|
266
|
+
|
|
267
|
+
# Auto-selection: prefer NVIDIA CUDA if present, else multi-threaded CPU. On Apple Silicon,
|
|
268
|
+
# CoreML runs part of each DETR graph on the CPU: it frees most CPU cores but is slower for
|
|
269
|
+
# RF-DETR, so it stays opt-in with --device coreml.
|
|
270
|
+
preferred = [
|
|
271
|
+
"CUDAExecutionProvider",
|
|
272
|
+
"CPUExecutionProvider",
|
|
273
|
+
]
|
|
274
|
+
selected = [p for p in preferred if p in available]
|
|
275
|
+
return selected or ["CPUExecutionProvider"]
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _apple_p_cores() -> int | None:
|
|
279
|
+
"""Return Apple Silicon's performance-core count via sysctlbyname, or None elsewhere."""
|
|
280
|
+
if platform.system() != "Darwin":
|
|
281
|
+
return None
|
|
282
|
+
try:
|
|
283
|
+
libc = ctypes.CDLL(None)
|
|
284
|
+
val = ctypes.c_int(0)
|
|
285
|
+
size = ctypes.c_size_t(ctypes.sizeof(val))
|
|
286
|
+
rc = libc.sysctlbyname(
|
|
287
|
+
b"hw.perflevel0.physicalcpu", ctypes.byref(val), ctypes.byref(size), None, 0
|
|
288
|
+
)
|
|
289
|
+
return val.value if rc == 0 and val.value > 0 else None
|
|
290
|
+
except Exception:
|
|
291
|
+
return None
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def _default_onnx_threads() -> int:
|
|
295
|
+
"""Pick ORT intra-op threads: honor OMP_NUM_THREADS, else pin Apple Silicon to P-cores."""
|
|
296
|
+
env = os.environ.get("OMP_NUM_THREADS", "").strip()
|
|
297
|
+
if env:
|
|
298
|
+
with contextlib.suppress(ValueError):
|
|
299
|
+
if (n := int(env)) > 0:
|
|
300
|
+
return n
|
|
301
|
+
# On Apple Silicon, ORT defaults to hw.physicalcpu (P + E cores), so slow E-cores stall
|
|
302
|
+
# thread barriers. Pinning to P-cores speeds up CPU DETR models by ~17-27%.
|
|
303
|
+
return _apple_p_cores() or 0
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def create_onnx_session(
|
|
307
|
+
onnx_path: Path,
|
|
308
|
+
device: str = "auto",
|
|
309
|
+
*,
|
|
310
|
+
optimization: ort.GraphOptimizationLevel = ort.GraphOptimizationLevel.ORT_ENABLE_ALL,
|
|
311
|
+
coreml_format: str | None = "MLProgram",
|
|
312
|
+
trt_fp16: bool = True,
|
|
313
|
+
cache_dir: str | Path | None = None,
|
|
314
|
+
) -> tuple[ort.InferenceSession, str]:
|
|
315
|
+
"""Create an ONNX Runtime session with safe fallback to CPU if an EP fails."""
|
|
316
|
+
providers = select_providers(device)
|
|
317
|
+
if (
|
|
318
|
+
"CUDAExecutionProvider" in providers
|
|
319
|
+
or "TensorrtExecutionProvider" in providers
|
|
320
|
+
):
|
|
321
|
+
preload_gpu_libraries()
|
|
322
|
+
|
|
323
|
+
provider_options: list[dict[str, Any]] = []
|
|
324
|
+
for p in providers:
|
|
325
|
+
if p == "CoreMLExecutionProvider" and coreml_format is not None:
|
|
326
|
+
# CoreML runs on the GPU, not the Neural Engine, so results match the CPU's fp32.
|
|
327
|
+
# ``coreml_format=None`` keeps ONNX Runtime's default CoreML setup.
|
|
328
|
+
provider_options.append({"ModelFormat": coreml_format, "MLComputeUnits": "CPUAndGPU"})
|
|
329
|
+
elif p == "CUDAExecutionProvider":
|
|
330
|
+
# HEURISTIC cuts cuDNN startup search ~4-5x with identical steady-state throughput.
|
|
331
|
+
provider_options.append({"cudnn_conv_algo_search": "HEURISTIC"})
|
|
332
|
+
elif p == "TensorrtExecutionProvider":
|
|
333
|
+
engine_dir, timing_root = _trt_cache_paths(
|
|
334
|
+
onnx_path, trt_fp16=trt_fp16, cache_dir=cache_dir
|
|
335
|
+
)
|
|
336
|
+
engine_dir.mkdir(parents=True, exist_ok=True)
|
|
337
|
+
if not any(engine_dir.glob("*.engine")):
|
|
338
|
+
precision_label = "FP16" if trt_fp16 else "FP32"
|
|
339
|
+
print(
|
|
340
|
+
f"Building TensorRT {precision_label} engine for {onnx_path.name} "
|
|
341
|
+
f"(first run only; cached in {engine_dir})...",
|
|
342
|
+
file=sys.stderr,
|
|
343
|
+
flush=True,
|
|
344
|
+
)
|
|
345
|
+
provider_options.append(
|
|
346
|
+
{
|
|
347
|
+
"trt_engine_cache_enable": True,
|
|
348
|
+
"trt_engine_cache_path": str(engine_dir),
|
|
349
|
+
"trt_timing_cache_enable": True,
|
|
350
|
+
"trt_timing_cache_path": str(timing_root),
|
|
351
|
+
"trt_fp16_enable": bool(trt_fp16),
|
|
352
|
+
}
|
|
353
|
+
)
|
|
354
|
+
else:
|
|
355
|
+
provider_options.append({})
|
|
356
|
+
|
|
357
|
+
sess_opts = ort.SessionOptions()
|
|
358
|
+
sess_opts.graph_optimization_level = optimization
|
|
359
|
+
sess_opts.intra_op_num_threads = _default_onnx_threads()
|
|
360
|
+
sess_opts.inter_op_num_threads = 1
|
|
361
|
+
|
|
362
|
+
try:
|
|
363
|
+
session = ort.InferenceSession(
|
|
364
|
+
str(onnx_path),
|
|
365
|
+
sess_options=sess_opts,
|
|
366
|
+
providers=providers,
|
|
367
|
+
provider_options=provider_options,
|
|
368
|
+
)
|
|
369
|
+
except Exception:
|
|
370
|
+
if device.strip().lower() != "auto" or providers == ["CPUExecutionProvider"]:
|
|
371
|
+
raise
|
|
372
|
+
session = ort.InferenceSession(
|
|
373
|
+
str(onnx_path),
|
|
374
|
+
sess_options=sess_opts,
|
|
375
|
+
providers=["CPUExecutionProvider"],
|
|
376
|
+
)
|
|
377
|
+
|
|
378
|
+
active = session.get_providers()
|
|
379
|
+
active_name = active[0] if active else "CPUExecutionProvider"
|
|
380
|
+
req = device.strip().lower()
|
|
381
|
+
if req != "auto" and active_name != providers[0]:
|
|
382
|
+
hint = ""
|
|
383
|
+
if providers[0] == "TensorrtExecutionProvider":
|
|
384
|
+
hint = f" {_TRT_INSTALL_HINT}"
|
|
385
|
+
elif providers[0] == "CUDAExecutionProvider":
|
|
386
|
+
hint = f" {_CUDA_INSTALL_HINT}"
|
|
387
|
+
raise RuntimeError(
|
|
388
|
+
f"Could not start {providers[0]}. ONNX Runtime selected {active_name}.{hint}"
|
|
389
|
+
)
|
|
390
|
+
return session, active_name
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def sigmoid(x: np.ndarray) -> np.ndarray:
|
|
394
|
+
"""Numerically stable sigmoid."""
|
|
395
|
+
x_clip = np.clip(x, -60.0, 60.0)
|
|
396
|
+
return 1.0 / (1.0 + np.exp(-x_clip))
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def _nms_class_aware(detections: list[Detection], iou_threshold: float) -> list[Detection]:
|
|
400
|
+
"""Deduplicate overlapping same-class DETR queries so duplicate boxes don't spawn ghost tracks."""
|
|
401
|
+
if len(detections) <= 1 or iou_threshold <= 0.0 or iou_threshold >= 1.0:
|
|
402
|
+
return detections
|
|
403
|
+
|
|
404
|
+
kept: list[Detection] = []
|
|
405
|
+
for det in detections:
|
|
406
|
+
x1, y1, x2, y2 = det.bbox
|
|
407
|
+
area_a = max(0.0, x2 - x1) * max(0.0, y2 - y1)
|
|
408
|
+
duplicate = False
|
|
409
|
+
for prev in kept:
|
|
410
|
+
if prev.class_id != det.class_id:
|
|
411
|
+
continue
|
|
412
|
+
px1, py1, px2, py2 = prev.bbox
|
|
413
|
+
iw = max(0.0, min(x2, px2) - max(x1, px1))
|
|
414
|
+
ih = max(0.0, min(y2, py2) - max(y1, py1))
|
|
415
|
+
inter = iw * ih
|
|
416
|
+
if inter <= 0.0:
|
|
417
|
+
continue
|
|
418
|
+
area_b = max(0.0, px2 - px1) * max(0.0, py2 - py1)
|
|
419
|
+
iou = inter / max(area_a + area_b - inter, 1e-6)
|
|
420
|
+
if iou >= iou_threshold:
|
|
421
|
+
duplicate = True
|
|
422
|
+
break
|
|
423
|
+
if not duplicate:
|
|
424
|
+
kept.append(det)
|
|
425
|
+
return kept
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def _letterbox(
|
|
429
|
+
frame_bgr: np.ndarray, input_hw: tuple[int, int], pad: int
|
|
430
|
+
) -> tuple[np.ndarray, tuple[int, int, float, float]]:
|
|
431
|
+
"""Resize keeping the aspect ratio, centered on a ``pad``-filled canvas of ``input_hw``.
|
|
432
|
+
|
|
433
|
+
Returns the canvas and ``(left, top, scale_x, scale_y)`` for ``_unletterbox``.
|
|
434
|
+
"""
|
|
435
|
+
h, w = input_hw
|
|
436
|
+
orig_h, orig_w = frame_bgr.shape[:2]
|
|
437
|
+
scale = min(w / orig_w, h / orig_h)
|
|
438
|
+
rw, rh = max(1, int(orig_w * scale)), max(1, int(orig_h * scale))
|
|
439
|
+
left, top = (w - rw) // 2, (h - rh) // 2
|
|
440
|
+
canvas = np.full((h, w, 3), pad, dtype=np.uint8)
|
|
441
|
+
canvas[top : top + rh, left : left + rw] = cv2.resize(frame_bgr, (rw, rh))
|
|
442
|
+
return canvas, (left, top, rw / orig_w, rh / orig_h)
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
def _unletterbox(xyxy: np.ndarray, placement: tuple[int, int, float, float]) -> np.ndarray:
|
|
446
|
+
"""Map xyxy boxes on a ``_letterbox`` canvas back to the original frame's pixels."""
|
|
447
|
+
left, top, sx, sy = placement
|
|
448
|
+
return (np.asarray(xyxy, dtype=np.float64) - [left, top, left, top]) / [sx, sy, sx, sy]
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
def postprocess_detr_outputs(
|
|
452
|
+
logits: np.ndarray,
|
|
453
|
+
pred_boxes: np.ndarray,
|
|
454
|
+
orig_hw: tuple[int, int],
|
|
455
|
+
id2label: dict[int, str],
|
|
456
|
+
threshold: float = 0.45,
|
|
457
|
+
allowed_classes: set[str] | None = None,
|
|
458
|
+
max_detections: int = 300,
|
|
459
|
+
nms_iou: float = 0.65,
|
|
460
|
+
softmax: bool = False,
|
|
461
|
+
) -> list[Detection]:
|
|
462
|
+
"""Convert DETR/RT-DETR/D-FINE/RF-DETR raw logits + normalized cxcywh boxes into Detections."""
|
|
463
|
+
native = native_module()
|
|
464
|
+
if native is not None:
|
|
465
|
+
return native.postprocess_detr_outputs(
|
|
466
|
+
logits,
|
|
467
|
+
pred_boxes,
|
|
468
|
+
orig_hw,
|
|
469
|
+
id2label,
|
|
470
|
+
threshold,
|
|
471
|
+
allowed_classes,
|
|
472
|
+
max_detections,
|
|
473
|
+
nms_iou,
|
|
474
|
+
softmax,
|
|
475
|
+
)
|
|
476
|
+
# Squeeze batch dimension [1, N, C] -> [N, C]
|
|
477
|
+
if logits.ndim == 3:
|
|
478
|
+
logits = logits[0]
|
|
479
|
+
if pred_boxes.ndim == 3:
|
|
480
|
+
pred_boxes = pred_boxes[0]
|
|
481
|
+
|
|
482
|
+
if softmax:
|
|
483
|
+
exp = np.exp(logits - logits.max(axis=-1, keepdims=True))
|
|
484
|
+
probs = (exp / exp.sum(axis=-1, keepdims=True))[:, :-1] # trailing no-object class
|
|
485
|
+
class_ids = np.argmax(probs, axis=-1)
|
|
486
|
+
scores = probs[np.arange(probs.shape[0]), class_ids]
|
|
487
|
+
else:
|
|
488
|
+
# Sigmoid is monotone on [-60, 60]; pick the top class logit per query first so
|
|
489
|
+
# exp() runs once per query instead of once per (query, class).
|
|
490
|
+
class_ids = np.argmax(logits, axis=-1)
|
|
491
|
+
max_logits = logits[np.arange(logits.shape[0]), class_ids]
|
|
492
|
+
scores = sigmoid(max_logits)
|
|
493
|
+
|
|
494
|
+
keep = (scores >= threshold) & np.isfinite(pred_boxes).all(axis=-1)
|
|
495
|
+
if not np.any(keep):
|
|
496
|
+
return []
|
|
497
|
+
|
|
498
|
+
kept_scores = scores[keep]
|
|
499
|
+
kept_classes = class_ids[keep]
|
|
500
|
+
kept_boxes = pred_boxes[keep]
|
|
501
|
+
|
|
502
|
+
# Stable sort so ties keep query order (web/detector.js mirrors this for parity).
|
|
503
|
+
order = np.argsort(-kept_scores, kind="stable")
|
|
504
|
+
orig_h, orig_w = orig_hw
|
|
505
|
+
|
|
506
|
+
detections: list[Detection] = []
|
|
507
|
+
for idx in order:
|
|
508
|
+
cid = int(kept_classes[idx])
|
|
509
|
+
cname = id2label.get(cid, str(cid))
|
|
510
|
+
if (
|
|
511
|
+
allowed_classes is not None
|
|
512
|
+
and cname.lower() not in allowed_classes
|
|
513
|
+
and _class_key(cname) not in allowed_classes
|
|
514
|
+
):
|
|
515
|
+
continue
|
|
516
|
+
|
|
517
|
+
cx, cy, w, h = kept_boxes[idx].tolist()
|
|
518
|
+
# Handle both normalized [0, 1] and already-pixel coordinates safely.
|
|
519
|
+
if max(cx, cy, w, h) <= 2.0:
|
|
520
|
+
x1 = (cx - 0.5 * w) * orig_w
|
|
521
|
+
y1 = (cy - 0.5 * h) * orig_h
|
|
522
|
+
x2 = (cx + 0.5 * w) * orig_w
|
|
523
|
+
y2 = (cy + 0.5 * h) * orig_h
|
|
524
|
+
else:
|
|
525
|
+
x1, y1, x2, y2 = cx - 0.5 * w, cy - 0.5 * h, cx + 0.5 * w, cy + 0.5 * h
|
|
526
|
+
|
|
527
|
+
x1 = float(np.clip(x1, 0.0, orig_w))
|
|
528
|
+
y1 = float(np.clip(y1, 0.0, orig_h))
|
|
529
|
+
x2 = float(np.clip(x2, 0.0, orig_w))
|
|
530
|
+
y2 = float(np.clip(y2, 0.0, orig_h))
|
|
531
|
+
|
|
532
|
+
if x2 - x1 < 2.0 or y2 - y1 < 2.0:
|
|
533
|
+
continue
|
|
534
|
+
|
|
535
|
+
detections.append(
|
|
536
|
+
Detection(
|
|
537
|
+
bbox=(x1, y1, x2, y2),
|
|
538
|
+
confidence=float(kept_scores[idx]),
|
|
539
|
+
class_id=cid,
|
|
540
|
+
class_name=cname,
|
|
541
|
+
)
|
|
542
|
+
)
|
|
543
|
+
|
|
544
|
+
return _nms_class_aware(detections, iou_threshold=nms_iou)[:max_detections]
|
|
545
|
+
|
|
546
|
+
|
|
547
|
+
class OnnxDetrDetector:
|
|
548
|
+
"""End-to-end transformer object detector powered by ONNX Runtime."""
|
|
549
|
+
|
|
550
|
+
def __init__(
|
|
551
|
+
self,
|
|
552
|
+
model: str = "rtdetr-v2-r18",
|
|
553
|
+
*,
|
|
554
|
+
precision: Precision = "fp32",
|
|
555
|
+
device: str = "auto",
|
|
556
|
+
threshold: float = 0.45,
|
|
557
|
+
classes: Sequence[str] | None = ("person",),
|
|
558
|
+
cache_dir: str | Path | None = None,
|
|
559
|
+
) -> None:
|
|
560
|
+
self.model_name = model
|
|
561
|
+
self.precision = precision
|
|
562
|
+
spec = MODEL_REGISTRY.get(model)
|
|
563
|
+
self.revision = spec.revision if spec else None
|
|
564
|
+
self.threshold = float(threshold)
|
|
565
|
+
self.allowed_classes = _allowed_classes(classes)
|
|
566
|
+
|
|
567
|
+
onnx_path, config_path, prep_path = resolve_detector_artifacts(
|
|
568
|
+
model=model,
|
|
569
|
+
precision=precision,
|
|
570
|
+
cache_dir=cache_dir,
|
|
571
|
+
)
|
|
572
|
+
self.onnx_path = onnx_path
|
|
573
|
+
self.id2label = self._load_labels(config_path)
|
|
574
|
+
self.input_hw, self.do_rescale, self.do_normalize, self.mean, self.std = (
|
|
575
|
+
self._load_preprocess_config(prep_path)
|
|
576
|
+
)
|
|
577
|
+
if spec and spec.normalize:
|
|
578
|
+
self.do_normalize = True
|
|
579
|
+
|
|
580
|
+
# CoreML EP on int8 quantized DETR graphs can occasionally fail or degrade; prefer CPU for int8.
|
|
581
|
+
effective_device = "cpu" if (device == "auto" and precision == "int8") else device
|
|
582
|
+
cfg = json.loads(config_path.read_text(encoding="utf-8")) if config_path else {}
|
|
583
|
+
optimization = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
|
|
584
|
+
# ORT's extended CPU fusions for this signed INT8 graph abort the process on arm64 macOS.
|
|
585
|
+
if (
|
|
586
|
+
cfg.get("model_type") == "d_fine"
|
|
587
|
+
and (precision == "int8" or "int8" in onnx_path.name)
|
|
588
|
+
and platform.system() == "Darwin"
|
|
589
|
+
and platform.machine() == "arm64"
|
|
590
|
+
):
|
|
591
|
+
optimization = ort.GraphOptimizationLevel.ORT_ENABLE_BASIC
|
|
592
|
+
self.session, self.active_provider = create_onnx_session(
|
|
593
|
+
onnx_path,
|
|
594
|
+
device=effective_device,
|
|
595
|
+
optimization=optimization,
|
|
596
|
+
coreml_format=spec.coreml_format if spec else "MLProgram",
|
|
597
|
+
trt_fp16=spec.trt_fp16 if spec else True,
|
|
598
|
+
cache_dir=cache_dir,
|
|
599
|
+
)
|
|
600
|
+
|
|
601
|
+
self.input_name = self.session.get_inputs()[0].name
|
|
602
|
+
self.output_names = [o.name for o in self.session.get_outputs()]
|
|
603
|
+
inputs = {i.name for i in self.session.get_inputs()}
|
|
604
|
+
self.letterbox = bool(spec and spec.letterbox)
|
|
605
|
+
self.deployed = inputs == {"images", "orig_target_sizes"} and set(self.output_names) == {
|
|
606
|
+
"labels",
|
|
607
|
+
"boxes",
|
|
608
|
+
"scores",
|
|
609
|
+
}
|
|
610
|
+
if self.deployed:
|
|
611
|
+
self.input_name = "images"
|
|
612
|
+
elif len(inputs) == 1 and {"logits", "pred_boxes"}.issubset(self.output_names):
|
|
613
|
+
self.raw_outputs = ["logits", "pred_boxes"]
|
|
614
|
+
elif len(inputs) == 1 and len(self.output_names) == 2:
|
|
615
|
+
# Legacy two-output exports can use other names or reverse the output order.
|
|
616
|
+
first, second = self.session.get_outputs()
|
|
617
|
+
if (
|
|
618
|
+
len(first.shape) != 3
|
|
619
|
+
or len(second.shape) != 3
|
|
620
|
+
or 4 not in (first.shape[-1], second.shape[-1])
|
|
621
|
+
):
|
|
622
|
+
raise ValueError(
|
|
623
|
+
"Expected class logits and cxcywh boxes with shape (1, queries, 4)."
|
|
624
|
+
)
|
|
625
|
+
self.raw_outputs = (
|
|
626
|
+
[first.name, second.name] if second.shape[-1] == 4 else [second.name, first.name]
|
|
627
|
+
)
|
|
628
|
+
else:
|
|
629
|
+
raise ValueError(
|
|
630
|
+
"Expected an ONNX detector with logits/pred_boxes or images + orig_target_sizes and labels/boxes/scores. For other formats supply detector= to TrackflowPipeline."
|
|
631
|
+
)
|
|
632
|
+
image_input = next(i for i in self.session.get_inputs() if i.name == self.input_name)
|
|
633
|
+
if len(image_input.shape) != 4 or image_input.type not in (
|
|
634
|
+
"tensor(float)",
|
|
635
|
+
"tensor(float16)",
|
|
636
|
+
):
|
|
637
|
+
raise ValueError("Expected a float32 or float16 NCHW image input.")
|
|
638
|
+
self.input_dtype = np.float16 if image_input.type == "tensor(float16)" else np.float32
|
|
639
|
+
h, w = image_input.shape[-2:]
|
|
640
|
+
if isinstance(h, int) and isinstance(w, int):
|
|
641
|
+
self.input_hw = (h, w)
|
|
642
|
+
# The converted YOLO26 graphs use the YOLOS config type but have no background logit.
|
|
643
|
+
logits_out = next((o for o in self.session.get_outputs() if o.name == "logits"), None)
|
|
644
|
+
self.softmax = cfg.get("model_type") in ("detr", "yolos", "table-transformer") and (
|
|
645
|
+
logits_out is not None and logits_out.shape[-1] == max(self.id2label, default=-1) + 2
|
|
646
|
+
)
|
|
647
|
+
|
|
648
|
+
@staticmethod
|
|
649
|
+
def _load_labels(config_path: Path | None) -> dict[int, str]:
|
|
650
|
+
if config_path is None or not config_path.is_file():
|
|
651
|
+
return dict(DEFAULT_COCO_LABELS)
|
|
652
|
+
raw: dict[str, Any] = json.loads(config_path.read_text(encoding="utf-8"))
|
|
653
|
+
id2label_raw = raw.get("id2label")
|
|
654
|
+
if not isinstance(id2label_raw, dict):
|
|
655
|
+
return dict(DEFAULT_COCO_LABELS)
|
|
656
|
+
return {int(k): str(v) for k, v in id2label_raw.items()}
|
|
657
|
+
|
|
658
|
+
@staticmethod
|
|
659
|
+
def _load_preprocess_config(
|
|
660
|
+
prep_path: Path | None,
|
|
661
|
+
) -> tuple[tuple[int, int], bool, bool, np.ndarray, np.ndarray]:
|
|
662
|
+
default_mean = np.array([0.485, 0.456, 0.406], dtype=np.float32).reshape(3, 1, 1)
|
|
663
|
+
default_std = np.array([0.229, 0.224, 0.225], dtype=np.float32).reshape(3, 1, 1)
|
|
664
|
+
if prep_path is None or not prep_path.is_file():
|
|
665
|
+
return (640, 640), True, False, default_mean, default_std
|
|
666
|
+
|
|
667
|
+
cfg: dict[str, Any] = json.loads(prep_path.read_text(encoding="utf-8"))
|
|
668
|
+
size = cfg.get("size", {})
|
|
669
|
+
if isinstance(size, int):
|
|
670
|
+
size = {"height": size, "width": size}
|
|
671
|
+
h = int(size.get("height", size.get("shortest_edge", 640)))
|
|
672
|
+
w = int(size.get("width", size.get("shortest_edge", 640)))
|
|
673
|
+
do_rescale = bool(cfg.get("do_rescale", True))
|
|
674
|
+
do_normalize = bool(cfg.get("do_normalize", False))
|
|
675
|
+
mean = np.array(cfg.get("image_mean", [0.485, 0.456, 0.406]), dtype=np.float32).reshape(
|
|
676
|
+
3, 1, 1
|
|
677
|
+
)
|
|
678
|
+
std = np.array(cfg.get("image_std", [0.229, 0.224, 0.225]), dtype=np.float32).reshape(
|
|
679
|
+
3, 1, 1
|
|
680
|
+
)
|
|
681
|
+
return (h, w), do_rescale, do_normalize, mean, std
|
|
682
|
+
|
|
683
|
+
def preprocess(self, frame_bgr: np.ndarray) -> np.ndarray:
|
|
684
|
+
"""Convert OpenCV BGR uint8 frame to NCHW float tensor."""
|
|
685
|
+
target_h, target_w = self.input_hw
|
|
686
|
+
native = native_module()
|
|
687
|
+
if native is not None:
|
|
688
|
+
resized = (
|
|
689
|
+
frame_bgr
|
|
690
|
+
if frame_bgr.shape[:2] == (target_h, target_w)
|
|
691
|
+
else cv2.resize(frame_bgr, (target_w, target_h), interpolation=cv2.INTER_LINEAR)
|
|
692
|
+
)
|
|
693
|
+
base_scale = (1.0 / 255.0) if self.do_rescale else 1.0
|
|
694
|
+
if self.do_normalize:
|
|
695
|
+
mean_rgb = self.mean.reshape(3)
|
|
696
|
+
std_rgb = self.std.reshape(3)
|
|
697
|
+
scale_t = (
|
|
698
|
+
float(base_scale / std_rgb[0]),
|
|
699
|
+
float(base_scale / std_rgb[1]),
|
|
700
|
+
float(base_scale / std_rgb[2]),
|
|
701
|
+
)
|
|
702
|
+
bias_t = (
|
|
703
|
+
float(-mean_rgb[0] / std_rgb[0]),
|
|
704
|
+
float(-mean_rgb[1] / std_rgb[1]),
|
|
705
|
+
float(-mean_rgb[2] / std_rgb[2]),
|
|
706
|
+
)
|
|
707
|
+
else:
|
|
708
|
+
scale_t = (base_scale, base_scale, base_scale)
|
|
709
|
+
bias_t = (0.0, 0.0, 0.0)
|
|
710
|
+
blob = native.bgr_to_nchw_f32(resized, scale_t, bias_t)
|
|
711
|
+
if self.input_dtype != np.float32:
|
|
712
|
+
return np.ascontiguousarray(blob, dtype=self.input_dtype)
|
|
713
|
+
return blob
|
|
714
|
+
|
|
715
|
+
scale = (1.0 / 255.0) if self.do_rescale else 1.0
|
|
716
|
+
if self.do_normalize:
|
|
717
|
+
mean_rgb = self.mean.reshape(3)
|
|
718
|
+
# cv2.dnn.blobFromImage(..., swapRB=True) swaps mean[0]/mean[2] internally,
|
|
719
|
+
# so pass mean in RGB order scaled to input uint8 domain when rescaling.
|
|
720
|
+
mean_scale = 255.0 if self.do_rescale else 1.0
|
|
721
|
+
blob_mean = (
|
|
722
|
+
float(mean_rgb[0] * mean_scale),
|
|
723
|
+
float(mean_rgb[1] * mean_scale),
|
|
724
|
+
float(mean_rgb[2] * mean_scale),
|
|
725
|
+
)
|
|
726
|
+
else:
|
|
727
|
+
blob_mean = (0.0, 0.0, 0.0)
|
|
728
|
+
blob = cv2.dnn.blobFromImage(
|
|
729
|
+
frame_bgr,
|
|
730
|
+
scalefactor=scale,
|
|
731
|
+
size=(target_w, target_h),
|
|
732
|
+
mean=blob_mean,
|
|
733
|
+
swapRB=True,
|
|
734
|
+
crop=False,
|
|
735
|
+
)
|
|
736
|
+
if self.do_normalize:
|
|
737
|
+
blob /= self.std.reshape(1, 3, 1, 1)
|
|
738
|
+
if self.input_dtype != np.float32:
|
|
739
|
+
return np.ascontiguousarray(blob, dtype=self.input_dtype)
|
|
740
|
+
return blob
|
|
741
|
+
|
|
742
|
+
def detect(self, frame_bgr: np.ndarray, threshold: float | None = None) -> list[Detection]:
|
|
743
|
+
"""Run object detection on a single BGR frame."""
|
|
744
|
+
orig_h, orig_w = frame_bgr.shape[:2]
|
|
745
|
+
cutoff = self.threshold if threshold is None else threshold
|
|
746
|
+
if self.deployed:
|
|
747
|
+
# Upstream DEIMv2 / RT-DETRv4 deployment graphs take a black-letterboxed RGB
|
|
748
|
+
# image and emit xyxy in the coordinate system supplied via orig_target_sizes.
|
|
749
|
+
h, w = self.input_hw
|
|
750
|
+
padded, placement = _letterbox(frame_bgr, self.input_hw, 0)
|
|
751
|
+
labels, boxes, scores = self.session.run(
|
|
752
|
+
["labels", "boxes", "scores"],
|
|
753
|
+
{
|
|
754
|
+
"images": self.preprocess(padded),
|
|
755
|
+
"orig_target_sizes": np.array([[w, h]], dtype=np.int64),
|
|
756
|
+
},
|
|
757
|
+
)
|
|
758
|
+
return _pixel_detections(
|
|
759
|
+
labels[0],
|
|
760
|
+
_unletterbox(boxes[0], placement),
|
|
761
|
+
scores[0],
|
|
762
|
+
(orig_h, orig_w),
|
|
763
|
+
self.id2label,
|
|
764
|
+
self.allowed_classes,
|
|
765
|
+
cutoff,
|
|
766
|
+
)
|
|
767
|
+
image, placement = frame_bgr, None
|
|
768
|
+
if self.letterbox:
|
|
769
|
+
image, placement = _letterbox(frame_bgr, self.input_hw, 114)
|
|
770
|
+
tensor = self.preprocess(image)
|
|
771
|
+
logits, pred_boxes = self.session.run(self.raw_outputs, {self.input_name: tensor})
|
|
772
|
+
|
|
773
|
+
detections = postprocess_detr_outputs(
|
|
774
|
+
logits=np.asarray(logits, dtype=np.float32),
|
|
775
|
+
pred_boxes=np.asarray(pred_boxes, dtype=np.float32),
|
|
776
|
+
orig_hw=image.shape[:2],
|
|
777
|
+
id2label=self.id2label,
|
|
778
|
+
threshold=cutoff,
|
|
779
|
+
allowed_classes=self.allowed_classes,
|
|
780
|
+
softmax=self.softmax,
|
|
781
|
+
)
|
|
782
|
+
if placement is None:
|
|
783
|
+
return detections
|
|
784
|
+
restored = []
|
|
785
|
+
for det in detections:
|
|
786
|
+
x1, y1, x2, y2 = _unletterbox(det.bbox, placement)
|
|
787
|
+
x1, x2 = np.clip([x1, x2], 0.0, orig_w)
|
|
788
|
+
y1, y2 = np.clip([y1, y2], 0.0, orig_h)
|
|
789
|
+
if x2 - x1 >= 2.0 and y2 - y1 >= 2.0:
|
|
790
|
+
det.bbox = (float(x1), float(y1), float(x2), float(y2))
|
|
791
|
+
restored.append(det)
|
|
792
|
+
return restored
|
|
793
|
+
|
|
794
|
+
|
|
795
|
+
def _pixel_detections(
|
|
796
|
+
labels: np.ndarray,
|
|
797
|
+
boxes: np.ndarray,
|
|
798
|
+
scores: np.ndarray,
|
|
799
|
+
orig_hw: tuple[int, int],
|
|
800
|
+
id2label: dict[int, str],
|
|
801
|
+
allowed: set[str] | None,
|
|
802
|
+
threshold: float,
|
|
803
|
+
) -> list[Detection]:
|
|
804
|
+
h, w = orig_hw
|
|
805
|
+
detections = []
|
|
806
|
+
for i in np.flatnonzero(scores >= threshold):
|
|
807
|
+
cid = int(labels[i])
|
|
808
|
+
name = id2label.get(cid, str(cid))
|
|
809
|
+
if allowed is not None and _class_key(name) not in allowed:
|
|
810
|
+
continue
|
|
811
|
+
x1, y1, x2, y2 = np.clip(boxes[i], 0, [w, h, w, h]).tolist()
|
|
812
|
+
if x2 - x1 >= 2 and y2 - y1 >= 2:
|
|
813
|
+
detections.append(Detection((x1, y1, x2, y2), float(scores[i]), cid, name))
|
|
814
|
+
detections.sort(key=lambda d: d.confidence, reverse=True)
|
|
815
|
+
return _nms_class_aware(detections, 0.65)
|
|
816
|
+
|
|
817
|
+
|
|
818
|
+
class TransformersDetector:
|
|
819
|
+
"""Use a native Transformers object-detection checkpoint and its own image processor."""
|
|
820
|
+
|
|
821
|
+
def __init__(
|
|
822
|
+
self,
|
|
823
|
+
repo_id: str,
|
|
824
|
+
*,
|
|
825
|
+
revision: str | None,
|
|
826
|
+
device: str,
|
|
827
|
+
precision: Precision,
|
|
828
|
+
threshold: float,
|
|
829
|
+
classes: Sequence[str] | None,
|
|
830
|
+
cache_dir: str | Path | None,
|
|
831
|
+
) -> None:
|
|
832
|
+
try:
|
|
833
|
+
import torch
|
|
834
|
+
from transformers import AutoImageProcessor, AutoModelForObjectDetection
|
|
835
|
+
except ImportError as exc:
|
|
836
|
+
raise ImportError(
|
|
837
|
+
"Install 'trackflow-python[transformers]' to load native Transformers checkpoints."
|
|
838
|
+
) from exc
|
|
839
|
+
if device == "auto":
|
|
840
|
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
|
841
|
+
if device not in ("cpu", "cuda", "mps"):
|
|
842
|
+
raise ValueError("Transformers supports --device auto, cpu, cuda, or mps.")
|
|
843
|
+
if precision not in ("fp32", "fp16"):
|
|
844
|
+
raise ValueError("Transformers detectors support fp32 or fp16.")
|
|
845
|
+
self.model_name = repo_id
|
|
846
|
+
self.device = device
|
|
847
|
+
self.precision = precision
|
|
848
|
+
self.dtype = torch.float32 if precision == "fp32" else torch.float16
|
|
849
|
+
kwargs = {"revision": revision, "cache_dir": cache_dir, "trust_remote_code": False}
|
|
850
|
+
self.processor = AutoImageProcessor.from_pretrained(repo_id, **kwargs)
|
|
851
|
+
self.model = (
|
|
852
|
+
AutoModelForObjectDetection.from_pretrained(repo_id, use_safetensors=True, **kwargs)
|
|
853
|
+
.to(device=device, dtype=self.dtype)
|
|
854
|
+
.eval()
|
|
855
|
+
)
|
|
856
|
+
self.revision = revision or getattr(self.model.config, "_commit_hash", None)
|
|
857
|
+
self.active_provider = f"torch:{device}"
|
|
858
|
+
self.threshold = threshold
|
|
859
|
+
self.allowed_classes = _allowed_classes(classes)
|
|
860
|
+
|
|
861
|
+
def detect(self, frame_bgr: np.ndarray) -> list[Detection]:
|
|
862
|
+
import torch
|
|
863
|
+
|
|
864
|
+
hw = frame_bgr.shape[:2]
|
|
865
|
+
rgb = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB)
|
|
866
|
+
with torch.inference_mode():
|
|
867
|
+
inputs = self.processor(images=rgb, return_tensors="pt").to(self.device, self.dtype)
|
|
868
|
+
output = self.model(**inputs)
|
|
869
|
+
result = self.processor.post_process_object_detection(
|
|
870
|
+
output, threshold=self.threshold, target_sizes=[hw]
|
|
871
|
+
)[0]
|
|
872
|
+
return _pixel_detections(
|
|
873
|
+
result["labels"].cpu().numpy(),
|
|
874
|
+
result["boxes"].float().cpu().numpy(),
|
|
875
|
+
result["scores"].float().cpu().numpy(),
|
|
876
|
+
hw,
|
|
877
|
+
self.model.config.id2label,
|
|
878
|
+
self.allowed_classes,
|
|
879
|
+
self.threshold,
|
|
880
|
+
)
|
|
881
|
+
|
|
882
|
+
|
|
883
|
+
def create_detector(
|
|
884
|
+
model: str | Path = "rtdetr-v2-r18",
|
|
885
|
+
*,
|
|
886
|
+
precision: Precision = "fp32",
|
|
887
|
+
device: str = "auto",
|
|
888
|
+
threshold: float = 0.45,
|
|
889
|
+
classes: Sequence[str] | None = ("person",),
|
|
890
|
+
cache_dir: str | Path | None = None,
|
|
891
|
+
) -> Detector:
|
|
892
|
+
"""Load a preset, compatible ONNX graph/repository, or hf:owner/repo Transformers checkpoint."""
|
|
893
|
+
model = str(model)
|
|
894
|
+
spec = MODEL_REGISTRY.get(model)
|
|
895
|
+
if model.startswith("hf:") or (spec and spec.backend == "transformers"):
|
|
896
|
+
return TransformersDetector(
|
|
897
|
+
spec.repo_id if spec else model.removeprefix("hf:"),
|
|
898
|
+
revision=spec.revision if spec else None,
|
|
899
|
+
device=device,
|
|
900
|
+
precision=precision,
|
|
901
|
+
threshold=threshold,
|
|
902
|
+
classes=classes,
|
|
903
|
+
cache_dir=cache_dir,
|
|
904
|
+
)
|
|
905
|
+
return OnnxDetrDetector(
|
|
906
|
+
model,
|
|
907
|
+
precision=precision,
|
|
908
|
+
device=device,
|
|
909
|
+
threshold=threshold,
|
|
910
|
+
classes=classes,
|
|
911
|
+
cache_dir=cache_dir,
|
|
912
|
+
)
|