fix: dedup across models only - a same-model overlap is a real sack
The merged pipeline ran a same-class IoU-0.5 dedup over ALL detections, including the primary model's own tracked detections. FCP keeps every tracked detection - the detector's own NMS already removed the duplicates inside a model (predict.py:891). Two sacks stacked on the truck overlap by more than IoU 0.5, so the recounter dropped one of them and lost its crossing: 54 detections dropped in 400 frames of the test clip, and 3 fewer sacks than FCP on the 20-minute clip (158 vs 161). The dedup now compares only detections from DIFFERENT models, and the tracked primary always wins: an extra carries a synthetic track id, and swapping the id would lose the track's crossing history.
This commit is contained in:
1 parent
f43044cc9e
commit
ac2a2350ad
2 files changed
+99
-21
No files matched your search
+31
-21
@@ -689,20 +689,28 @@ def _compute_iou(box1: tuple, box2: tuple) -> float:
|
||||
return inter / union if union > 0 else 0.0
|
||||
|
||||
|
||||
def _deduplicate_detections(dets: list[Detection], iou_threshold: float = 0.5) -> list[Detection]:
|
||||
if not dets:
|
||||
return dets
|
||||
dets = sorted(dets, key=lambda d: d.confidence, reverse=True)
|
||||
kept: list[Detection] = []
|
||||
for det in dets:
|
||||
is_dup = False
|
||||
for existing in kept:
|
||||
if existing.class_name == det.class_name:
|
||||
if _compute_iou(existing.bbox, det.bbox) > iou_threshold:
|
||||
is_dup = True
|
||||
break
|
||||
if not is_dup:
|
||||
kept.append(det)
|
||||
def _deduplicate_detections(
|
||||
primary: list[Detection], extras: list[Detection], iou_threshold: float = 0.5
|
||||
) -> list[Detection]:
|
||||
"""Drop a detection that duplicates the same object seen by ANOTHER model.
|
||||
|
||||
FCP keeps every tracked detection — the detector's own NMS already
|
||||
removed the duplicates inside a model (predict.py:891). Comparing two
|
||||
detections of the SAME model here would drop real, overlapping sacks (a
|
||||
stack on the truck) and silently lose crossings.
|
||||
|
||||
The tracked primary always wins: an extra detection carries a synthetic
|
||||
track id, and swapping the id would lose the track's crossing history.
|
||||
"""
|
||||
kept = list(primary)
|
||||
for det in sorted(extras, key=lambda d: d.confidence, reverse=True):
|
||||
if any(
|
||||
other.class_name == det.class_name
|
||||
and _compute_iou(other.bbox, det.bbox) > iou_threshold
|
||||
for other in kept
|
||||
):
|
||||
continue
|
||||
kept.append(det)
|
||||
return kept
|
||||
|
||||
|
||||
@@ -978,29 +986,31 @@ def run_merged_pipeline(
|
||||
# "Run line crossing counter on every frame"). Gating it on an open
|
||||
# batch would drop every crossing that happens before the batch
|
||||
# opens.
|
||||
all_detections: list[Detection] = []
|
||||
tracked: list[Detection] = []
|
||||
counter_input: list[Detection] = []
|
||||
events: list[dict] = []
|
||||
# Primary: tracker gives detections WITH track_id for counting
|
||||
primary = tracker.update(frame, []) if frame_idx % detect_interval == 0 else []
|
||||
primary = apply_class_filter(primary, primary_filter)
|
||||
all_detections.extend(primary)
|
||||
|
||||
# Supplementary: run extra models every N frames for richer annotations
|
||||
extras: list[Detection] = []
|
||||
if len(detectors) > 1 and frame_idx % sup_det_interval == 0:
|
||||
with ThreadPoolExecutor(max_workers=len(detectors) - 1) as pool:
|
||||
extras = [d for i, d in enumerate(detectors) if i != 0]
|
||||
futures = {pool.submit(d.detect, frame): d for d in extras}
|
||||
extra_detectors = [d for i, d in enumerate(detectors) if i != 0]
|
||||
futures = {pool.submit(d.detect, frame): d for d in extra_detectors}
|
||||
for future in as_completed(futures):
|
||||
try:
|
||||
all_detections.extend(future.result())
|
||||
extras.extend(future.result())
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Deduplicate
|
||||
# Deduplicate ACROSS models only — the same object seen by two
|
||||
# models is one object. Inside one model the detector's own NMS
|
||||
# already did that (FCP predict.py:891); deduping there drops real,
|
||||
# overlapping sacks (a stack on the truck) and loses crossings.
|
||||
merged = _deduplicate_detections(
|
||||
all_detections, iou_threshold=cfg["iou"]["dedup"]
|
||||
primary, extras, iou_threshold=cfg["iou"]["dedup"]
|
||||
)
|
||||
|
||||
# Give supplementary (track_id=None) dets stable negative ids
|
||||
|
||||
@@ -1588,3 +1588,71 @@ def test_fixed_mode_uses_the_truck_detector_for_the_batch_signal(tmp_path, monke
|
||||
assert len(detector_calls) == 2, "truck detection must run every 5th frame"
|
||||
assert [detected for detected, _ in batch.truck_calls] == [False] * 4 + [True] * 8
|
||||
assert batch.truck_calls[-1][1] == (700.0, 200.0)
|
||||
|
||||
|
||||
# ── Cross-model dedup only (FCP predict.py:891) ──────────────────────────
|
||||
|
||||
# Two sacks of the SAME model overlapping by IoU 0.56 (a stack on the truck).
|
||||
_OVERLAP_A = Detection(
|
||||
bbox=(600.0, 300.0, 700.0, 400.0), confidence=0.9, class_id=0,
|
||||
class_name="sack", track_id=1,
|
||||
)
|
||||
_OVERLAP_B = Detection(
|
||||
bbox=(620.0, 310.0, 720.0, 410.0), confidence=0.8, class_id=0,
|
||||
class_name="sack", track_id=2,
|
||||
)
|
||||
# The same object seen by ANOTHER model (no track id yet).
|
||||
_OVERLAP_DUPE = Detection(
|
||||
bbox=(605.0, 302.0, 705.0, 402.0), confidence=0.7, class_id=0,
|
||||
class_name="sack", track_id=None,
|
||||
)
|
||||
|
||||
|
||||
def test_deduplicate_detections_only_merges_across_models():
|
||||
"""FCP keeps every tracked detection (predict.py:891).
|
||||
|
||||
Two detections of the SAME model are two objects (sacks stacked on the
|
||||
truck overlap) — dropping the lower-confidence one loses a crossing.
|
||||
A detection that duplicates an object from ANOTHER model is one object.
|
||||
"""
|
||||
from src.pipeline import _deduplicate_detections
|
||||
|
||||
kept = _deduplicate_detections(
|
||||
[_OVERLAP_A, _OVERLAP_B], [_OVERLAP_DUPE], iou_threshold=0.5
|
||||
)
|
||||
assert [d.bbox for d in kept] == [_OVERLAP_A.bbox, _OVERLAP_B.bbox]
|
||||
|
||||
|
||||
def test_deduplicate_detections_keeps_an_extra_that_is_not_a_duplicate():
|
||||
"""An extra detection of another object stays."""
|
||||
from src.pipeline import _deduplicate_detections
|
||||
|
||||
far_away = Detection(
|
||||
bbox=(100.0, 100.0, 200.0, 200.0), confidence=0.7, class_id=0,
|
||||
class_name="sack", track_id=None,
|
||||
)
|
||||
kept = _deduplicate_detections([_OVERLAP_A], [far_away], iou_threshold=0.5)
|
||||
assert [d.bbox for d in kept] == [_OVERLAP_A.bbox, far_away.bbox]
|
||||
|
||||
|
||||
def test_the_merged_runner_keeps_overlapping_sacks_of_one_model(tmp_path, monkeypatch):
|
||||
"""The merged runner must not drop a sack that overlaps another sack."""
|
||||
from src.pipeline import run_merged_pipeline
|
||||
|
||||
counter, _batch = _patch_counting_fakes(monkeypatch, [_OVERLAP_A, _OVERLAP_B])
|
||||
video_path = str(tmp_path / "t.mp4")
|
||||
_write_video(video_path, frames=2)
|
||||
|
||||
run_merged_pipeline(
|
||||
video_path=video_path,
|
||||
model_configs=[
|
||||
ModelConfig(
|
||||
filename="a.pt", path=str(tmp_path / "a.pt"), stem="a",
|
||||
known_classes=["sack"],
|
||||
)
|
||||
],
|
||||
output_path=str(tmp_path / "merged.mp4"),
|
||||
preview_enabled=False,
|
||||
)
|
||||
|
||||
assert {d.bbox for d in counter.seen} == {_OVERLAP_A.bbox, _OVERLAP_B.bbox}
|
||||
Reference in new issue
Block a user