SuperBitDev commited on
Commit
aab03c6
·
verified ·
1 Parent(s): 51ede53

Upload folder using huggingface_hub

Browse files
Files changed (2) hide show
  1. miner.py +597 -564
  2. weights.onnx +1 -1
miner.py CHANGED
@@ -1,565 +1,598 @@
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=1280)
72
- self.input_width = self._safe_dim(self.input_shape[3], default=1280)
73
-
74
- self.conf_thres = 0.1
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
 
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 / "person-detection.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
+ self.input_height = self._safe_dim(self.input_shape[2], default=1280)
71
+ self.input_width = self._safe_dim(self.input_shape[3], default=1280)
72
+
73
+ # ---------- Scoring-oriented thresholds ----------
74
+ # Low threshold for candidate generation
75
+ self.conf_thres = 0.10
76
+
77
+ # High-confidence boxes can survive without TTA confirmation
78
+ self.conf_high = 0.20
79
+
80
+ # NMS threshold
81
+ self.iou_thres = 0.50
82
+
83
+ # TTA confirmation IoU
84
+ self.tta_match_iou = 0.55
85
+
86
+ self.max_det = 300
87
+ self.use_tta = True
88
+
89
+ # Box sanity filters
90
+ self.min_box_area = 16 * 16
91
+ self.min_w = 6
92
+ self.min_h = 6
93
+ self.max_aspect_ratio = 6.0
94
+ self.max_box_area_ratio = 0.95
95
+
96
+ print(f"✅ ONNX model loaded from: {model_path}")
97
+ print(f"✅ ONNX providers: {self.session.get_providers()}")
98
+ print(f"✅ ONNX input: name={self.input_name}, shape={self.input_shape}")
99
+
100
+ def __repr__(self) -> str:
101
+ return (
102
+ f"ONNXRuntime(session={type(self.session).__name__}, "
103
+ f"providers={self.session.get_providers()})"
104
+ )
105
+
106
+ @staticmethod
107
+ def _safe_dim(value, default: int) -> int:
108
+ return value if isinstance(value, int) and value > 0 else default
109
+
110
+ def _letterbox(
111
+ self,
112
+ image: ndarray,
113
+ new_shape: tuple[int, int],
114
+ color=(114, 114, 114),
115
+ ) -> tuple[ndarray, float, tuple[float, float]]:
116
+ h, w = image.shape[:2]
117
+ new_w, new_h = new_shape
118
+
119
+ ratio = min(new_w / w, new_h / h)
120
+ resized_w = int(round(w * ratio))
121
+ resized_h = int(round(h * ratio))
122
+
123
+ if (resized_w, resized_h) != (w, h):
124
+ interp = cv2.INTER_CUBIC if ratio > 1.0 else cv2.INTER_LINEAR
125
+ image = cv2.resize(image, (resized_w, resized_h), interpolation=interp)
126
+
127
+ dw = new_w - resized_w
128
+ dh = new_h - resized_h
129
+ dw /= 2.0
130
+ dh /= 2.0
131
+
132
+ left = int(round(dw - 0.1))
133
+ right = int(round(dw + 0.1))
134
+ top = int(round(dh - 0.1))
135
+ bottom = int(round(dh + 0.1))
136
+
137
+ padded = cv2.copyMakeBorder(
138
+ image,
139
+ top,
140
+ bottom,
141
+ left,
142
+ right,
143
+ borderType=cv2.BORDER_CONSTANT,
144
+ value=color,
145
+ )
146
+ return padded, ratio, (dw, dh)
147
+
148
+ def _preprocess(
149
+ self, image: ndarray
150
+ ) -> tuple[np.ndarray, float, tuple[float, float], tuple[int, int]]:
151
+ orig_h, orig_w = image.shape[:2]
152
+
153
+ img, ratio, pad = self._letterbox(
154
+ image, (self.input_width, self.input_height)
155
+ )
156
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
157
+ img = img.astype(np.float32) / 255.0
158
+ img = np.transpose(img, (2, 0, 1))[None, ...]
159
+ img = np.ascontiguousarray(img, dtype=np.float32)
160
+
161
+ return img, ratio, pad, (orig_w, orig_h)
162
+
163
+ @staticmethod
164
+ def _clip_boxes(boxes: np.ndarray, image_size: tuple[int, int]) -> np.ndarray:
165
+ w, h = image_size
166
+ boxes[:, 0] = np.clip(boxes[:, 0], 0, w - 1)
167
+ boxes[:, 1] = np.clip(boxes[:, 1], 0, h - 1)
168
+ boxes[:, 2] = np.clip(boxes[:, 2], 0, w - 1)
169
+ boxes[:, 3] = np.clip(boxes[:, 3], 0, h - 1)
170
+ return boxes
171
+
172
+ @staticmethod
173
+ def _xywh_to_xyxy(boxes: np.ndarray) -> np.ndarray:
174
+ out = np.empty_like(boxes)
175
+ out[:, 0] = boxes[:, 0] - boxes[:, 2] / 2.0
176
+ out[:, 1] = boxes[:, 1] - boxes[:, 3] / 2.0
177
+ out[:, 2] = boxes[:, 0] + boxes[:, 2] / 2.0
178
+ out[:, 3] = boxes[:, 1] + boxes[:, 3] / 2.0
179
+ return out
180
+
181
+ @staticmethod
182
+ def _hard_nms(
183
+ boxes: np.ndarray,
184
+ scores: np.ndarray,
185
+ iou_thresh: float,
186
+ ) -> np.ndarray:
187
+ if len(boxes) == 0:
188
+ return np.array([], dtype=np.intp)
189
+
190
+ boxes = np.asarray(boxes, dtype=np.float32)
191
+ scores = np.asarray(scores, dtype=np.float32)
192
+ order = np.argsort(scores)[::-1]
193
+ keep = []
194
+
195
+ while len(order) > 0:
196
+ i = order[0]
197
+ keep.append(i)
198
+ if len(order) == 1:
199
+ break
200
+
201
+ rest = order[1:]
202
+
203
+ xx1 = np.maximum(boxes[i, 0], boxes[rest, 0])
204
+ yy1 = np.maximum(boxes[i, 1], boxes[rest, 1])
205
+ xx2 = np.minimum(boxes[i, 2], boxes[rest, 2])
206
+ yy2 = np.minimum(boxes[i, 3], boxes[rest, 3])
207
+
208
+ inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)
209
+
210
+ area_i = np.maximum(0.0, (boxes[i, 2] - boxes[i, 0])) * np.maximum(0.0, (boxes[i, 3] - boxes[i, 1]))
211
+ area_r = np.maximum(0.0, (boxes[rest, 2] - boxes[rest, 0])) * np.maximum(0.0, (boxes[rest, 3] - boxes[rest, 1]))
212
+
213
+ iou = inter / (area_i + area_r - inter + 1e-7)
214
+ order = rest[iou <= iou_thresh]
215
+
216
+ return np.array(keep, dtype=np.intp)
217
+
218
+ @staticmethod
219
+ def _box_iou_one_to_many(box: np.ndarray, boxes: np.ndarray) -> np.ndarray:
220
+ xx1 = np.maximum(box[0], boxes[:, 0])
221
+ yy1 = np.maximum(box[1], boxes[:, 1])
222
+ xx2 = np.minimum(box[2], boxes[:, 2])
223
+ yy2 = np.minimum(box[3], boxes[:, 3])
224
+
225
+ inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)
226
+
227
+ area_a = max(0.0, (box[2] - box[0]) * (box[3] - box[1]))
228
+ area_b = np.maximum(0.0, boxes[:, 2] - boxes[:, 0]) * np.maximum(0.0, boxes[:, 3] - boxes[:, 1])
229
+
230
+ return inter / (area_a + area_b - inter + 1e-7)
231
+
232
+ def _filter_sane_boxes(
233
+ self,
234
+ boxes: np.ndarray,
235
+ scores: np.ndarray,
236
+ cls_ids: np.ndarray,
237
+ orig_size: tuple[int, int],
238
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
239
+ if len(boxes) == 0:
240
+ return boxes, scores, cls_ids
241
+
242
+ orig_w, orig_h = orig_size
243
+ image_area = float(orig_w * orig_h)
244
+
245
+ keep = []
246
+ for i, box in enumerate(boxes):
247
+ x1, y1, x2, y2 = box.tolist()
248
+ bw = x2 - x1
249
+ bh = y2 - y1
250
+
251
+ if bw <= 0 or bh <= 0:
252
+ continue
253
+ if bw < self.min_w or bh < self.min_h:
254
+ continue
255
+
256
+ area = bw * bh
257
+ if area < self.min_box_area:
258
+ continue
259
+ if area > self.max_box_area_ratio * image_area:
260
+ continue
261
+
262
+ ar = max(bw / max(bh, 1e-6), bh / max(bw, 1e-6))
263
+ if ar > self.max_aspect_ratio:
264
+ continue
265
+
266
+ keep.append(i)
267
+
268
+ if not keep:
269
+ return (
270
+ np.empty((0, 4), dtype=np.float32),
271
+ np.empty((0,), dtype=np.float32),
272
+ np.empty((0,), dtype=np.int32),
273
+ )
274
+
275
+ keep = np.array(keep, dtype=np.intp)
276
+ return boxes[keep], scores[keep], cls_ids[keep]
277
+
278
+ def _decode_final_dets(
279
+ self,
280
+ preds: np.ndarray,
281
+ ratio: float,
282
+ pad: tuple[float, float],
283
+ orig_size: tuple[int, int],
284
+ ) -> list[BoundingBox]:
285
+ if preds.ndim == 3 and preds.shape[0] == 1:
286
+ preds = preds[0]
287
+
288
+ if preds.ndim != 2 or preds.shape[1] < 6:
289
+ raise ValueError(f"Unexpected ONNX final-det output shape: {preds.shape}")
290
+
291
+ boxes = preds[:, :4].astype(np.float32)
292
+ scores = preds[:, 4].astype(np.float32)
293
+ cls_ids = preds[:, 5].astype(np.int32)
294
+
295
+ # person only
296
+ keep = cls_ids == 0
297
+ boxes = boxes[keep]
298
+ scores = scores[keep]
299
+ cls_ids = cls_ids[keep]
300
+
301
+ # candidate threshold
302
+ keep = scores >= self.conf_thres
303
+ boxes = boxes[keep]
304
+ scores = scores[keep]
305
+ cls_ids = cls_ids[keep]
306
+
307
+ if len(boxes) == 0:
308
+ return []
309
+
310
+ pad_w, pad_h = pad
311
+ orig_w, orig_h = orig_size
312
+
313
+ boxes[:, [0, 2]] -= pad_w
314
+ boxes[:, [1, 3]] -= pad_h
315
+ boxes /= ratio
316
+ boxes = self._clip_boxes(boxes, (orig_w, orig_h))
317
+
318
+ boxes, scores, cls_ids = self._filter_sane_boxes(boxes, scores, cls_ids, orig_size)
319
+ if len(boxes) == 0:
320
+ return []
321
+
322
+ keep_idx = self._hard_nms(boxes, scores, self.iou_thres)
323
+ keep_idx = keep_idx[: self.max_det]
324
+
325
+ boxes = boxes[keep_idx]
326
+ scores = scores[keep_idx]
327
+ cls_ids = cls_ids[keep_idx]
328
+
329
+ return [
330
+ BoundingBox(
331
+ x1=int(math.floor(box[0])),
332
+ y1=int(math.floor(box[1])),
333
+ x2=int(math.ceil(box[2])),
334
+ y2=int(math.ceil(box[3])),
335
+ cls_id=int(cls_id),
336
+ conf=float(conf),
337
+ )
338
+ for box, conf, cls_id in zip(boxes, scores, cls_ids)
339
+ if box[2] > box[0] and box[3] > box[1]
340
+ ]
341
+
342
+ def _decode_raw_yolo(
343
+ self,
344
+ preds: np.ndarray,
345
+ ratio: float,
346
+ pad: tuple[float, float],
347
+ orig_size: tuple[int, int],
348
+ ) -> list[BoundingBox]:
349
+ if preds.ndim != 3:
350
+ raise ValueError(f"Unexpected raw ONNX output shape: {preds.shape}")
351
+ if preds.shape[0] != 1:
352
+ raise ValueError(f"Unexpected batch dimension in raw output: {preds.shape}")
353
+
354
+ preds = preds[0]
355
+
356
+ # Normalize to [N, C]
357
+ if preds.shape[0] <= 16 and preds.shape[1] > preds.shape[0]:
358
+ preds = preds.T
359
+
360
+ if preds.ndim != 2 or preds.shape[1] < 5:
361
+ raise ValueError(f"Unexpected normalized raw output shape: {preds.shape}")
362
+
363
+ boxes_xywh = preds[:, :4].astype(np.float32)
364
+ tail = preds[:, 4:].astype(np.float32)
365
+
366
+ # Supports:
367
+ # [x,y,w,h,score] single-class
368
+ # [x,y,w,h,obj,cls] YOLO standard single-class
369
+ # [x,y,w,h,obj,cls1,cls2,...] multi-class
370
+ if tail.shape[1] == 1:
371
+ scores = tail[:, 0]
372
+ cls_ids = np.zeros(len(scores), dtype=np.int32)
373
+ elif tail.shape[1] == 2:
374
+ obj = tail[:, 0]
375
+ cls_prob = tail[:, 1]
376
+ scores = obj * cls_prob
377
+ cls_ids = np.zeros(len(scores), dtype=np.int32)
378
+ else:
379
+ obj = tail[:, 0]
380
+ class_probs = tail[:, 1:]
381
+ cls_ids = np.argmax(class_probs, axis=1).astype(np.int32)
382
+ cls_scores = class_probs[np.arange(len(class_probs)), cls_ids]
383
+ scores = obj * cls_scores
384
+
385
+ keep = cls_ids == 0
386
+ boxes_xywh = boxes_xywh[keep]
387
+ scores = scores[keep]
388
+ cls_ids = cls_ids[keep]
389
+
390
+ keep = scores >= self.conf_thres
391
+ boxes_xywh = boxes_xywh[keep]
392
+ scores = scores[keep]
393
+ cls_ids = cls_ids[keep]
394
+
395
+ if len(boxes_xywh) == 0:
396
+ return []
397
+
398
+ boxes = self._xywh_to_xyxy(boxes_xywh)
399
+
400
+ pad_w, pad_h = pad
401
+ orig_w, orig_h = orig_size
402
+
403
+ boxes[:, [0, 2]] -= pad_w
404
+ boxes[:, [1, 3]] -= pad_h
405
+ boxes /= ratio
406
+ boxes = self._clip_boxes(boxes, (orig_w, orig_h))
407
+
408
+ boxes, scores, cls_ids = self._filter_sane_boxes(boxes, scores, cls_ids, orig_size)
409
+ if len(boxes) == 0:
410
+ return []
411
+
412
+ keep_idx = self._hard_nms(boxes, scores, self.iou_thres)
413
+ keep_idx = keep_idx[: self.max_det]
414
+
415
+ boxes = boxes[keep_idx]
416
+ scores = scores[keep_idx]
417
+ cls_ids = cls_ids[keep_idx]
418
+
419
+ return [
420
+ BoundingBox(
421
+ x1=int(math.floor(box[0])),
422
+ y1=int(math.floor(box[1])),
423
+ x2=int(math.ceil(box[2])),
424
+ y2=int(math.ceil(box[3])),
425
+ cls_id=int(cls_id),
426
+ conf=float(conf),
427
+ )
428
+ for box, conf, cls_id in zip(boxes, scores, cls_ids)
429
+ if box[2] > box[0] and box[3] > box[1]
430
+ ]
431
+
432
+ def _postprocess(
433
+ self,
434
+ output: np.ndarray,
435
+ ratio: float,
436
+ pad: tuple[float, float],
437
+ orig_size: tuple[int, int],
438
+ ) -> list[BoundingBox]:
439
+ if output.ndim == 2 and output.shape[1] >= 6:
440
+ return self._decode_final_dets(output, ratio, pad, orig_size)
441
+
442
+ if output.ndim == 3 and output.shape[0] == 1 and output.shape[2] >= 6:
443
+ return self._decode_final_dets(output, ratio, pad, orig_size)
444
+
445
+ return self._decode_raw_yolo(output, ratio, pad, orig_size)
446
+
447
+ def _predict_single(self, image: np.ndarray) -> list[BoundingBox]:
448
+ if image is None:
449
+ raise ValueError("Input image is None")
450
+ if not isinstance(image, np.ndarray):
451
+ raise TypeError(f"Input is not numpy array: {type(image)}")
452
+ if image.ndim != 3:
453
+ raise ValueError(f"Expected HWC image, got shape={image.shape}")
454
+ if image.shape[0] <= 0 or image.shape[1] <= 0:
455
+ raise ValueError(f"Invalid image shape={image.shape}")
456
+ if image.shape[2] != 3:
457
+ raise ValueError(f"Expected 3 channels, got shape={image.shape}")
458
+
459
+ if image.dtype != np.uint8:
460
+ image = image.astype(np.uint8)
461
+
462
+ input_tensor, ratio, pad, orig_size = self._preprocess(image)
463
+
464
+ expected_shape = (1, 3, self.input_height, self.input_width)
465
+ if input_tensor.shape != expected_shape:
466
+ raise ValueError(
467
+ f"Bad input tensor shape={input_tensor.shape}, expected={expected_shape}"
468
+ )
469
+
470
+ outputs = self.session.run(self.output_names, {self.input_name: input_tensor})
471
+ det_output = outputs[0]
472
+ return self._postprocess(det_output, ratio, pad, orig_size)
473
+
474
+ def _merge_tta_consensus(
475
+ self,
476
+ boxes_orig: list[BoundingBox],
477
+ boxes_flip: list[BoundingBox],
478
+ ) -> list[BoundingBox]:
479
+ """
480
+ Keep:
481
+ - any box with conf >= conf_high
482
+ - low/medium-conf boxes only if confirmed across TTA views
483
+ Then run final hard NMS.
484
+ """
485
+ if not boxes_orig and not boxes_flip:
486
+ return []
487
+
488
+ coords_o = np.array([[b.x1, b.y1, b.x2, b.y2] for b in boxes_orig], dtype=np.float32) if boxes_orig else np.empty((0, 4), dtype=np.float32)
489
+ scores_o = np.array([b.conf for b in boxes_orig], dtype=np.float32) if boxes_orig else np.empty((0,), dtype=np.float32)
490
+
491
+ coords_f = np.array([[b.x1, b.y1, b.x2, b.y2] for b in boxes_flip], dtype=np.float32) if boxes_flip else np.empty((0, 4), dtype=np.float32)
492
+ scores_f = np.array([b.conf for b in boxes_flip], dtype=np.float32) if boxes_flip else np.empty((0,), dtype=np.float32)
493
+
494
+ accepted_boxes = []
495
+ accepted_scores = []
496
+
497
+ # Original view candidates
498
+ for i in range(len(coords_o)):
499
+ score = scores_o[i]
500
+ if score >= self.conf_high:
501
+ accepted_boxes.append(coords_o[i])
502
+ accepted_scores.append(score)
503
+ elif len(coords_f) > 0:
504
+ ious = self._box_iou_one_to_many(coords_o[i], coords_f)
505
+ j = int(np.argmax(ious))
506
+ if ious[j] >= self.tta_match_iou:
507
+ fused_score = max(score, scores_f[j])
508
+ accepted_boxes.append(coords_o[i])
509
+ accepted_scores.append(fused_score)
510
+
511
+ # Flipped-view high-confidence boxes that original missed
512
+ for i in range(len(coords_f)):
513
+ score = scores_f[i]
514
+ if score < self.conf_high:
515
+ continue
516
+
517
+ if len(coords_o) == 0:
518
+ accepted_boxes.append(coords_f[i])
519
+ accepted_scores.append(score)
520
+ continue
521
+
522
+ ious = self._box_iou_one_to_many(coords_f[i], coords_o)
523
+ if np.max(ious) < self.tta_match_iou:
524
+ accepted_boxes.append(coords_f[i])
525
+ accepted_scores.append(score)
526
+
527
+ if not accepted_boxes:
528
+ return []
529
+
530
+ boxes = np.array(accepted_boxes, dtype=np.float32)
531
+ scores = np.array(accepted_scores, dtype=np.float32)
532
+
533
+ keep = self._hard_nms(boxes, scores, self.iou_thres)
534
+ keep = keep[: self.max_det]
535
+
536
+ out = []
537
+ for idx in keep:
538
+ x1, y1, x2, y2 = boxes[idx].tolist()
539
+ out.append(
540
+ BoundingBox(
541
+ x1=int(math.floor(x1)),
542
+ y1=int(math.floor(y1)),
543
+ x2=int(math.ceil(x2)),
544
+ y2=int(math.ceil(y2)),
545
+ cls_id=0,
546
+ conf=float(scores[idx]),
547
+ )
548
+ )
549
+ return out
550
+
551
+ def _predict_tta(self, image: np.ndarray) -> list[BoundingBox]:
552
+ boxes_orig = self._predict_single(image)
553
+
554
+ flipped = cv2.flip(image, 1)
555
+ boxes_flip_raw = self._predict_single(flipped)
556
+
557
+ w = image.shape[1]
558
+ boxes_flip = [
559
+ BoundingBox(
560
+ x1=w - b.x2,
561
+ y1=b.y1,
562
+ x2=w - b.x1,
563
+ y2=b.y2,
564
+ cls_id=b.cls_id,
565
+ conf=b.conf,
566
+ )
567
+ for b in boxes_flip_raw
568
+ ]
569
+
570
+ return self._merge_tta_consensus(boxes_orig, boxes_flip)
571
+
572
+ def predict_batch(
573
+ self,
574
+ batch_images: list[ndarray],
575
+ offset: int,
576
+ n_keypoints: int,
577
+ ) -> list[TVFrameResult]:
578
+ results: list[TVFrameResult] = []
579
+
580
+ for frame_number_in_batch, image in enumerate(batch_images):
581
+ try:
582
+ if self.use_tta:
583
+ boxes = self._predict_tta(image)
584
+ else:
585
+ boxes = self._predict_single(image)
586
+ except Exception as e:
587
+ print(f"⚠️ Inference failed for frame {offset + frame_number_in_batch}: {e}")
588
+ boxes = []
589
+
590
+ results.append(
591
+ TVFrameResult(
592
+ frame_id=offset + frame_number_in_batch,
593
+ boxes=boxes,
594
+ keypoints=[(0, 0) for _ in range(max(0, int(n_keypoints)))],
595
+ )
596
+ )
597
+
598
  return results
weights.onnx CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:0e2308ea9e8784fa26f57b93fe4d66837b07f031f9371e7f988aec0e8d7c9da9
3
  size 19404973
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:be6e4b7e468f655482d0f73509954721601eacb68d376d8191a14bdb7f3d3105
3
  size 19404973