Realfencer commited on
Commit
bbf61fa
·
verified ·
1 Parent(s): 684f265

Upload miner.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. miner.py +310 -38
miner.py CHANGED
@@ -24,20 +24,32 @@ class TVFrameResult(BaseModel):
24
 
25
 
26
  class Miner:
27
- """ONNX Runtime miner. Hard global NMS + sanity filter + dedup + flip TTA, with per-class rescue bonus."""
28
 
29
  class_names = ["cup", "bottle", "can"]
30
- model_class_names = ["bottle", "can", "cup"]
31
- _model_to_competition_cls = np.array([1, 2, 0], dtype=np.int32)
32
  input_size = 1280
33
  iou_thres = 0.3
34
- cross_iou_thresh = 0.7
35
  min_side = 8.0
36
  min_box_area = 100.0
37
  max_aspect_ratio = 10.0
38
  max_det = 300
39
- _conf_thres_array = np.array([0.35, 0.5, 0.5], dtype=np.float32)
40
- _bonus_array = np.array([0.0, 0.0, 0.2], dtype=np.float32)
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
  def __init__(self, path_hf_repo: Path) -> None:
43
  model_path = path_hf_repo / "weights.onnx"
@@ -83,6 +95,8 @@ class Miner:
83
 
84
  self.input_height = self._safe_dim(self.input_shape[2], default=self.input_size)
85
  self.input_width = self._safe_dim(self.input_shape[3], default=self.input_size)
 
 
86
 
87
  print(f"ONNX model loaded from: {model_path}")
88
  print(f"ONNX providers: {self.session.get_providers()}")
@@ -208,9 +222,18 @@ class Miner:
208
  def _cross_class_dedup_op(self, boxes: np.ndarray, scores: np.ndarray,
209
  cls_ids: np.ndarray, iou_thresh: float
210
  ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
 
 
 
 
 
 
 
 
 
211
  n = len(boxes)
212
  if n <= 1:
213
- return boxes, scores, cls_ids
214
  boxes = np.asarray(boxes, dtype=np.float32)
215
  scores = np.asarray(scores, dtype=np.float32)
216
  cls_ids = np.asarray(cls_ids, dtype=np.int32)
@@ -235,8 +258,7 @@ class Miner:
235
  dup = iou > iou_thresh
236
  dup[i] = False
237
  suppressed |= dup
238
- keep_idx = np.array(keep, dtype=np.intp)
239
- return boxes[keep_idx], scores[keep_idx], cls_ids[keep_idx]
240
 
241
  def _filter_sane_boxes(self, boxes: np.ndarray, scores: np.ndarray,
242
  cls_ids: np.ndarray, orig_size: tuple[int, int]
@@ -286,27 +308,130 @@ class Miner:
286
  out[i] = float(np.max(full_scores[cluster])) if np.any(cluster) else 0.0
287
  return out
288
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
289
  def _conf_filter_mask(self, scores: np.ndarray,
290
  cls_ids: np.ndarray) -> np.ndarray:
291
- """Boolean keep-mask: score >= per-class threshold, with a per-class
292
- rescue — if a class has zero boxes passing, admit its top-1 candidate
293
- when its score >= (per-class threshold - per-class bonus)."""
294
  if len(scores) == 0:
295
  return np.zeros(0, dtype=bool)
296
- thr = self._conf_thres_array[cls_ids]
297
- keep = scores >= thr
298
- for c in np.unique(cls_ids):
299
- b = float(self._bonus_array[c])
300
- if b <= 0.0:
301
- continue
302
- cm = cls_ids == c
303
- if keep[cm].any():
304
- continue
305
- idx = np.where(cm)[0]
306
- top = int(idx[int(np.argmax(scores[idx]))])
307
- if scores[top] >= self._conf_thres_array[c] - b:
308
- keep[top] = True
309
- return keep
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
310
 
311
  def _per_view_pipeline(self, boxes: np.ndarray, scores: np.ndarray,
312
  cls_ids: np.ndarray, orig_size: tuple[int, int]
@@ -317,7 +442,7 @@ class Miner:
317
  if len(boxes) == 0:
318
  return boxes, scores, cls_ids
319
  if len(boxes) > 1:
320
- keep = self._hard_nms(boxes, scores, self.iou_thres)
321
  boxes, scores, cls_ids = boxes[keep], scores[keep], cls_ids[keep]
322
  if len(scores) > self.max_det:
323
  top = np.argsort(-scores)[: self.max_det]
@@ -457,7 +582,8 @@ class Miner:
457
  outputs = self.session.run(self.output_names, {self.input_name: input_tensor})
458
  return self._postprocess(outputs[0], ratio, pad, orig_size)
459
 
460
- def _predict_tta(self, image: np.ndarray) -> list[BoundingBox]:
 
461
  boxes_orig = self._predict_single(image)
462
  flipped = cv2.flip(image, 1)
463
  boxes_flip = self._predict_single(flipped)
@@ -471,17 +597,16 @@ class Miner:
471
  ]
472
  all_boxes = boxes_orig + boxes_flip
473
  if not all_boxes:
474
- return []
475
 
476
- coords = np.array(
477
- [[b.x1, b.y1, b.x2, b.y2] for b in all_boxes], dtype=np.float32
 
478
  )
479
- scores = np.array([b.conf for b in all_boxes], dtype=np.float32)
480
- cls_ids = np.array([b.cls_id for b in all_boxes], dtype=np.int32)
481
 
482
  hard_keep = self._per_class_hard_nms(coords, scores, cls_ids, self.iou_thres)
483
  if len(hard_keep) == 0:
484
- return []
485
  if len(hard_keep) > self.max_det:
486
  top = np.argsort(-scores[hard_keep])[: self.max_det]
487
  hard_keep = hard_keep[top]
@@ -492,12 +617,19 @@ class Miner:
492
 
493
  kept_coords = coords[hard_keep]
494
  kept_cls = cls_ids[hard_keep]
 
 
 
495
  if len(kept_coords) > 1:
496
- kept_coords, boosted, kept_cls = self._cross_class_dedup_op(
497
  kept_coords, boosted, kept_cls, self.cross_iou_thresh
498
  )
 
 
 
 
499
 
500
- return [
501
  BoundingBox(
502
  x1=int(math.floor(kept_coords[j, 0])),
503
  y1=int(math.floor(kept_coords[j, 1])),
@@ -508,19 +640,159 @@ class Miner:
508
  )
509
  for j in range(len(kept_coords))
510
  ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
511
 
512
  def predict_batch(self, batch_images: list[ndarray], offset: int,
513
  n_keypoints: int) -> list[TVFrameResult]:
 
 
 
514
  results: list[TVFrameResult] = []
515
  for frame_number_in_batch, image in enumerate(batch_images):
516
  try:
517
- boxes = self._predict_tta(image)
518
  except Exception as e:
519
  print(f"Inference failed for frame {offset + frame_number_in_batch}: {e}")
520
  boxes = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
521
  results.append(
522
  TVFrameResult(
523
- frame_id=offset + frame_number_in_batch,
524
  boxes=boxes,
525
  keypoints=[(0, 0) for _ in range(max(0, int(n_keypoints)))],
526
  )
 
24
 
25
 
26
  class Miner:
27
+ """ONNX Runtime miner with per-class candidates, TTA fusion, and temporal rescue."""
28
 
29
  class_names = ["cup", "bottle", "can"]
30
+ model_class_names = ["cup", "bottle", "can"]
31
+ _model_to_competition_cls = np.array([0, 1, 2], dtype=np.int32)
32
  input_size = 1280
33
  iou_thres = 0.3
34
+ cross_iou_thresh = 0.65
35
  min_side = 8.0
36
  min_box_area = 100.0
37
  max_aspect_ratio = 10.0
38
  max_det = 300
39
+ _conf_thres_array = np.array([0.60, 0.45, 0.50], dtype=np.float32)
40
+ _candidate_conf_thres_array = np.array([0.20, 0.30, 0.30], dtype=np.float32)
41
+ _tta_conf_thres_array = np.array([0.52, 0.37, 0.42], dtype=np.float32)
42
+ _temporal_conf_thres_array = np.array([0.54, 0.39, 0.44], dtype=np.float32)
43
+ _tta_confirmed_views = 1
44
+ temporal_iou_thresh = 0.25
45
+ track_iou_thresh = 0.35
46
+ track_keep_frames = 2
47
+ track_min_conf = np.array([0.50, 0.35, 0.40], dtype=np.float32)
48
+ sparse_candidate_count = 8
49
+ crowded_candidate_count = 28
50
+ crowded_area_ratio = 0.030
51
+ sparse_relax = 0.04
52
+ crowded_raise = 0.04
53
 
54
  def __init__(self, path_hf_repo: Path) -> None:
55
  model_path = path_hf_repo / "weights.onnx"
 
95
 
96
  self.input_height = self._safe_dim(self.input_shape[2], default=self.input_size)
97
  self.input_width = self._safe_dim(self.input_shape[3], default=self.input_size)
98
+ self._tracks: list[dict] = []
99
+ self._last_track_frame_id: int | None = None
100
 
101
  print(f"ONNX model loaded from: {model_path}")
102
  print(f"ONNX providers: {self.session.get_providers()}")
 
222
  def _cross_class_dedup_op(self, boxes: np.ndarray, scores: np.ndarray,
223
  cls_ids: np.ndarray, iou_thresh: float
224
  ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
225
+ keep_idx = self._cross_class_dedup_keep_indices(
226
+ boxes, scores, cls_ids, iou_thresh
227
+ )
228
+ return boxes[keep_idx], scores[keep_idx], cls_ids[keep_idx]
229
+
230
+ def _cross_class_dedup_keep_indices(self, boxes: np.ndarray,
231
+ scores: np.ndarray,
232
+ cls_ids: np.ndarray,
233
+ iou_thresh: float) -> np.ndarray:
234
  n = len(boxes)
235
  if n <= 1:
236
+ return np.arange(n, dtype=np.intp)
237
  boxes = np.asarray(boxes, dtype=np.float32)
238
  scores = np.asarray(scores, dtype=np.float32)
239
  cls_ids = np.asarray(cls_ids, dtype=np.int32)
 
258
  dup = iou > iou_thresh
259
  dup[i] = False
260
  suppressed |= dup
261
+ return np.array(keep, dtype=np.intp)
 
262
 
263
  def _filter_sane_boxes(self, boxes: np.ndarray, scores: np.ndarray,
264
  cls_ids: np.ndarray, orig_size: tuple[int, int]
 
308
  out[i] = float(np.max(full_scores[cluster])) if np.any(cluster) else 0.0
309
  return out
310
 
311
+ def _view_support_per_cluster(self, post_boxes: np.ndarray,
312
+ post_cls: np.ndarray,
313
+ full_boxes: np.ndarray,
314
+ full_cls: np.ndarray,
315
+ full_view_ids: np.ndarray,
316
+ iou_thresh: float) -> np.ndarray:
317
+ n = len(post_boxes)
318
+ if n == 0:
319
+ return np.empty(0, dtype=np.int32)
320
+ full_areas = (np.maximum(0.0, full_boxes[:, 2] - full_boxes[:, 0]) *
321
+ np.maximum(0.0, full_boxes[:, 3] - full_boxes[:, 1]))
322
+ out = np.ones(n, dtype=np.int32)
323
+ for i in range(n):
324
+ bi = post_boxes[i]
325
+ xx1 = np.maximum(bi[0], full_boxes[:, 0])
326
+ yy1 = np.maximum(bi[1], full_boxes[:, 1])
327
+ xx2 = np.minimum(bi[2], full_boxes[:, 2])
328
+ yy2 = np.minimum(bi[3], full_boxes[:, 3])
329
+ inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)
330
+ a_i = max(0.0, float((bi[2] - bi[0]) * (bi[3] - bi[1])))
331
+ iou = inter / (a_i + full_areas - inter + 1e-7)
332
+ cluster = (iou >= iou_thresh) & (full_cls == post_cls[i])
333
+ if np.any(cluster):
334
+ out[i] = int(len(np.unique(full_view_ids[cluster])))
335
+ return out
336
+
337
  def _conf_filter_mask(self, scores: np.ndarray,
338
  cls_ids: np.ndarray) -> np.ndarray:
339
+ """Keep low-score candidates; final acceptance happens after evidence fusion."""
 
 
340
  if len(scores) == 0:
341
  return np.zeros(0, dtype=bool)
342
+ return scores >= self._candidate_conf_thres_array[cls_ids]
343
+
344
+ def _scene_adjustment(self, boxes: list[BoundingBox],
345
+ image_shape: tuple[int, int, int] | None) -> float:
346
+ if not boxes or image_shape is None:
347
+ return 0.0
348
+ h, w = image_shape[:2]
349
+ image_area = max(1.0, float(w * h))
350
+ total_box_area = sum(
351
+ max(0, box.x2 - box.x1) * max(0, box.y2 - box.y1)
352
+ for box in boxes
353
+ )
354
+ area_ratio = float(total_box_area) / image_area
355
+ if len(boxes) >= self.crowded_candidate_count or area_ratio >= self.crowded_area_ratio:
356
+ return self.crowded_raise
357
+ if len(boxes) <= self.sparse_candidate_count and area_ratio < self.crowded_area_ratio * 0.5:
358
+ return -self.sparse_relax
359
+ return 0.0
360
+
361
+ def _adaptive_thresholds(self, cls_ids: np.ndarray,
362
+ boxes: list[BoundingBox],
363
+ image_shape: tuple[int, int, int] | None
364
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
365
+ adjustment = self._scene_adjustment(boxes, image_shape)
366
+ auto = np.clip(
367
+ self._conf_thres_array[cls_ids] + adjustment,
368
+ self._candidate_conf_thres_array[cls_ids] + 0.05,
369
+ 0.95,
370
+ )
371
+ tta = np.clip(
372
+ self._tta_conf_thres_array[cls_ids] + adjustment,
373
+ self._candidate_conf_thres_array[cls_ids],
374
+ auto,
375
+ )
376
+ temporal = np.clip(
377
+ self._temporal_conf_thres_array[cls_ids] + adjustment,
378
+ self._candidate_conf_thres_array[cls_ids],
379
+ auto,
380
+ )
381
+ return auto, tta, temporal
382
+
383
+ def _candidate_accept_mask(self, boxes: list[BoundingBox],
384
+ view_support: np.ndarray,
385
+ image_shape: tuple[int, int, int] | None
386
+ ) -> np.ndarray:
387
+ _, scores, cls_ids = self._boxes_to_arrays(boxes)
388
+ if len(scores) == 0:
389
+ return np.zeros(0, dtype=bool)
390
+ auto_thres, tta_thres, _ = self._adaptive_thresholds(
391
+ cls_ids, boxes, image_shape
392
+ )
393
+ auto = scores >= auto_thres
394
+ tta_confirmed = (
395
+ (scores >= tta_thres) &
396
+ (view_support >= self._tta_confirmed_views)
397
+ )
398
+ return auto | tta_confirmed
399
+
400
+ @staticmethod
401
+ def _boxes_to_arrays(boxes: list[BoundingBox]
402
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
403
+ if not boxes:
404
+ return (
405
+ np.empty((0, 4), dtype=np.float32),
406
+ np.empty(0, dtype=np.float32),
407
+ np.empty(0, dtype=np.int32),
408
+ )
409
+ coords = np.array(
410
+ [[b.x1, b.y1, b.x2, b.y2] for b in boxes], dtype=np.float32
411
+ )
412
+ scores = np.array([b.conf for b in boxes], dtype=np.float32)
413
+ cls_ids = np.array([b.cls_id for b in boxes], dtype=np.int32)
414
+ return coords, scores, cls_ids
415
+
416
+ @staticmethod
417
+ def _image_shape(image: np.ndarray | None) -> tuple[int, int, int] | None:
418
+ if isinstance(image, np.ndarray) and image.ndim == 3:
419
+ return image.shape
420
+ return None
421
+
422
+ @staticmethod
423
+ def _single_box_iou(box: BoundingBox, boxes: np.ndarray) -> np.ndarray:
424
+ if len(boxes) == 0:
425
+ return np.empty(0, dtype=np.float32)
426
+ xx1 = np.maximum(float(box.x1), boxes[:, 0])
427
+ yy1 = np.maximum(float(box.y1), boxes[:, 1])
428
+ xx2 = np.minimum(float(box.x2), boxes[:, 2])
429
+ yy2 = np.minimum(float(box.y2), boxes[:, 3])
430
+ inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)
431
+ a_i = max(0.0, float((box.x2 - box.x1) * (box.y2 - box.y1)))
432
+ areas = (np.maximum(0.0, boxes[:, 2] - boxes[:, 0]) *
433
+ np.maximum(0.0, boxes[:, 3] - boxes[:, 1]))
434
+ return inter / (a_i + areas - inter + 1e-7)
435
 
436
  def _per_view_pipeline(self, boxes: np.ndarray, scores: np.ndarray,
437
  cls_ids: np.ndarray, orig_size: tuple[int, int]
 
442
  if len(boxes) == 0:
443
  return boxes, scores, cls_ids
444
  if len(boxes) > 1:
445
+ keep = self._per_class_hard_nms(boxes, scores, cls_ids, self.iou_thres)
446
  boxes, scores, cls_ids = boxes[keep], scores[keep], cls_ids[keep]
447
  if len(scores) > self.max_det:
448
  top = np.argsort(-scores)[: self.max_det]
 
582
  outputs = self.session.run(self.output_names, {self.input_name: input_tensor})
583
  return self._postprocess(outputs[0], ratio, pad, orig_size)
584
 
585
+ def _predict_tta_candidates(self, image: np.ndarray
586
+ ) -> tuple[list[BoundingBox], np.ndarray]:
587
  boxes_orig = self._predict_single(image)
588
  flipped = cv2.flip(image, 1)
589
  boxes_flip = self._predict_single(flipped)
 
597
  ]
598
  all_boxes = boxes_orig + boxes_flip
599
  if not all_boxes:
600
+ return [], np.empty(0, dtype=np.int32)
601
 
602
+ coords, scores, cls_ids = self._boxes_to_arrays(all_boxes)
603
+ view_ids = np.array(
604
+ [0] * len(boxes_orig) + [1] * len(boxes_flip), dtype=np.int32
605
  )
 
 
606
 
607
  hard_keep = self._per_class_hard_nms(coords, scores, cls_ids, self.iou_thres)
608
  if len(hard_keep) == 0:
609
+ return [], np.empty(0, dtype=np.int32)
610
  if len(hard_keep) > self.max_det:
611
  top = np.argsort(-scores[hard_keep])[: self.max_det]
612
  hard_keep = hard_keep[top]
 
617
 
618
  kept_coords = coords[hard_keep]
619
  kept_cls = cls_ids[hard_keep]
620
+ view_support = self._view_support_per_cluster(
621
+ kept_coords, kept_cls, coords, cls_ids, view_ids, self.iou_thres,
622
+ )
623
  if len(kept_coords) > 1:
624
+ dedup_keep = self._cross_class_dedup_keep_indices(
625
  kept_coords, boosted, kept_cls, self.cross_iou_thresh
626
  )
627
+ kept_coords = kept_coords[dedup_keep]
628
+ boosted = boosted[dedup_keep]
629
+ kept_cls = kept_cls[dedup_keep]
630
+ view_support = view_support[dedup_keep]
631
 
632
+ boxes = [
633
  BoundingBox(
634
  x1=int(math.floor(kept_coords[j, 0])),
635
  y1=int(math.floor(kept_coords[j, 1])),
 
640
  )
641
  for j in range(len(kept_coords))
642
  ]
643
+ return boxes, view_support
644
+
645
+ def _filter_by_evidence(self, boxes: list[BoundingBox],
646
+ view_support: np.ndarray,
647
+ image_shape: tuple[int, int, int] | None
648
+ ) -> list[BoundingBox]:
649
+ keep = self._candidate_accept_mask(boxes, view_support, image_shape)
650
+ return [box for box, ok in zip(boxes, keep) if bool(ok)]
651
+
652
+ def _predict_tta(self, image: np.ndarray) -> list[BoundingBox]:
653
+ boxes, view_support = self._predict_tta_candidates(image)
654
+ return self._filter_by_evidence(boxes, view_support, image.shape)
655
+
656
+ def _has_temporal_support(self, frame_idx: int, box: BoundingBox,
657
+ candidate_boxes: list[list[BoundingBox]],
658
+ initial_keep: list[np.ndarray]) -> bool:
659
+ neighbor_indices = [
660
+ idx for idx in (frame_idx - 1, frame_idx + 1)
661
+ if 0 <= idx < len(candidate_boxes)
662
+ ]
663
+ for idx in neighbor_indices:
664
+ coords, _, cls_ids = self._boxes_to_arrays(candidate_boxes[idx])
665
+ same_cls = cls_ids == box.cls_id
666
+ if not np.any(same_cls):
667
+ continue
668
+ accepted = same_cls & initial_keep[idx]
669
+ if np.any(accepted):
670
+ if np.max(self._single_box_iou(box, coords[accepted])) >= self.temporal_iou_thresh:
671
+ return True
672
+
673
+ two_sided_candidate_support = []
674
+ for idx in (frame_idx - 1, frame_idx + 1):
675
+ if not 0 <= idx < len(candidate_boxes):
676
+ two_sided_candidate_support.append(False)
677
+ continue
678
+ coords, scores, cls_ids = self._boxes_to_arrays(candidate_boxes[idx])
679
+ same_cls = cls_ids == box.cls_id
680
+ if not np.any(same_cls):
681
+ two_sided_candidate_support.append(False)
682
+ continue
683
+ score_ok = scores >= self._temporal_conf_thres_array[cls_ids]
684
+ neighbor_ok = same_cls & score_ok
685
+ supported = (
686
+ np.any(neighbor_ok) and
687
+ np.max(self._single_box_iou(box, coords[neighbor_ok])) >= self.temporal_iou_thresh
688
+ )
689
+ two_sided_candidate_support.append(bool(supported))
690
+ return all(two_sided_candidate_support)
691
+
692
+ def _reset_tracks_if_needed(self, frame_id: int) -> None:
693
+ if self._last_track_frame_id is None:
694
+ self._last_track_frame_id = frame_id - 1
695
+ return
696
+ if frame_id <= self._last_track_frame_id:
697
+ self._tracks = []
698
+ self._last_track_frame_id = frame_id
699
+
700
+ def _track_supported(self, box: BoundingBox, frame_id: int) -> bool:
701
+ best_iou = 0.0
702
+ for track in self._tracks:
703
+ if int(track["cls_id"]) != box.cls_id:
704
+ continue
705
+ age = frame_id - int(track["frame_id"])
706
+ if age < 1 or age > self.track_keep_frames:
707
+ continue
708
+ iou = self._single_box_iou(box, track["coords"])[0]
709
+ best_iou = max(best_iou, float(iou))
710
+ return best_iou >= self.track_iou_thresh
711
+
712
+ def _update_tracks(self, boxes: list[BoundingBox], frame_id: int) -> None:
713
+ fresh_tracks = []
714
+ for track in self._tracks:
715
+ if frame_id - int(track["frame_id"]) <= self.track_keep_frames:
716
+ fresh_tracks.append(track)
717
+ for box in boxes:
718
+ coords = np.array(
719
+ [[box.x1, box.y1, box.x2, box.y2]], dtype=np.float32
720
+ )
721
+ updated = False
722
+ for track in fresh_tracks:
723
+ if int(track["cls_id"]) != box.cls_id:
724
+ continue
725
+ iou = self._single_box_iou(box, track["coords"])[0]
726
+ if iou >= self.track_iou_thresh:
727
+ track["coords"] = coords
728
+ track["frame_id"] = frame_id
729
+ track["conf"] = box.conf
730
+ updated = True
731
+ break
732
+ if not updated:
733
+ fresh_tracks.append(
734
+ {
735
+ "coords": coords,
736
+ "cls_id": box.cls_id,
737
+ "conf": box.conf,
738
+ "frame_id": frame_id,
739
+ }
740
+ )
741
+ self._tracks = fresh_tracks
742
 
743
  def predict_batch(self, batch_images: list[ndarray], offset: int,
744
  n_keypoints: int) -> list[TVFrameResult]:
745
+ candidate_boxes: list[list[BoundingBox]] = []
746
+ view_supports: list[np.ndarray] = []
747
+ image_shapes = [self._image_shape(image) for image in batch_images]
748
  results: list[TVFrameResult] = []
749
  for frame_number_in_batch, image in enumerate(batch_images):
750
  try:
751
+ boxes, view_support = self._predict_tta_candidates(image)
752
  except Exception as e:
753
  print(f"Inference failed for frame {offset + frame_number_in_batch}: {e}")
754
  boxes = []
755
+ view_support = np.empty(0, dtype=np.int32)
756
+ candidate_boxes.append(boxes)
757
+ view_supports.append(view_support)
758
+
759
+ initial_keep: list[np.ndarray] = []
760
+ for boxes, view_support, image_shape in zip(
761
+ candidate_boxes, view_supports, image_shapes
762
+ ):
763
+ initial_keep.append(
764
+ self._candidate_accept_mask(boxes, view_support, image_shape)
765
+ )
766
+
767
+ for frame_number_in_batch, boxes in enumerate(candidate_boxes):
768
+ frame_id = offset + frame_number_in_batch
769
+ self._reset_tracks_if_needed(frame_id)
770
+ keep = initial_keep[frame_number_in_batch].copy()
771
+ _, scores, cls_ids = self._boxes_to_arrays(boxes)
772
+ _, _, temporal_thres = self._adaptive_thresholds(
773
+ cls_ids, boxes, image_shapes[frame_number_in_batch]
774
+ )
775
+ temporal_ready = scores >= temporal_thres
776
+ track_ready = scores >= self.track_min_conf[cls_ids]
777
+ for i, box in enumerate(boxes):
778
+ if keep[i]:
779
+ continue
780
+ has_neighbor_support = (
781
+ bool(temporal_ready[i]) and
782
+ self._has_temporal_support(
783
+ frame_number_in_batch, box, candidate_boxes, initial_keep
784
+ )
785
+ )
786
+ has_track_support = (
787
+ bool(track_ready[i]) and self._track_supported(box, frame_id)
788
+ )
789
+ if has_neighbor_support or has_track_support:
790
+ keep[i] = True
791
+ boxes = [box for box, ok in zip(boxes, keep) if bool(ok)]
792
+ self._update_tracks(boxes, frame_id)
793
  results.append(
794
  TVFrameResult(
795
+ frame_id=frame_id,
796
  boxes=boxes,
797
  keypoints=[(0, 0) for _ in range(max(0, int(n_keypoints)))],
798
  )