gtensorapp commited on
Commit
d880509
·
verified ·
1 Parent(s): 9660757

Detect-Vehicle miner

Browse files
Files changed (5) hide show
  1. chute_config.yml +20 -0
  2. class_names.txt +4 -0
  3. config.json +27 -0
  4. miner.py +514 -0
  5. weights.onnx +3 -0
chute_config.yml ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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>=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==2.8.0 torchvision==0.23.0 torchaudio==2.8.0 --index-url https://download.pytorch.org/whl/cu128
7
+
8
+ NodeSelector:
9
+ gpu_count: 1
10
+ min_vram_gb_per_gpu: 16
11
+ include:
12
+ - pro_6000
13
+
14
+ Chute:
15
+ timeout_seconds: 900
16
+ concurrency: 4
17
+ max_instances: 5
18
+ scaling_threshold: 0.5
19
+ shutdown_after_seconds: 288000
20
+ tee: true
class_names.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ bus
2
+ car
3
+ truck
4
+ motorcycle
config.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "element_id": "vehicle",
3
+ "classes": ["bus", "car", "truck", "motorcycle", "van"],
4
+ "emit_order": ["car", "bus", "truck", "motorcycle", "van"],
5
+ "coco_ids": [0, 1, 3, 2],
6
+ "missing_classes": ["van"],
7
+ "imgsz": 704,
8
+ "conf": 0.35,
9
+ "conf_per_class": {
10
+ "bus": 0.56,
11
+ "car": 0.4,
12
+ "truck": 0.56,
13
+ "motorcycle": 0.45,
14
+ "van": 0.34
15
+ },
16
+ "dual_label": {
17
+ "pair": ["bus", "truck"],
18
+ "below": 0.6
19
+ },
20
+ "car_override": {
21
+ "prefer": "car",
22
+ "remove": ["bus", "truck"],
23
+ "min_iou": 0.5
24
+ },
25
+ "nms_iou": 0.4,
26
+ "max_det": 300
27
+ }
miner.py ADDED
@@ -0,0 +1,514 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import math
3
+ from pathlib import Path
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
+ class BoundingBox(BaseModel):
11
+ x1: int
12
+ y1: int
13
+ x2: int
14
+ y2: int
15
+ cls_id: int
16
+ conf: float
17
+
18
+ class TVFrameResult(BaseModel):
19
+ frame_id: int
20
+ boxes: list[BoundingBox]
21
+ keypoints: list[tuple[int, int]]
22
+
23
+ class Miner:
24
+
25
+ def __init__(self, path_hf_repo: Path) -> None:
26
+ model_path = self._resolve_model_path(path_hf_repo)
27
+ self.class_names = ['car', 'bus', 'truck', 'motorcycle']
28
+ self._model_class_order = ['car', 'bus', 'truck', 'motorcycle']
29
+ print('ORT version:', ort.__version__)
30
+ try:
31
+ ort.preload_dlls()
32
+ print('onnxruntime.preload_dlls() success')
33
+ except Exception as e:
34
+ print(f'preload_dlls failed: {e}')
35
+ print('ORT available providers BEFORE session:', ort.get_available_providers())
36
+ sess_options = ort.SessionOptions()
37
+ sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
38
+ sess_options.intra_op_num_threads = 2
39
+ sess_options.inter_op_num_threads = 1
40
+ sess_options.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL
41
+ force_cpu = os.environ.get('MINER_FORCE_CPU', '') == '1'
42
+ try:
43
+ if force_cpu:
44
+ raise RuntimeError('MINER_FORCE_CPU=1')
45
+ self.session = ort.InferenceSession(str(model_path), sess_options=sess_options, providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
46
+ print('Created ORT session with preferred CUDA provider list')
47
+ except Exception as e:
48
+ print(f'CUDA session creation skipped/failed, using CPU: {e}')
49
+ self.session = ort.InferenceSession(str(model_path), sess_options=sess_options, providers=['CPUExecutionProvider'])
50
+ print('ORT session providers:', self.session.get_providers())
51
+ model_class_order = self._read_model_class_order()
52
+ if model_class_order is None:
53
+ model_class_order = list(self._model_class_order)
54
+ print(f'cls order: no usable ONNX metadata, FALLBACK {model_class_order}')
55
+ else:
56
+ print(f'cls order: from ONNX metadata {model_class_order}')
57
+ self.cls_remap = np.array([self.class_names.index(n) for n in model_class_order], dtype=np.int32)
58
+ for inp in self.session.get_inputs():
59
+ print('INPUT:', inp.name, inp.shape, inp.type)
60
+ for out in self.session.get_outputs():
61
+ print('OUTPUT:', out.name, out.shape, out.type)
62
+ self.input_name = self.session.get_inputs()[0].name
63
+ self.output_names = [o.name for o in self.session.get_outputs()]
64
+ self.input_shape = self.session.get_inputs()[0].shape
65
+ input_type = self.session.get_inputs()[0].type
66
+ self.np_dtype = np.float16 if 'float16' in input_type else np.float32
67
+ self.input_u8 = 'uint8' in input_type
68
+ print(f'ONNX input dtype: {input_type} -> numpy {self.np_dtype}')
69
+ _hw = (1, 2) if self.input_u8 else (2, 3)
70
+ self.input_height = self._safe_dim(self.input_shape[_hw[0]], default=704)
71
+ self.input_width = self._safe_dim(self.input_shape[_hw[1]], default=704)
72
+ self._iou_thres_array = np.array([0.44, 0.46, 0.53, 0.47], dtype=np.float32)
73
+ self.cross_iou_thresh = 0.7
74
+ self.max_det = 300
75
+ self.pre_nms_topk = 1000
76
+ self.use_tta = False
77
+ self.use_cluster_boost = True
78
+ self.use_soft_nms = False
79
+ self.soft_nms_sigma = 0.5
80
+ self._conf_thres_array = np.array([0.45, 0.15, 0.4, 0.3], dtype=np.float32)
81
+ self._extra_conf_thres_array = np.array([0.45, 0.15, 0.4, 0.3], dtype=np.float32)
82
+ self._bonus_array = np.array([0.0, 0.0, 0.0, 0.0], dtype=np.float32)
83
+ self._min_box_area_array = np.array([64, 12, 12, 12], dtype=np.float32)
84
+ self.min_side = 3
85
+ self.max_aspect_ratio = 8
86
+ self.max_area_frac = 0.95
87
+ self.square_pad_frac = 0
88
+ self.dual_label_pair = ('bus', 'truck')
89
+ self.dual_label_below = 0
90
+ self._avg_iou = float(np.mean(self._iou_thres_array))
91
+ print(f'ONNX model loaded from: {model_path}')
92
+ print(f'ONNX input: name={self.input_name}, shape={self.input_shape}')
93
+ self._warmup()
94
+
95
+ def _warmup(self, iters: int=3) -> None:
96
+ try:
97
+ dummy = np.zeros((1024, 1024, 3), dtype=np.uint8)
98
+ for _ in range(max(1, iters)):
99
+ self.predict_batch(batch_images=[dummy], offset=0, n_keypoints=0)
100
+ print(f'warmup: {iters} dummy predict_batch call(s) done')
101
+ except Exception as e:
102
+ print(f'warmup skipped: {e}')
103
+
104
+ def __repr__(self) -> str:
105
+ return f'VehicleMiner(classes={len(self.class_names)}, providers={self.session.get_providers()})'
106
+
107
+ @staticmethod
108
+ def _safe_dim(value, default: int) -> int:
109
+ return value if isinstance(value, int) and value > 0 else default
110
+
111
+ @staticmethod
112
+ def _resolve_model_path(repo: Path) -> Path:
113
+ for name in ('weights.onnx', 'weights_int8.onnx'):
114
+ p = repo / name
115
+ if p.exists():
116
+ if name != 'weights.onnx':
117
+ print(f'model: weights.onnx not found, using {name}')
118
+ return p
119
+ candidates = sorted(repo.glob('*.onnx'))
120
+ if candidates:
121
+ print(f'model: using {candidates[0].name}')
122
+ return candidates[0]
123
+ return repo / 'weights.onnx'
124
+
125
+ def _read_model_class_order(self) -> list[str] | None:
126
+ try:
127
+ import ast
128
+ meta = self.session.get_modelmeta().custom_metadata_map
129
+ names = ast.literal_eval(meta['names'])
130
+ order = [str(names[i]) for i in sorted(names)] if isinstance(names, dict) else [str(n) for n in names]
131
+ except Exception as e:
132
+ print(f'cls order: could not read ONNX names metadata ({e})')
133
+ return None
134
+ if sorted(order) != sorted(self.class_names):
135
+ print(f'cls order: ONNX names {order} != expected {self.class_names}; ignoring')
136
+ return None
137
+ return order
138
+
139
+ def _letterbox(self, image: ndarray, new_shape: tuple[int, int], color=(114, 114, 114)) -> tuple[ndarray, float, tuple[float, float]]:
140
+ h, w = image.shape[:2]
141
+ new_w, new_h = new_shape
142
+ ratio = min(new_w / w, new_h / h)
143
+ rw, rh = (int(round(w * ratio)), int(round(h * ratio)))
144
+ if (rw, rh) != (w, h):
145
+ interp = cv2.INTER_CUBIC if ratio > 1.0 else cv2.INTER_LINEAR
146
+ image = cv2.resize(image, (rw, rh), interpolation=interp)
147
+ dw = (new_w - rw) / 2.0
148
+ dh = (new_h - rh) / 2.0
149
+ left, right = (int(round(dw - 0.1)), int(round(dw + 0.1)))
150
+ top, bottom = (int(round(dh - 0.1)), int(round(dh + 0.1)))
151
+ padded = cv2.copyMakeBorder(image, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color)
152
+ return (padded, ratio, (dw, dh))
153
+
154
+ def _preprocess(self, image: ndarray) -> tuple[np.ndarray, dict]:
155
+ orig_h, orig_w = image.shape[:2]
156
+ extra_left = extra_right = 0
157
+ if self.square_pad_frac > 0.0 and orig_w == orig_h:
158
+ target_w = int(orig_w * (1.0 + self.square_pad_frac))
159
+ if target_w > orig_w:
160
+ total = target_w - orig_w
161
+ extra_left = total // 2
162
+ extra_right = total - extra_left
163
+ image = cv2.copyMakeBorder(image, 0, 0, extra_left, extra_right, cv2.BORDER_CONSTANT, value=(114, 114, 114))
164
+ img, ratio, pad = self._letterbox(image, (self.input_width, self.input_height))
165
+ if self.input_u8:
166
+ return (np.ascontiguousarray(img[None]), {'ratio': ratio, 'pad': pad, 'orig_size': (orig_w, orig_h), 'extra_left': extra_left, 'extra_right': extra_right})
167
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
168
+ img = img.astype(np.float32) / 255.0
169
+ img = np.transpose(img, (2, 0, 1))[None, ...]
170
+ img = np.ascontiguousarray(img, dtype=self.np_dtype)
171
+ return (img, {'ratio': ratio, 'pad': pad, 'orig_size': (orig_w, orig_h), 'extra_left': extra_left, 'extra_right': extra_right})
172
+
173
+ @staticmethod
174
+ def _clip_boxes(boxes: np.ndarray, image_size: tuple[int, int]) -> np.ndarray:
175
+ w, h = image_size
176
+ boxes[:, 0] = np.clip(boxes[:, 0], 0, w - 1)
177
+ boxes[:, 1] = np.clip(boxes[:, 1], 0, h - 1)
178
+ boxes[:, 2] = np.clip(boxes[:, 2], 0, w - 1)
179
+ boxes[:, 3] = np.clip(boxes[:, 3], 0, h - 1)
180
+ return boxes
181
+
182
+ @staticmethod
183
+ def _xywh_to_xyxy(boxes: np.ndarray) -> np.ndarray:
184
+ out = np.empty_like(boxes)
185
+ out[:, 0] = boxes[:, 0] - boxes[:, 2] / 2.0
186
+ out[:, 1] = boxes[:, 1] - boxes[:, 3] / 2.0
187
+ out[:, 2] = boxes[:, 0] + boxes[:, 2] / 2.0
188
+ out[:, 3] = boxes[:, 1] + boxes[:, 3] / 2.0
189
+ return out
190
+
191
+ @staticmethod
192
+ def _hard_nms(boxes: np.ndarray, scores: np.ndarray, iou_thresh: float) -> np.ndarray:
193
+ n = len(boxes)
194
+ if n == 0:
195
+ return np.array([], dtype=np.intp)
196
+ x1, y1, x2, y2 = (boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3])
197
+ areas = np.maximum(0.0, x2 - x1) * np.maximum(0.0, y2 - y1)
198
+ order = np.argsort(-scores)
199
+ keep = []
200
+ while order.size > 0:
201
+ i = int(order[0])
202
+ keep.append(i)
203
+ if order.size == 1:
204
+ break
205
+ rest = order[1:]
206
+ xx1 = np.maximum(x1[i], x1[rest])
207
+ yy1 = np.maximum(y1[i], y1[rest])
208
+ xx2 = np.minimum(x2[i], x2[rest])
209
+ yy2 = np.minimum(y2[i], y2[rest])
210
+ inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)
211
+ iou = inter / (areas[i] + areas[rest] - inter + 1e-07)
212
+ order = rest[iou <= iou_thresh]
213
+ return np.array(keep, dtype=np.intp)
214
+
215
+ @staticmethod
216
+ def _soft_nms(boxes: np.ndarray, scores: np.ndarray, sigma: float) -> tuple[np.ndarray, np.ndarray]:
217
+ n = len(boxes)
218
+ if n == 0:
219
+ return (np.array([], dtype=np.intp), np.array([], dtype=np.float32))
220
+ b = boxes.astype(np.float32, copy=True)
221
+ sc = scores.astype(np.float32, copy=True)
222
+ order = np.arange(n)
223
+ for i in range(n):
224
+ mp = i + int(np.argmax(sc[i:]))
225
+ b[[i, mp]] = b[[mp, i]]
226
+ sc[[i, mp]] = sc[[mp, i]]
227
+ order[[i, mp]] = order[[mp, i]]
228
+ if i + 1 >= n:
229
+ break
230
+ xx1 = np.maximum(b[i, 0], b[i + 1:, 0])
231
+ yy1 = np.maximum(b[i, 1], b[i + 1:, 1])
232
+ xx2 = np.minimum(b[i, 2], b[i + 1:, 2])
233
+ yy2 = np.minimum(b[i, 3], b[i + 1:, 3])
234
+ inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)
235
+ ai = max(0.0, float((b[i, 2] - b[i, 0]) * (b[i, 3] - b[i, 1])))
236
+ aj = np.maximum(0.0, b[i + 1:, 2] - b[i + 1:, 0]) * np.maximum(0.0, b[i + 1:, 3] - b[i + 1:, 1])
237
+ iou = inter / (ai + aj - inter + 1e-07)
238
+ sc[i + 1:] *= np.exp(-iou ** 2 / sigma)
239
+ return (order, sc)
240
+
241
+ def _per_class_soft_nms(self, boxes: np.ndarray, scores: np.ndarray, cls_ids: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
242
+ keep_idx: list[int] = []
243
+ keep_sc: list[float] = []
244
+ for c in np.unique(cls_ids):
245
+ idx = np.where(cls_ids == c)[0]
246
+ order, dec = self._soft_nms(boxes[idx], scores[idx], self.soft_nms_sigma)
247
+ thr = float(self._conf_thres_array[c])
248
+ for k, s_dec in zip(order, dec):
249
+ if s_dec >= thr:
250
+ keep_idx.append(int(idx[k]))
251
+ keep_sc.append(float(s_dec))
252
+ return (np.array(keep_idx, dtype=np.intp), np.array(keep_sc, dtype=np.float32))
253
+
254
+ def _per_class_hard_nms(self, boxes: np.ndarray, scores: np.ndarray, cls_ids: np.ndarray) -> np.ndarray:
255
+ if len(boxes) == 0:
256
+ return np.array([], dtype=np.intp)
257
+ all_keep: list[int] = []
258
+ for c in np.unique(cls_ids):
259
+ idx = np.where(cls_ids == c)[0]
260
+ cls_iou = float(self._iou_thres_array[c])
261
+ keep = self._hard_nms(boxes[idx], scores[idx], cls_iou)
262
+ all_keep.extend(idx[keep].tolist())
263
+ all_keep.sort()
264
+ return np.array(all_keep, dtype=np.intp)
265
+
266
+ @staticmethod
267
+ def _max_score_per_cluster(post_boxes: np.ndarray, post_cls: np.ndarray, full_boxes: np.ndarray, full_scores: np.ndarray, full_cls: np.ndarray, iou_thresh: float) -> np.ndarray:
268
+ n = len(post_boxes)
269
+ if n == 0:
270
+ return np.empty(0, dtype=np.float32)
271
+ m = len(full_boxes)
272
+ if m == 0:
273
+ return np.zeros(n, dtype=np.float32)
274
+ pa = np.maximum(0.0, post_boxes[:, 2] - post_boxes[:, 0]) * np.maximum(0.0, post_boxes[:, 3] - post_boxes[:, 1])
275
+ fa = np.maximum(0.0, full_boxes[:, 2] - full_boxes[:, 0]) * np.maximum(0.0, full_boxes[:, 3] - full_boxes[:, 1])
276
+ xx1 = np.maximum(post_boxes[:, 0][:, None], full_boxes[:, 0][None, :])
277
+ yy1 = np.maximum(post_boxes[:, 1][:, None], full_boxes[:, 1][None, :])
278
+ xx2 = np.minimum(post_boxes[:, 2][:, None], full_boxes[:, 2][None, :])
279
+ yy2 = np.minimum(post_boxes[:, 3][:, None], full_boxes[:, 3][None, :])
280
+ inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)
281
+ iou = inter / (pa[:, None] + fa[None, :] - inter + 1e-07)
282
+ mask = (iou >= iou_thresh) & (post_cls[:, None] == full_cls[None, :])
283
+ tiled = np.where(mask, full_scores[None, :], -np.inf)
284
+ out = tiled.max(axis=1)
285
+ out[~np.isfinite(out)] = 0.0
286
+ return out.astype(np.float32)
287
+
288
+ def _conf_filter_mask(self, scores: np.ndarray, cls_ids: np.ndarray, extra_left: int) -> np.ndarray:
289
+ if len(scores) == 0:
290
+ return np.zeros(0, dtype=bool)
291
+ thr_arr = self._extra_conf_thres_array if extra_left > 0 else self._conf_thres_array
292
+ keep = scores >= thr_arr[cls_ids]
293
+ for c in np.unique(cls_ids):
294
+ b = float(self._bonus_array[c])
295
+ if b <= 0.0:
296
+ continue
297
+ cm = cls_ids == c
298
+ if keep[cm].any():
299
+ continue
300
+ idx = np.where(cm)[0]
301
+ top = int(idx[int(np.argmax(scores[idx]))])
302
+ if scores[top] >= float(self._conf_thres_array[c]) - b:
303
+ keep[top] = True
304
+ return keep
305
+
306
+ def _filter_sane_boxes(self, boxes: np.ndarray, scores: np.ndarray, cls_ids: np.ndarray, orig_size: tuple[int, int]) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
307
+ if len(boxes) == 0:
308
+ return (boxes, scores, cls_ids)
309
+ orig_w, orig_h = orig_size
310
+ image_area = float(orig_w * orig_h)
311
+ bw = np.maximum(0.0, boxes[:, 2] - boxes[:, 0])
312
+ bh = np.maximum(0.0, boxes[:, 3] - boxes[:, 1])
313
+ area = bw * bh
314
+ ar = np.maximum(bw / np.maximum(bh, 1e-06), bh / np.maximum(bw, 1e-06))
315
+ keep = (bw >= self.min_side) & (bh >= self.min_side) & (area >= self._min_box_area_array[cls_ids]) & (area <= self.max_area_frac * image_area) & (ar <= self.max_aspect_ratio)
316
+ return (boxes[keep], scores[keep], cls_ids[keep])
317
+
318
+ def _cross_class_dedup_op(self, boxes: np.ndarray, scores: np.ndarray, cls_ids: np.ndarray, iou_thresh: float) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
319
+ n = len(boxes)
320
+ if n <= 1:
321
+ return (boxes, scores, cls_ids)
322
+ boxes = np.asarray(boxes, dtype=np.float32)
323
+ scores = np.asarray(scores, dtype=np.float32)
324
+ cls_ids = np.asarray(cls_ids, dtype=np.int32)
325
+ areas = np.maximum(0.0, boxes[:, 2] - boxes[:, 0]) * np.maximum(0.0, boxes[:, 3] - boxes[:, 1])
326
+ margins = scores - self._conf_thres_array[cls_ids]
327
+ order = np.lexsort((-areas, -margins))
328
+ suppressed = np.zeros(n, dtype=bool)
329
+ keep: list[int] = []
330
+ for i in order:
331
+ if suppressed[i]:
332
+ continue
333
+ keep.append(int(i))
334
+ bi = boxes[i]
335
+ xx1 = np.maximum(bi[0], boxes[:, 0])
336
+ yy1 = np.maximum(bi[1], boxes[:, 1])
337
+ xx2 = np.minimum(bi[2], boxes[:, 2])
338
+ yy2 = np.minimum(bi[3], boxes[:, 3])
339
+ inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)
340
+ a_i = max(1e-07, float((bi[2] - bi[0]) * (bi[3] - bi[1])))
341
+ iou = inter / (a_i + areas - inter + 1e-07)
342
+ dup = iou > iou_thresh
343
+ dup[i] = False
344
+ suppressed |= dup
345
+ keep_idx = np.array(keep, dtype=np.intp)
346
+ return (boxes[keep_idx], scores[keep_idx], cls_ids[keep_idx])
347
+
348
+ def _apply_dual_label(self, boxes: np.ndarray, scores: np.ndarray, cls_ids: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
349
+ if self.dual_label_below <= 0.0 or len(boxes) == 0:
350
+ return (boxes, scores, cls_ids)
351
+ a = self.class_names.index(self.dual_label_pair[0])
352
+ b = self.class_names.index(self.dual_label_pair[1])
353
+ sib = np.full(len(self.class_names), -1, dtype=np.int32)
354
+ sib[a], sib[b] = (b, a)
355
+ mask = (sib[cls_ids] >= 0) & (scores < self.dual_label_below)
356
+ if not mask.any():
357
+ return (boxes, scores, cls_ids)
358
+ boxes = np.concatenate([boxes, boxes[mask]], axis=0)
359
+ scores = np.concatenate([scores, scores[mask]], axis=0)
360
+ cls_ids = np.concatenate([cls_ids, sib[cls_ids[mask]]], axis=0)
361
+ return (boxes, scores, cls_ids)
362
+
363
+ def _per_view_pipeline(self, boxes: np.ndarray, scores: np.ndarray, cls_ids: np.ndarray, orig_size: tuple[int, int]) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
364
+ boxes, scores, cls_ids = self._filter_sane_boxes(boxes, scores, cls_ids, orig_size)
365
+ if len(boxes) == 0:
366
+ return (boxes, scores, cls_ids)
367
+ if len(scores) > self.pre_nms_topk:
368
+ top = np.argpartition(-scores, self.pre_nms_topk)[:self.pre_nms_topk]
369
+ boxes, scores, cls_ids = (boxes[top], scores[top], cls_ids[top])
370
+ if len(boxes) > 1:
371
+ if self.use_soft_nms:
372
+ keep, scores = self._per_class_soft_nms(boxes, scores, cls_ids)
373
+ boxes, cls_ids = (boxes[keep], cls_ids[keep])
374
+ else:
375
+ keep = self._per_class_hard_nms(boxes, scores, cls_ids)
376
+ boxes, scores, cls_ids = (boxes[keep], scores[keep], cls_ids[keep])
377
+ if len(scores) > self.max_det:
378
+ top = np.argsort(-scores)[:self.max_det]
379
+ boxes, scores, cls_ids = (boxes[top], scores[top], cls_ids[top])
380
+ if len(boxes) > 1:
381
+ boxes, scores, cls_ids = self._cross_class_dedup_op(boxes, scores, cls_ids, self.cross_iou_thresh)
382
+ return (boxes, scores, cls_ids)
383
+
384
+ def _unmap_and_finish(self, boxes: np.ndarray, scores: np.ndarray, cls_ids: np.ndarray, meta: dict) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
385
+ pad_w, pad_h = meta['pad']
386
+ ratio = meta['ratio']
387
+ orig_w, orig_h = meta['orig_size']
388
+ extra_left, extra_right = (meta['extra_left'], meta['extra_right'])
389
+ boxes[:, [0, 2]] -= pad_w
390
+ boxes[:, [1, 3]] -= pad_h
391
+ boxes /= ratio
392
+ if extra_left:
393
+ boxes[:, [0, 2]] -= extra_left
394
+ if extra_left or extra_right:
395
+ cx = (boxes[:, 0] + boxes[:, 2]) * 0.5
396
+ inside = (cx >= 0) & (cx <= orig_w)
397
+ boxes, scores, cls_ids = (boxes[inside], scores[inside], cls_ids[inside])
398
+ if len(boxes) == 0:
399
+ return (boxes, scores, cls_ids)
400
+ boxes = self._clip_boxes(boxes, (orig_w, orig_h))
401
+ return self._per_view_pipeline(boxes, scores, cls_ids, (orig_w, orig_h))
402
+
403
+ def _decode_final_dets(self, preds: np.ndarray, meta: dict) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
404
+ empty = (np.empty((0, 4), np.float32), np.empty(0, np.float32), np.empty(0, np.int32))
405
+ if preds.ndim == 3 and preds.shape[0] == 1:
406
+ preds = preds[0]
407
+ if preds.ndim != 2 or preds.shape[1] < 6:
408
+ raise ValueError(f'Unexpected final-det output shape: {preds.shape}')
409
+ boxes = preds[:, :4].astype(np.float32)
410
+ scores = preds[:, 4].astype(np.float32)
411
+ cls_ids = self.cls_remap[preds[:, 5].astype(np.int32)]
412
+ keep = self._conf_filter_mask(scores, cls_ids, meta['extra_left'])
413
+ boxes, scores, cls_ids = (boxes[keep], scores[keep], cls_ids[keep])
414
+ if len(boxes) == 0:
415
+ return empty
416
+ return self._unmap_and_finish(boxes, scores, cls_ids, meta)
417
+
418
+ def _decode_raw_yolo(self, preds: np.ndarray, meta: dict) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
419
+ empty = (np.empty((0, 4), np.float32), np.empty(0, np.float32), np.empty(0, np.int32))
420
+ if preds.ndim != 3 or preds.shape[0] != 1:
421
+ raise ValueError(f'Unexpected raw output shape: {preds.shape}')
422
+ preds = preds[0]
423
+ if preds.shape[0] <= 16 and preds.shape[1] > preds.shape[0]:
424
+ preds = preds.T
425
+ if preds.ndim != 2 or preds.shape[1] < 5:
426
+ raise ValueError(f'Unexpected normalized raw shape: {preds.shape}')
427
+ boxes_xywh = preds[:, :4].astype(np.float32)
428
+ cls_part = preds[:, 4:].astype(np.float32)
429
+ if cls_part.shape[1] == 1:
430
+ scores = cls_part[:, 0]
431
+ cls_ids = np.zeros(len(scores), dtype=np.int32)
432
+ else:
433
+ cls_ids = np.argmax(cls_part, axis=1).astype(np.int32)
434
+ scores = cls_part[np.arange(len(cls_part)), cls_ids]
435
+ cls_ids = self.cls_remap[cls_ids]
436
+ keep = self._conf_filter_mask(scores, cls_ids, meta['extra_left'])
437
+ boxes_xywh, scores, cls_ids = (boxes_xywh[keep], scores[keep], cls_ids[keep])
438
+ if len(boxes_xywh) == 0:
439
+ return empty
440
+ boxes = self._xywh_to_xyxy(boxes_xywh)
441
+ return self._unmap_and_finish(boxes, scores, cls_ids, meta)
442
+
443
+ def _decode(self, output: np.ndarray, meta: dict) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
444
+ if output.ndim == 2 and output.shape[1] >= 6:
445
+ return self._decode_final_dets(output, meta)
446
+ if output.ndim == 3 and output.shape[0] == 1 and (output.shape[2] == 6):
447
+ return self._decode_final_dets(output, meta)
448
+ return self._decode_raw_yolo(output, meta)
449
+
450
+ def _predict_single_arrays(self, image: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray, dict]:
451
+ if not isinstance(image, np.ndarray) or image.ndim != 3 or image.shape[2] != 3:
452
+ raise ValueError(f"Expected HWC BGR image, got {type(image)} {getattr(image, 'shape', None)}")
453
+ if image.dtype != np.uint8:
454
+ image = image.astype(np.uint8)
455
+ inp, meta = self._preprocess(image)
456
+ outputs = self.session.run(self.output_names, {self.input_name: inp})
457
+ boxes, scores, cls_ids = self._decode(outputs[0], meta)
458
+ return (boxes, scores, cls_ids, meta)
459
+
460
+ @staticmethod
461
+ def _to_boxes(boxes: np.ndarray, scores: np.ndarray, cls_ids: np.ndarray, orig_size: tuple[int, int]) -> list[BoundingBox]:
462
+ results: list[BoundingBox] = []
463
+ orig_w, orig_h = orig_size
464
+ for box, conf, cls_id in zip(boxes, scores, cls_ids):
465
+ x1, y1, x2, y2 = box.tolist()
466
+ if x2 <= x1 or y2 <= y1:
467
+ continue
468
+ results.append(BoundingBox(x1=max(0, min(orig_w, int(math.floor(x1)))), y1=max(0, min(orig_h, int(math.floor(y1)))), x2=max(0, min(orig_w, int(math.ceil(x2)))), y2=max(0, min(orig_h, int(math.ceil(y2)))), cls_id=int(cls_id), conf=float(max(0.0, min(1.0, conf)))))
469
+ return results
470
+
471
+ def _infer_single(self, image: np.ndarray) -> list[BoundingBox]:
472
+ boxes, scores, cls_ids, meta = self._predict_single_arrays(image)
473
+ if len(boxes) == 0:
474
+ return []
475
+ if self.use_cluster_boost and len(boxes) > 1:
476
+ scores = self._max_score_per_cluster(boxes, cls_ids, boxes, scores, cls_ids, self._avg_iou)
477
+ boxes, scores, cls_ids = self._apply_dual_label(boxes, scores, cls_ids)
478
+ return self._to_boxes(boxes, scores, cls_ids, meta['orig_size'])
479
+
480
+ def _infer_tta(self, image: np.ndarray) -> list[BoundingBox]:
481
+ b0, s0, c0, meta = self._predict_single_arrays(image)
482
+ w = image.shape[1]
483
+ bf, sf, cf, _ = self._predict_single_arrays(cv2.flip(image, 1))
484
+ if len(bf):
485
+ bf = bf.copy()
486
+ bf[:, [0, 2]] = w - bf[:, [2, 0]]
487
+ coords = np.concatenate([b0, bf], axis=0) if len(bf) else b0
488
+ scores = np.concatenate([s0, sf], axis=0) if len(sf) else s0
489
+ cls_ids = np.concatenate([c0, cf], axis=0) if len(cf) else c0
490
+ if len(coords) == 0:
491
+ return []
492
+ keep = self._per_class_hard_nms(coords, scores, cls_ids)
493
+ if len(keep) == 0:
494
+ return []
495
+ if len(keep) > self.max_det:
496
+ keep = keep[np.argsort(-scores[keep])[:self.max_det]]
497
+ boosted = self._max_score_per_cluster(coords[keep], cls_ids[keep], coords, scores, cls_ids, self._avg_iou)
498
+ kb, kc = (coords[keep], cls_ids[keep])
499
+ if len(kb) > 1:
500
+ kb, boosted, kc = self._cross_class_dedup_op(kb, boosted, kc, self.cross_iou_thresh)
501
+ kb, boosted, kc = self._apply_dual_label(kb, boosted, kc)
502
+ return self._to_boxes(kb, boosted, kc, meta['orig_size'])
503
+
504
+ def predict_batch(self, batch_images: list[ndarray], offset: int, n_keypoints: int) -> list[TVFrameResult]:
505
+ results: list[TVFrameResult] = []
506
+ for idx, image in enumerate(batch_images):
507
+ try:
508
+ boxes = self._infer_tta(image) if self.use_tta else self._infer_single(image)
509
+ except Exception as e:
510
+ print(f'Inference failed for frame {offset + idx}: {e}')
511
+ boxes = []
512
+ keypoints = [(0, 0) for _ in range(max(0, int(n_keypoints)))]
513
+ results.append(TVFrameResult(frame_id=offset + idx, boxes=boxes, keypoints=keypoints))
514
+ return results
weights.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6e53c94cceddee7b838c334934bcf6657e473674ecd6bef381bd3749be918aaf
3
+ size 9830747