Upload folder using huggingface_hub
Browse files- README.md +23 -0
- chute_config.yml +19 -0
- miner.py +565 -0
- weights.onnx +3 -0
README.md
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
tags:
|
| 3 |
+
- element_type:detect
|
| 4 |
+
- model:yolov11-nano
|
| 5 |
+
- object:person
|
| 6 |
+
manako:
|
| 7 |
+
description: Roboflow - generated by element_trainer service to detect person
|
| 8 |
+
source: element_trainer/800e961b-eb64-4380-880c-f1ed67abd563
|
| 9 |
+
prompt_hints: null
|
| 10 |
+
input_payload:
|
| 11 |
+
- name: frame
|
| 12 |
+
type: image
|
| 13 |
+
description: RGB frame
|
| 14 |
+
output_payload:
|
| 15 |
+
- name: detections
|
| 16 |
+
type: detections
|
| 17 |
+
description: List of detections
|
| 18 |
+
evaluation_score: null
|
| 19 |
+
last_benchmark:
|
| 20 |
+
type: synthetic_fixed
|
| 21 |
+
ran_at: '2026-03-06T02:20:51.927289Z'
|
| 22 |
+
result_path: benchmark/synthetic/1ada5b1e-38b8-4bdc-967a-d8a27b0e6afb.json
|
| 23 |
+
---
|
chute_config.yml
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Image:
|
| 2 |
+
from_base: parachutes/python:3.12
|
| 3 |
+
run_command:
|
| 4 |
+
- pip install --upgrade setuptools wheel
|
| 5 |
+
- pip install 'numpy>=1.23' 'onnxruntime-gpu[cuda,cudnn]>=1.16' 'opencv-python>=4.7' 'pillow>=9.5' 'huggingface_hub>=0.19.4' 'pydantic>=2.0' 'pyyaml>=6.0' 'aiohttp>=3.9'
|
| 6 |
+
- pip install torch torchvision
|
| 7 |
+
|
| 8 |
+
NodeSelector:
|
| 9 |
+
gpu_count: 1
|
| 10 |
+
min_vram_gb_per_gpu: 24
|
| 11 |
+
min_memory_gb: 32
|
| 12 |
+
min_cpu_count: 32
|
| 13 |
+
|
| 14 |
+
Chute:
|
| 15 |
+
timeout_seconds: 900
|
| 16 |
+
concurrency: 4
|
| 17 |
+
max_instances: 5
|
| 18 |
+
scaling_threshold: 0.5
|
| 19 |
+
shutdown_after_seconds: 288000
|
miner.py
ADDED
|
@@ -0,0 +1,565 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import math
|
| 3 |
+
|
| 4 |
+
import cv2
|
| 5 |
+
import numpy as np
|
| 6 |
+
import onnxruntime as ort
|
| 7 |
+
from numpy import ndarray
|
| 8 |
+
from pydantic import BaseModel
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class BoundingBox(BaseModel):
|
| 12 |
+
x1: int
|
| 13 |
+
y1: int
|
| 14 |
+
x2: int
|
| 15 |
+
y2: int
|
| 16 |
+
cls_id: int
|
| 17 |
+
conf: float
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class TVFrameResult(BaseModel):
|
| 21 |
+
frame_id: int
|
| 22 |
+
boxes: list[BoundingBox]
|
| 23 |
+
keypoints: list[tuple[int, int]]
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class Miner:
|
| 27 |
+
def __init__(self, path_hf_repo: Path) -> None:
|
| 28 |
+
model_path = path_hf_repo / "weights.onnx"
|
| 29 |
+
self.class_names = ['person']
|
| 30 |
+
print("ORT version:", ort.__version__)
|
| 31 |
+
|
| 32 |
+
try:
|
| 33 |
+
ort.preload_dlls()
|
| 34 |
+
print("✅ onnxruntime.preload_dlls() success")
|
| 35 |
+
except Exception as e:
|
| 36 |
+
print(f"⚠️ preload_dlls failed: {e}")
|
| 37 |
+
|
| 38 |
+
print("ORT available providers BEFORE session:", ort.get_available_providers())
|
| 39 |
+
|
| 40 |
+
sess_options = ort.SessionOptions()
|
| 41 |
+
sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
|
| 42 |
+
|
| 43 |
+
try:
|
| 44 |
+
self.session = ort.InferenceSession(
|
| 45 |
+
str(model_path),
|
| 46 |
+
sess_options=sess_options,
|
| 47 |
+
providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
|
| 48 |
+
)
|
| 49 |
+
print("✅ Created ORT session with preferred CUDA provider list")
|
| 50 |
+
except Exception as e:
|
| 51 |
+
print(f"⚠️ CUDA session creation failed, falling back to CPU: {e}")
|
| 52 |
+
self.session = ort.InferenceSession(
|
| 53 |
+
str(model_path),
|
| 54 |
+
sess_options=sess_options,
|
| 55 |
+
providers=["CPUExecutionProvider"],
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
print("ORT session providers:", self.session.get_providers())
|
| 59 |
+
|
| 60 |
+
for inp in self.session.get_inputs():
|
| 61 |
+
print("INPUT:", inp.name, inp.shape, inp.type)
|
| 62 |
+
|
| 63 |
+
for out in self.session.get_outputs():
|
| 64 |
+
print("OUTPUT:", out.name, out.shape, out.type)
|
| 65 |
+
|
| 66 |
+
self.input_name = self.session.get_inputs()[0].name
|
| 67 |
+
self.output_names = [output.name for output in self.session.get_outputs()]
|
| 68 |
+
self.input_shape = self.session.get_inputs()[0].shape
|
| 69 |
+
|
| 70 |
+
# Your export is fixed-size 1280, but we still read actual ONNX input shape first.
|
| 71 |
+
self.input_height = self._safe_dim(self.input_shape[2], default=960)
|
| 72 |
+
self.input_width = self._safe_dim(self.input_shape[3], default=960)
|
| 73 |
+
|
| 74 |
+
self.conf_thres = 0.01
|
| 75 |
+
self.iou_thres = 0.6
|
| 76 |
+
self.max_det = 300
|
| 77 |
+
self.use_tta = True
|
| 78 |
+
|
| 79 |
+
print(f"✅ ONNX model loaded from: {model_path}")
|
| 80 |
+
print(f"✅ ONNX providers: {self.session.get_providers()}")
|
| 81 |
+
print(f"✅ ONNX input: name={self.input_name}, shape={self.input_shape}")
|
| 82 |
+
|
| 83 |
+
def __repr__(self) -> str:
|
| 84 |
+
return (
|
| 85 |
+
f"ONNXRuntime(session={type(self.session).__name__}, "
|
| 86 |
+
f"providers={self.session.get_providers()})"
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
@staticmethod
|
| 90 |
+
def _safe_dim(value, default: int) -> int:
|
| 91 |
+
return value if isinstance(value, int) and value > 0 else default
|
| 92 |
+
|
| 93 |
+
def _letterbox(
|
| 94 |
+
self,
|
| 95 |
+
image: ndarray,
|
| 96 |
+
new_shape: tuple[int, int],
|
| 97 |
+
color=(114, 114, 114),
|
| 98 |
+
) -> tuple[ndarray, float, tuple[float, float]]:
|
| 99 |
+
"""
|
| 100 |
+
Resize with unchanged aspect ratio and pad to target shape.
|
| 101 |
+
Returns:
|
| 102 |
+
padded_image,
|
| 103 |
+
ratio,
|
| 104 |
+
(pad_w, pad_h) # half-padding
|
| 105 |
+
"""
|
| 106 |
+
h, w = image.shape[:2]
|
| 107 |
+
new_w, new_h = new_shape
|
| 108 |
+
|
| 109 |
+
ratio = min(new_w / w, new_h / h)
|
| 110 |
+
resized_w = int(round(w * ratio))
|
| 111 |
+
resized_h = int(round(h * ratio))
|
| 112 |
+
|
| 113 |
+
if (resized_w, resized_h) != (w, h):
|
| 114 |
+
interp = cv2.INTER_CUBIC if ratio > 1.0 else cv2.INTER_LINEAR
|
| 115 |
+
image = cv2.resize(image, (resized_w, resized_h), interpolation=interp)
|
| 116 |
+
|
| 117 |
+
dw = new_w - resized_w
|
| 118 |
+
dh = new_h - resized_h
|
| 119 |
+
dw /= 2.0
|
| 120 |
+
dh /= 2.0
|
| 121 |
+
|
| 122 |
+
left = int(round(dw - 0.1))
|
| 123 |
+
right = int(round(dw + 0.1))
|
| 124 |
+
top = int(round(dh - 0.1))
|
| 125 |
+
bottom = int(round(dh + 0.1))
|
| 126 |
+
|
| 127 |
+
padded = cv2.copyMakeBorder(
|
| 128 |
+
image,
|
| 129 |
+
top,
|
| 130 |
+
bottom,
|
| 131 |
+
left,
|
| 132 |
+
right,
|
| 133 |
+
borderType=cv2.BORDER_CONSTANT,
|
| 134 |
+
value=color,
|
| 135 |
+
)
|
| 136 |
+
return padded, ratio, (dw, dh)
|
| 137 |
+
|
| 138 |
+
def _preprocess(
|
| 139 |
+
self, image: ndarray
|
| 140 |
+
) -> tuple[np.ndarray, float, tuple[float, float], tuple[int, int]]:
|
| 141 |
+
"""
|
| 142 |
+
Preprocess for fixed-size ONNX export:
|
| 143 |
+
- enhance image quality (CLAHE, denoise, sharpen)
|
| 144 |
+
- letterbox to model input size
|
| 145 |
+
- BGR -> RGB
|
| 146 |
+
- normalize to [0,1]
|
| 147 |
+
- HWC -> NCHW float32
|
| 148 |
+
"""
|
| 149 |
+
orig_h, orig_w = image.shape[:2]
|
| 150 |
+
|
| 151 |
+
img, ratio, pad = self._letterbox(
|
| 152 |
+
image, (self.input_width, self.input_height)
|
| 153 |
+
)
|
| 154 |
+
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
| 155 |
+
img = img.astype(np.float32) / 255.0
|
| 156 |
+
img = np.transpose(img, (2, 0, 1))[None, ...]
|
| 157 |
+
img = np.ascontiguousarray(img, dtype=np.float32)
|
| 158 |
+
|
| 159 |
+
return img, ratio, pad, (orig_w, orig_h)
|
| 160 |
+
|
| 161 |
+
@staticmethod
|
| 162 |
+
def _clip_boxes(boxes: np.ndarray, image_size: tuple[int, int]) -> np.ndarray:
|
| 163 |
+
w, h = image_size
|
| 164 |
+
boxes[:, 0] = np.clip(boxes[:, 0], 0, w - 1)
|
| 165 |
+
boxes[:, 1] = np.clip(boxes[:, 1], 0, h - 1)
|
| 166 |
+
boxes[:, 2] = np.clip(boxes[:, 2], 0, w - 1)
|
| 167 |
+
boxes[:, 3] = np.clip(boxes[:, 3], 0, h - 1)
|
| 168 |
+
return boxes
|
| 169 |
+
|
| 170 |
+
@staticmethod
|
| 171 |
+
def _xywh_to_xyxy(boxes: np.ndarray) -> np.ndarray:
|
| 172 |
+
out = np.empty_like(boxes)
|
| 173 |
+
out[:, 0] = boxes[:, 0] - boxes[:, 2] / 2.0
|
| 174 |
+
out[:, 1] = boxes[:, 1] - boxes[:, 3] / 2.0
|
| 175 |
+
out[:, 2] = boxes[:, 0] + boxes[:, 2] / 2.0
|
| 176 |
+
out[:, 3] = boxes[:, 1] + boxes[:, 3] / 2.0
|
| 177 |
+
return out
|
| 178 |
+
|
| 179 |
+
def _soft_nms(
|
| 180 |
+
self,
|
| 181 |
+
boxes: np.ndarray,
|
| 182 |
+
scores: np.ndarray,
|
| 183 |
+
sigma: float = 0.5,
|
| 184 |
+
score_thresh: float = 0.01,
|
| 185 |
+
) -> tuple[np.ndarray, np.ndarray]:
|
| 186 |
+
"""
|
| 187 |
+
Soft-NMS: Gaussian decay of overlapping scores instead of hard removal.
|
| 188 |
+
Returns (kept_original_indices, updated_scores).
|
| 189 |
+
"""
|
| 190 |
+
N = len(boxes)
|
| 191 |
+
if N == 0:
|
| 192 |
+
return np.array([], dtype=np.intp), np.array([], dtype=np.float32)
|
| 193 |
+
|
| 194 |
+
boxes = boxes.astype(np.float32, copy=True)
|
| 195 |
+
scores = scores.astype(np.float32, copy=True)
|
| 196 |
+
order = np.arange(N)
|
| 197 |
+
|
| 198 |
+
for i in range(N):
|
| 199 |
+
max_pos = i + int(np.argmax(scores[i:]))
|
| 200 |
+
boxes[[i, max_pos]] = boxes[[max_pos, i]]
|
| 201 |
+
scores[[i, max_pos]] = scores[[max_pos, i]]
|
| 202 |
+
order[[i, max_pos]] = order[[max_pos, i]]
|
| 203 |
+
|
| 204 |
+
if i + 1 >= N:
|
| 205 |
+
break
|
| 206 |
+
|
| 207 |
+
xx1 = np.maximum(boxes[i, 0], boxes[i + 1:, 0])
|
| 208 |
+
yy1 = np.maximum(boxes[i, 1], boxes[i + 1:, 1])
|
| 209 |
+
xx2 = np.minimum(boxes[i, 2], boxes[i + 1:, 2])
|
| 210 |
+
yy2 = np.minimum(boxes[i, 3], boxes[i + 1:, 3])
|
| 211 |
+
inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)
|
| 212 |
+
|
| 213 |
+
area_i = max(0.0, float(
|
| 214 |
+
(boxes[i, 2] - boxes[i, 0]) * (boxes[i, 3] - boxes[i, 1])
|
| 215 |
+
))
|
| 216 |
+
areas_j = (
|
| 217 |
+
np.maximum(0.0, boxes[i + 1:, 2] - boxes[i + 1:, 0])
|
| 218 |
+
* np.maximum(0.0, boxes[i + 1:, 3] - boxes[i + 1:, 1])
|
| 219 |
+
)
|
| 220 |
+
iou = inter / (area_i + areas_j - inter + 1e-7)
|
| 221 |
+
scores[i + 1:] *= np.exp(-(iou ** 2) / sigma)
|
| 222 |
+
|
| 223 |
+
mask = scores > score_thresh
|
| 224 |
+
return order[mask], scores[mask]
|
| 225 |
+
|
| 226 |
+
@staticmethod
|
| 227 |
+
def _hard_nms(
|
| 228 |
+
boxes: np.ndarray,
|
| 229 |
+
scores: np.ndarray,
|
| 230 |
+
iou_thresh: float,
|
| 231 |
+
) -> np.ndarray:
|
| 232 |
+
"""
|
| 233 |
+
Standard NMS: keep one box per overlapping cluster (the one with highest score).
|
| 234 |
+
Returns indices of kept boxes (into the boxes/scores arrays).
|
| 235 |
+
"""
|
| 236 |
+
N = len(boxes)
|
| 237 |
+
if N == 0:
|
| 238 |
+
return np.array([], dtype=np.intp)
|
| 239 |
+
boxes = np.asarray(boxes, dtype=np.float32)
|
| 240 |
+
scores = np.asarray(scores, dtype=np.float32)
|
| 241 |
+
order = np.argsort(scores)[::-1]
|
| 242 |
+
keep: list[int] = []
|
| 243 |
+
suppressed = np.zeros(N, dtype=bool)
|
| 244 |
+
for i in range(N):
|
| 245 |
+
idx = order[i]
|
| 246 |
+
if suppressed[idx]:
|
| 247 |
+
continue
|
| 248 |
+
keep.append(idx)
|
| 249 |
+
bi = boxes[idx]
|
| 250 |
+
for k in range(i + 1, N):
|
| 251 |
+
jdx = order[k]
|
| 252 |
+
if suppressed[jdx]:
|
| 253 |
+
continue
|
| 254 |
+
bj = boxes[jdx]
|
| 255 |
+
xx1 = max(bi[0], bj[0])
|
| 256 |
+
yy1 = max(bi[1], bj[1])
|
| 257 |
+
xx2 = min(bi[2], bj[2])
|
| 258 |
+
yy2 = min(bi[3], bj[3])
|
| 259 |
+
inter = max(0.0, xx2 - xx1) * max(0.0, yy2 - yy1)
|
| 260 |
+
area_i = (bi[2] - bi[0]) * (bi[3] - bi[1])
|
| 261 |
+
area_j = (bj[2] - bj[0]) * (bj[3] - bj[1])
|
| 262 |
+
iou = inter / (area_i + area_j - inter + 1e-7)
|
| 263 |
+
if iou > iou_thresh:
|
| 264 |
+
suppressed[jdx] = True
|
| 265 |
+
return np.array(keep)
|
| 266 |
+
|
| 267 |
+
@staticmethod
|
| 268 |
+
def _max_score_per_cluster(
|
| 269 |
+
coords: np.ndarray,
|
| 270 |
+
scores: np.ndarray,
|
| 271 |
+
keep_indices: np.ndarray,
|
| 272 |
+
iou_thresh: float,
|
| 273 |
+
) -> np.ndarray:
|
| 274 |
+
"""
|
| 275 |
+
For each kept box, return the max original score among itself and any
|
| 276 |
+
box that overlaps it with IOU >= iou_thresh (so TTA cluster keeps best conf).
|
| 277 |
+
"""
|
| 278 |
+
n_keep = len(keep_indices)
|
| 279 |
+
if n_keep == 0:
|
| 280 |
+
return np.array([], dtype=np.float32)
|
| 281 |
+
out = np.empty(n_keep, dtype=np.float32)
|
| 282 |
+
coords = np.asarray(coords, dtype=np.float32)
|
| 283 |
+
scores = np.asarray(scores, dtype=np.float32)
|
| 284 |
+
for i in range(n_keep):
|
| 285 |
+
idx = keep_indices[i]
|
| 286 |
+
bi = coords[idx]
|
| 287 |
+
xx1 = np.maximum(bi[0], coords[:, 0])
|
| 288 |
+
yy1 = np.maximum(bi[1], coords[:, 1])
|
| 289 |
+
xx2 = np.minimum(bi[2], coords[:, 2])
|
| 290 |
+
yy2 = np.minimum(bi[3], coords[:, 3])
|
| 291 |
+
inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)
|
| 292 |
+
area_i = (bi[2] - bi[0]) * (bi[3] - bi[1])
|
| 293 |
+
areas_j = (coords[:, 2] - coords[:, 0]) * (coords[:, 3] - coords[:, 1])
|
| 294 |
+
iou = inter / (area_i + areas_j - inter + 1e-7)
|
| 295 |
+
in_cluster = iou >= iou_thresh
|
| 296 |
+
out[i] = float(np.max(scores[in_cluster]))
|
| 297 |
+
return out
|
| 298 |
+
|
| 299 |
+
def _decode_final_dets(
|
| 300 |
+
self,
|
| 301 |
+
preds: np.ndarray,
|
| 302 |
+
ratio: float,
|
| 303 |
+
pad: tuple[float, float],
|
| 304 |
+
orig_size: tuple[int, int],
|
| 305 |
+
apply_optional_dedup: bool = False,
|
| 306 |
+
) -> list[BoundingBox]:
|
| 307 |
+
"""
|
| 308 |
+
Primary path:
|
| 309 |
+
expected output rows like [x1, y1, x2, y2, conf, cls_id]
|
| 310 |
+
in letterboxed input coordinates.
|
| 311 |
+
"""
|
| 312 |
+
if preds.ndim == 3 and preds.shape[0] == 1:
|
| 313 |
+
preds = preds[0]
|
| 314 |
+
|
| 315 |
+
if preds.ndim != 2 or preds.shape[1] < 6:
|
| 316 |
+
raise ValueError(f"Unexpected ONNX final-det output shape: {preds.shape}")
|
| 317 |
+
|
| 318 |
+
boxes = preds[:, :4].astype(np.float32)
|
| 319 |
+
scores = preds[:, 4].astype(np.float32)
|
| 320 |
+
cls_ids = preds[:, 5].astype(np.int32)
|
| 321 |
+
|
| 322 |
+
keep = scores >= self.conf_thres
|
| 323 |
+
boxes = boxes[keep]
|
| 324 |
+
scores = scores[keep]
|
| 325 |
+
cls_ids = cls_ids[keep]
|
| 326 |
+
|
| 327 |
+
if len(boxes) == 0:
|
| 328 |
+
return []
|
| 329 |
+
|
| 330 |
+
pad_w, pad_h = pad
|
| 331 |
+
orig_w, orig_h = orig_size
|
| 332 |
+
|
| 333 |
+
# reverse letterbox
|
| 334 |
+
boxes[:, [0, 2]] -= pad_w
|
| 335 |
+
boxes[:, [1, 3]] -= pad_h
|
| 336 |
+
boxes /= ratio
|
| 337 |
+
boxes = self._clip_boxes(boxes, (orig_w, orig_h))
|
| 338 |
+
|
| 339 |
+
if apply_optional_dedup and len(boxes) > 1:
|
| 340 |
+
keep_idx, scores = self._soft_nms(boxes, scores)
|
| 341 |
+
boxes = boxes[keep_idx]
|
| 342 |
+
cls_ids = cls_ids[keep_idx]
|
| 343 |
+
|
| 344 |
+
results: list[BoundingBox] = []
|
| 345 |
+
for box, conf, cls_id in zip(boxes, scores, cls_ids):
|
| 346 |
+
x1, y1, x2, y2 = box.tolist()
|
| 347 |
+
|
| 348 |
+
if x2 <= x1 or y2 <= y1:
|
| 349 |
+
continue
|
| 350 |
+
|
| 351 |
+
results.append(
|
| 352 |
+
BoundingBox(
|
| 353 |
+
x1=int(math.floor(x1)),
|
| 354 |
+
y1=int(math.floor(y1)),
|
| 355 |
+
x2=int(math.ceil(x2)),
|
| 356 |
+
y2=int(math.ceil(y2)),
|
| 357 |
+
cls_id=int(cls_id),
|
| 358 |
+
conf=float(conf),
|
| 359 |
+
)
|
| 360 |
+
)
|
| 361 |
+
|
| 362 |
+
return results
|
| 363 |
+
|
| 364 |
+
def _decode_raw_yolo(
|
| 365 |
+
self,
|
| 366 |
+
preds: np.ndarray,
|
| 367 |
+
ratio: float,
|
| 368 |
+
pad: tuple[float, float],
|
| 369 |
+
orig_size: tuple[int, int],
|
| 370 |
+
) -> list[BoundingBox]:
|
| 371 |
+
"""
|
| 372 |
+
Fallback path for raw YOLO predictions.
|
| 373 |
+
Supports common layouts:
|
| 374 |
+
- [1, C, N]
|
| 375 |
+
- [1, N, C]
|
| 376 |
+
"""
|
| 377 |
+
if preds.ndim != 3:
|
| 378 |
+
raise ValueError(f"Unexpected raw ONNX output shape: {preds.shape}")
|
| 379 |
+
|
| 380 |
+
if preds.shape[0] != 1:
|
| 381 |
+
raise ValueError(f"Unexpected batch dimension in raw output: {preds.shape}")
|
| 382 |
+
|
| 383 |
+
preds = preds[0]
|
| 384 |
+
|
| 385 |
+
# Normalize to [N, C]
|
| 386 |
+
if preds.shape[0] <= 16 and preds.shape[1] > preds.shape[0]:
|
| 387 |
+
preds = preds.T
|
| 388 |
+
|
| 389 |
+
if preds.ndim != 2 or preds.shape[1] < 5:
|
| 390 |
+
raise ValueError(f"Unexpected normalized raw output shape: {preds.shape}")
|
| 391 |
+
|
| 392 |
+
boxes_xywh = preds[:, :4].astype(np.float32)
|
| 393 |
+
cls_part = preds[:, 4:].astype(np.float32)
|
| 394 |
+
|
| 395 |
+
if cls_part.shape[1] == 1:
|
| 396 |
+
scores = cls_part[:, 0]
|
| 397 |
+
cls_ids = np.zeros(len(scores), dtype=np.int32)
|
| 398 |
+
else:
|
| 399 |
+
cls_ids = np.argmax(cls_part, axis=1).astype(np.int32)
|
| 400 |
+
scores = cls_part[np.arange(len(cls_part)), cls_ids]
|
| 401 |
+
|
| 402 |
+
keep = scores >= self.conf_thres
|
| 403 |
+
boxes_xywh = boxes_xywh[keep]
|
| 404 |
+
scores = scores[keep]
|
| 405 |
+
cls_ids = cls_ids[keep]
|
| 406 |
+
|
| 407 |
+
if len(boxes_xywh) == 0:
|
| 408 |
+
return []
|
| 409 |
+
|
| 410 |
+
boxes = self._xywh_to_xyxy(boxes_xywh)
|
| 411 |
+
keep_idx, scores = self._soft_nms(boxes, scores)
|
| 412 |
+
keep_idx = keep_idx[: self.max_det]
|
| 413 |
+
scores = scores[: self.max_det]
|
| 414 |
+
|
| 415 |
+
boxes = boxes[keep_idx]
|
| 416 |
+
cls_ids = cls_ids[keep_idx]
|
| 417 |
+
|
| 418 |
+
pad_w, pad_h = pad
|
| 419 |
+
orig_w, orig_h = orig_size
|
| 420 |
+
|
| 421 |
+
boxes[:, [0, 2]] -= pad_w
|
| 422 |
+
boxes[:, [1, 3]] -= pad_h
|
| 423 |
+
boxes /= ratio
|
| 424 |
+
boxes = self._clip_boxes(boxes, (orig_w, orig_h))
|
| 425 |
+
|
| 426 |
+
results: list[BoundingBox] = []
|
| 427 |
+
for box, conf, cls_id in zip(boxes, scores, cls_ids):
|
| 428 |
+
x1, y1, x2, y2 = box.tolist()
|
| 429 |
+
|
| 430 |
+
if x2 <= x1 or y2 <= y1:
|
| 431 |
+
continue
|
| 432 |
+
|
| 433 |
+
results.append(
|
| 434 |
+
BoundingBox(
|
| 435 |
+
x1=int(math.floor(x1)),
|
| 436 |
+
y1=int(math.floor(y1)),
|
| 437 |
+
x2=int(math.ceil(x2)),
|
| 438 |
+
y2=int(math.ceil(y2)),
|
| 439 |
+
cls_id=int(cls_id),
|
| 440 |
+
conf=float(conf),
|
| 441 |
+
)
|
| 442 |
+
)
|
| 443 |
+
|
| 444 |
+
return results
|
| 445 |
+
|
| 446 |
+
def _postprocess(
|
| 447 |
+
self,
|
| 448 |
+
output: np.ndarray,
|
| 449 |
+
ratio: float,
|
| 450 |
+
pad: tuple[float, float],
|
| 451 |
+
orig_size: tuple[int, int],
|
| 452 |
+
) -> list[BoundingBox]:
|
| 453 |
+
"""
|
| 454 |
+
Prefer final detections first.
|
| 455 |
+
Fallback to raw decode only if needed.
|
| 456 |
+
"""
|
| 457 |
+
# final detections: [N,6]
|
| 458 |
+
if output.ndim == 2 and output.shape[1] >= 6:
|
| 459 |
+
return self._decode_final_dets(output, ratio, pad, orig_size)
|
| 460 |
+
|
| 461 |
+
# final detections: [1,N,6]
|
| 462 |
+
if output.ndim == 3 and output.shape[0] == 1 and output.shape[2] == 6:
|
| 463 |
+
return self._decode_final_dets(output, ratio, pad, orig_size)
|
| 464 |
+
|
| 465 |
+
# fallback raw decode
|
| 466 |
+
return self._decode_raw_yolo(output, ratio, pad, orig_size)
|
| 467 |
+
|
| 468 |
+
def _predict_single(self, image: np.ndarray) -> list[BoundingBox]:
|
| 469 |
+
if image is None:
|
| 470 |
+
raise ValueError("Input image is None")
|
| 471 |
+
if not isinstance(image, np.ndarray):
|
| 472 |
+
raise TypeError(f"Input is not numpy array: {type(image)}")
|
| 473 |
+
if image.ndim != 3:
|
| 474 |
+
raise ValueError(f"Expected HWC image, got shape={image.shape}")
|
| 475 |
+
if image.shape[0] <= 0 or image.shape[1] <= 0:
|
| 476 |
+
raise ValueError(f"Invalid image shape={image.shape}")
|
| 477 |
+
if image.shape[2] != 3:
|
| 478 |
+
raise ValueError(f"Expected 3 channels, got shape={image.shape}")
|
| 479 |
+
|
| 480 |
+
if image.dtype != np.uint8:
|
| 481 |
+
image = image.astype(np.uint8)
|
| 482 |
+
|
| 483 |
+
input_tensor, ratio, pad, orig_size = self._preprocess(image)
|
| 484 |
+
|
| 485 |
+
expected_shape = (1, 3, self.input_height, self.input_width)
|
| 486 |
+
if input_tensor.shape != expected_shape:
|
| 487 |
+
raise ValueError(
|
| 488 |
+
f"Bad input tensor shape={input_tensor.shape}, expected={expected_shape}"
|
| 489 |
+
)
|
| 490 |
+
|
| 491 |
+
outputs = self.session.run(self.output_names, {self.input_name: input_tensor})
|
| 492 |
+
det_output = outputs[0]
|
| 493 |
+
return self._postprocess(det_output, ratio, pad, orig_size)
|
| 494 |
+
|
| 495 |
+
def _predict_tta(self, image: np.ndarray) -> list[BoundingBox]:
|
| 496 |
+
"""Horizontal-flip TTA: merge original + flipped via hard NMS."""
|
| 497 |
+
boxes_orig = self._predict_single(image)
|
| 498 |
+
|
| 499 |
+
flipped = cv2.flip(image, 1)
|
| 500 |
+
boxes_flip = self._predict_single(flipped)
|
| 501 |
+
|
| 502 |
+
w = image.shape[1]
|
| 503 |
+
boxes_flip = [
|
| 504 |
+
BoundingBox(
|
| 505 |
+
x1=w - b.x2, y1=b.y1, x2=w - b.x1, y2=b.y2,
|
| 506 |
+
cls_id=b.cls_id, conf=b.conf,
|
| 507 |
+
)
|
| 508 |
+
for b in boxes_flip
|
| 509 |
+
]
|
| 510 |
+
|
| 511 |
+
all_boxes = boxes_orig + boxes_flip
|
| 512 |
+
if len(all_boxes) == 0:
|
| 513 |
+
return []
|
| 514 |
+
|
| 515 |
+
coords = np.array(
|
| 516 |
+
[[b.x1, b.y1, b.x2, b.y2] for b in all_boxes], dtype=np.float32
|
| 517 |
+
)
|
| 518 |
+
scores = np.array([b.conf for b in all_boxes], dtype=np.float32)
|
| 519 |
+
|
| 520 |
+
hard_keep = self._hard_nms(coords, scores, self.iou_thres)
|
| 521 |
+
if len(hard_keep) == 0:
|
| 522 |
+
return []
|
| 523 |
+
|
| 524 |
+
# _hard_nms already orders kept indices by descending score.
|
| 525 |
+
hard_keep = hard_keep[: self.max_det]
|
| 526 |
+
|
| 527 |
+
return [
|
| 528 |
+
BoundingBox(
|
| 529 |
+
x1=all_boxes[i].x1,
|
| 530 |
+
y1=all_boxes[i].y1,
|
| 531 |
+
x2=all_boxes[i].x2,
|
| 532 |
+
y2=all_boxes[i].y2,
|
| 533 |
+
cls_id=all_boxes[i].cls_id,
|
| 534 |
+
conf=float(scores[i]),
|
| 535 |
+
)
|
| 536 |
+
for i in hard_keep
|
| 537 |
+
]
|
| 538 |
+
|
| 539 |
+
def predict_batch(
|
| 540 |
+
self,
|
| 541 |
+
batch_images: list[ndarray],
|
| 542 |
+
offset: int,
|
| 543 |
+
n_keypoints: int,
|
| 544 |
+
) -> list[TVFrameResult]:
|
| 545 |
+
results: list[TVFrameResult] = []
|
| 546 |
+
|
| 547 |
+
for frame_number_in_batch, image in enumerate(batch_images):
|
| 548 |
+
try:
|
| 549 |
+
if self.use_tta:
|
| 550 |
+
boxes = self._predict_tta(image)
|
| 551 |
+
else:
|
| 552 |
+
boxes = self._predict_single(image)
|
| 553 |
+
except Exception as e:
|
| 554 |
+
print(f"⚠️ Inference failed for frame {offset + frame_number_in_batch}: {e}")
|
| 555 |
+
boxes = []
|
| 556 |
+
|
| 557 |
+
results.append(
|
| 558 |
+
TVFrameResult(
|
| 559 |
+
frame_id=offset + frame_number_in_batch,
|
| 560 |
+
boxes=boxes,
|
| 561 |
+
keypoints=[(0, 0) for _ in range(max(0, int(n_keypoints)))],
|
| 562 |
+
)
|
| 563 |
+
)
|
| 564 |
+
|
| 565 |
+
return results
|
weights.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:175038b4491834781d517af0faaea7754762c3bff497327986ce80ee1c941294
|
| 3 |
+
size 19122644
|