feat(pipeline,config): sync detection thresholds, filter order, and multi-model tracking with FCP main

This commit is contained in:
jetson committed 2026-11-17 10:19:54 +07:00
1 parent ff55a733d6
commit 3cc0919fb1
9 files changed
+698 -118

No files matched your search

+1 -1
View File
@@ -13,7 +13,7 @@ Feedmill Recounter: AI video analysis for counting sacks/boxes in feedmill video
## Architecture
- `app.py`: Flask routes, job queue, model upload/conversion endpoints.
- `src/pipeline.py`: `run_pipeline` / `run_merged_pipeline`; analysis space is fixed 1280x720.
- `src/pipeline.py`: `run_pipeline` / `run_merged_pipeline`; analysis space is fixed 1280x720; pre-stabilizer conf/area filtering + post-polygon box-over-sack suppression; `run_merged_pipeline` selects the first `sack` engine as primary `ByteTrackTracker` (`iou.sack_nms=0.45`) and runs a dedicated per-frame `box_tracker` (`iou.box_nms=0.7`) when a separate engine covers `box`.
- `src/job.py`: in-memory `JobQueue`; jobs die on restart, output dirs survive.
- `src/model_registry.py`: scans `models/` by stem; formats `.engine` > `.pt` > `.onnx`.
- `src/model_conversion.py`: background conversion (`.pt` -> `.onnx`, then `.pt` -> `.engine`; Ultralytics cannot export an engine from ONNX); only one at a time and blocks analysis.
+5
View File
@@ -84,6 +84,11 @@ version tags are cut in this repo — `main` is the release line).
counter does (horizontal at the mean y of its two endpoints).
### Changed
- **Sync detection thresholds, filter ordering, and multi-model tracking with FCP `main` (`91d8b48`)**:
- `detection.sack_conf` 0.30 → **0.35**, plus per-class ByteTrack NMS thresholds `iou.sack_nms` (**0.45**) and `iou.box_nms` (**0.7**) matching FCP `config.yaml:103-116`.
- Pre-stabilizer `conf` and `min_bbox_area` filtering (`_filter_raw_detections`) now runs before `BboxStabilizer` so held occlusions do not drop due to `0.85x` confidence decay and sub-threshold boxes cannot suppress valid sacks; cross-class suppression (`_suppress_sacks_under_boxes`) now uses `iou < threshold` (`>=` drop parity) and runs after polygon/ROI filtering.
- `truck_detection_centroid` selects the largest-area valid truck instead of first match.
- `run_merged_pipeline` now selects the first engine covering `sack` for primary `ByteTrackTracker` (fixing FCP Modes B/D where `v4-best` is truck-only) and runs a dedicated per-frame `box` `ByteTrackTracker` + `BboxStabilizer` when a separate engine covers `box` (fixing FCP Modes C/D).
- **Align corridor filter and default palet zone with FCP main (`91d8b48`)**:
the corridor filter in `src/counting.py` now keeps `_initial_zone` when a
detection sits deep in the truck bed (matching FCP `main`), while
+1 -1
View File
@@ -213,7 +213,7 @@ The web upload form offers three zone modes:
- **Fixed Zone** (default): static zone from `zones.json` presets, built in the fixed 1280×720 analysis frame; never moves; presets editable via `tools/calibrate_zone.py`
- **Auto-detect + Freeze**: auto-detects the truck then locks the ROI permanently after 3 consecutive detections (geometry fixed, truck-presence still tracked for batch state machine)
In multi-model runs, model #1 (primary, alphabetical order) is tracked every frame; supplementary models run every 5th frame; detections from supplementary models get synthetic track IDs so counts and overlays stay stable.
In multi-model runs, the first model covering `sack` runs primary ByteTrack tracking every frame (`iou.sack_nms=0.45`); if a separate model covers `box`, a dedicated `box` ByteTrack tracker runs every frame (`iou.box_nms=0.7`); any remaining non-truck-only models run every 5th frame with synthetic track IDs. Per-class confidence (`sack_conf=0.35`, `box_conf=0.35`) and `min_bbox_area` filtering run before stabilization, matching FCP `main`.
### Calibrating counting zone
+3 -1
View File
@@ -4,7 +4,7 @@
# Missing keys fall back to built-in defaults — partial files are fine.
detection:
sack_conf: 0.3 # detector confidence for sack (FCP config.yaml:87 — reduce undercounting)
sack_conf: 0.35 # detector confidence for sack (FCP config.yaml:109)
box_conf: 0.35 # detector confidence for box
truck_conf: 0.45 # truck detector confidence
@@ -20,6 +20,8 @@ iou:
suppress_sack_box: 0.4 # drop sack overlapping a box (box label wins)
synthetic: 0.3 # synthetic track ID matching
sticky_truck: 0.3 # keep previous main truck pick
sack_nms: 0.45 # primary sack ByteTrack NMS IoU (FCP config.yaml:111)
box_nms: 0.7 # box ByteTrack NMS IoU (FCP config.yaml:115)
roi:
ema_alpha: 0.15 # truck ROI smoothing
+3 -1
View File
@@ -20,7 +20,7 @@ CONFIG_PATH = os.path.join(os.path.dirname(os.path.dirname(__file__)), "config.y
DEFAULTS: dict = {
"detection": {
"sack_conf": 0.3,
"sack_conf": 0.35,
"box_conf": 0.35,
"truck_conf": 0.45,
},
@@ -34,6 +34,8 @@ DEFAULTS: dict = {
"suppress_sack_box": 0.4,
"synthetic": 0.3,
"sticky_truck": 0.3,
"sack_nms": 0.45,
"box_nms": 0.7,
},
"roi": {
"ema_alpha": 0.15,
+225 -111
View File
@@ -235,20 +235,30 @@ def build_batch_manager(cfg: dict) -> BatchLifecycleManager:
)
def _extract_valid_trucks(
detections: list[Detection], truck_conf: float, min_truck_area: float
) -> list[Detection]:
"""Extract truck detections meeting conf and min_bbox_area from tracker output."""
return [
d for d in detections
if d.class_name == "truck"
and d.confidence >= truck_conf
and (d.bbox[2] - d.bbox[0]) * (d.bbox[3] - d.bbox[1]) >= min_truck_area
]
def truck_detection_centroid(
truck_detections: list[Detection],
counting_polygon: Polygon | None = None,
min_overlap: float = 0.5,
) -> tuple[float, float] | None:
"""Centroid of the truck FCP would call "in the area", or None when there is none.
"""Centroid of the largest valid truck FCP calls "in the area", or None.
FCP keeps a truck only when at least 50% of its bbox lies inside the
detection polygon (predict.py:893-902) and uses that as the batch's truck
signal (predict.py:964). Without a polygon any truck counts.
The FSM only leaves IDLE when a truck is detected AND a centroid is known
(src/batch.py:133-134), so the centroid must follow the detection.
FCP keeps trucks with at least 50% of their bbox inside the detection
polygon and picks the largest-area (then highest-confidence) candidate
(predict.py:1074-1095). Without a polygon any truck counts.
"""
best: tuple[float, float, tuple[float, float]] | None = None
for det in truck_detections:
if det.class_name != "truck":
continue
@@ -260,8 +270,10 @@ def truck_detection_centroid(
overlap = counting_polygon.intersection(box(x1, y1, x2, y2)).area
if overlap / area < min_overlap:
continue
return ((x1 + x2) / 2.0, (y1 + y2) / 2.0)
return None
candidate = (area, det.confidence, ((x1 + x2) / 2.0, (y1 + y2) / 2.0))
if best is None or candidate[:2] > best[:2]:
best = candidate
return best[2] if best is not None else None
def update_batch_state(
@@ -396,11 +408,18 @@ def run_pipeline(
model_config.known_classes if model_config.known_classes else None
)
# Run inference at the lowest per-class conf so box TPs in
# [box_conf, sack_conf) survive; per-class gating happens later.
# Run inference at the lowest per-class conf so box/truck TPs survive
# to the per-class gating stages downstream (FCP predict.py:496).
truck_from_tracker = (
truck_model_config is None
and "truck" in (model_config.known_classes or [])
and (effective_filter is None or "truck" in effective_filter)
)
effective_detector_conf = (
min(sack_conf, box_conf) if not effective_filter or "box" in effective_filter else sack_conf
)
if truck_from_tracker:
effective_detector_conf = min(effective_detector_conf, truck_conf)
# Check onnxruntime for .onnx models
if model_config.path.endswith(".onnx"):
@@ -413,28 +432,27 @@ def run_pipeline(
)
shared_model = YOLO(model_config.path)
detector = BaseDetector(
shared_model, conf=effective_detector_conf, class_filter=effective_filter
)
# Truck detector — the FSM's truck signal is the real detection in BOTH
# zone modes (FCP predict.py:882-886), so it always runs.
# Truck detector — only construct BaseDetector when using a separate model
# so we never share one Ultralytics YOLO instance between .track() and .predict().
truck_detector = None
if truck_model_config is not None:
# Load a separate truck detection model
truck_shared = YOLO(truck_model_config.path)
truck_detector = BaseDetector(truck_shared, conf=truck_conf, class_filter=("truck",))
elif "truck" in (model_config.known_classes or []):
# Use the same model for truck detection
truck_detector = BaseDetector(
shared_model, conf=truck_conf, class_filter=("truck",)
)
tracker = ByteTrackTracker(shared_model, conf=effective_detector_conf)
primary_nms = (
cfg["iou"]["box_nms"]
if (effective_filter is not None and "sack" not in effective_filter and "box" in effective_filter)
else cfg["iou"]["sack_nms"]
)
tracker = ByteTrackTracker(
shared_model, conf=effective_detector_conf, iou=primary_nms
)
stabilizer = BboxStabilizer(
ema_alpha=cfg["stabilizer"]["ema_alpha"],
max_hold_frames=cfg["stabilizer"]["max_hold"],
)
min_areas = _scaled_min_areas(cfg, w, h)
roi_tracker = TruckROITracker(
frame_width=w,
frame_height=h,
@@ -507,12 +525,19 @@ def run_pipeline(
if cancel_check and frame_idx % 30 == 0 and cancel_check():
break
# Truck detection — every truck_det_interval frames, the result
# is cached in between (FCP predict.py:882-886 caches
# last_detected_trucks).
# Track every frame (FCP predict.py:1066-1067).
raw_tracked = tracker.update(frame, []) if frame_idx % detect_interval == 0 else []
# Truck detection — separate model runs every truck_det_interval;
# shared tracker extracts truck candidates directly without sharing YOLO.predict().
if truck_detector is not None and frame_idx % truck_det_interval == 0:
last_trucks = truck_detector.detect(frame)
elif truck_from_tracker and frame_idx % detect_interval == 0:
last_trucks = _extract_valid_trucks(
raw_tracked, truck_conf, min_areas.get("truck", 0)
)
has_truck_source = truck_detector is not None or truck_from_tracker
if fixed_zone is not None:
roi = fixed_zone
# The calibrated zone is a fixed AREA: it says where to count,
@@ -522,7 +547,7 @@ def run_pipeline(
truck_present = truck_centroid is not None
else:
roi = roi_tracker.roi
if truck_detector is not None and frame_idx % truck_det_interval == 0:
if has_truck_source and frame_idx % truck_det_interval == 0:
roi = roi_tracker.update(last_trucks)
truck_present = roi is not None and roi.confidence > 0
truck_centroid = None
@@ -540,17 +565,15 @@ def run_pipeline(
roi.line_x_end if roi.line_x_end is not None else roi.x2
)
# Track → Stabilize → Count — on EVERY frame (FCP predict.py:1066-1067:
# "Run line crossing counter on every frame"). Gating it on an open
# batch would drop every crossing that happens before the batch
# opens.
tracked_sacks: list[Detection] = []
counter_input: list[Detection] = []
events: list[dict] = []
raw_tracked = tracker.update(frame, []) if frame_idx % detect_interval == 0 else []
# Filter → Stabilize → Polygon → Cross-class suppress → ROI X-window → Count
raw_tracked = _filter_raw_detections(
raw_tracked, effective_filter, sack_conf, box_conf, min_areas
)
stable = stabilizer.update(raw_tracked)
stable = apply_class_filter(stable, effective_filter)
stable = filter_by_counting_polygon(stable, counting_polygon)
stable = _suppress_sacks_under_boxes(
stable, iou_threshold=cfg["iou"]["suppress_sack_box"]
)
if roi is not None:
tracked_sacks = [
@@ -560,11 +583,6 @@ def run_pipeline(
else:
tracked_sacks = stable
tracked_sacks = _suppress_sacks_under_boxes(
tracked_sacks, iou_threshold=cfg["iou"]["suppress_sack_box"]
)
tracked_sacks = _apply_class_confs(tracked_sacks, sack_conf, box_conf)
tracked_sacks = _apply_min_area(tracked_sacks, _scaled_min_areas(cfg, w, h))
counter_input = countable_detections(tracked_sacks)
events = counter.update(counter_input)
@@ -696,7 +714,10 @@ def _compute_iou(box1: tuple, box2: tuple) -> float:
def _deduplicate_detections(
primary: list[Detection], extras: list[Detection], iou_threshold: float = 0.5
primary: list[Detection],
extras: list[Detection],
iou_threshold: float = 0.5,
extra_against: list[Detection] | tuple[Detection, ...] = (),
) -> list[Detection]:
"""Drop a detection that duplicates the same object seen by ANOTHER model.
@@ -707,13 +728,15 @@ def _deduplicate_detections(
The tracked primary always wins: an extra detection carries a synthetic
track id, and swapping the id would lose the track's crossing history.
`extra_against` suppresses extras overlapping a separate box_tracker without
merging those box_tracker detections into the primary/synthetic stream.
"""
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
for other in (*kept, *extra_against)
):
continue
kept.append(det)
@@ -723,14 +746,32 @@ def _deduplicate_detections(
def _suppress_sacks_under_boxes(dets, iou_threshold=0.5):
"""Drop sack dets overlapping a box det — same object, box label wins.
ponytail: box-wins heuristic; models without a box class label boxes as
sack. Upgrade path: per-model provenance field on Detection.
Matches FCP's drop_sacks_overlapping_boxes (src/counting.py:487):
keeps a sack iff all box IoUs < iou_threshold; iou_threshold <= 0 disables.
"""
if iou_threshold <= 0:
return dets
boxes = [d for d in dets if d.class_name == "box"]
if not boxes:
return dets
return [d for d in dets if d.class_name != "sack"
or not any(_compute_iou(d.bbox, b.bbox) > iou_threshold for b in boxes)]
return [
d for d in dets
if d.class_name != "sack"
or all(_compute_iou(d.bbox, b.bbox) < iou_threshold for b in boxes)
]
def _filter_raw_detections(
dets: list[Detection],
class_filter: list[str] | None,
sack_conf: float,
box_conf: float,
min_areas: dict,
) -> list[Detection]:
"""Apply class filter, per-class conf floor, and min bbox area before stabilization."""
filtered = apply_class_filter(dets, class_filter)
filtered = _apply_class_confs(filtered, sack_conf, box_conf)
return _apply_min_area(filtered, min_areas)
def _apply_class_confs(dets, sack_conf, box_conf):
@@ -833,54 +874,117 @@ def run_merged_pipeline(
w, h = analysis_size(src_w, src_h)
print(f"[PIPELINE] source {src_w}x{src_h} -> analysis {w}x{h}")
# Load all detectors
detectors = []
# Load all models once, resolve each model's effective class filter
models = []
eff_filters: list[list[str] | None] = []
for mcfg in model_configs:
if mcfg.path.endswith(".onnx"):
try:
import onnxruntime
import onnxruntime # noqa: F401
except ImportError:
raise RuntimeError(
f"onnxruntime not installed. Cannot load '{mcfg.filename}'. "
f"Use the .engine version instead."
)
model = YOLO(mcfg.path)
eff_filter = (class_filters or {}).get(mcfg.stem) or mcfg.known_classes or None
# Inference at lowest per-class conf so box TPs in [box_conf, sack_conf)
# survive; per-class gating happens later.
det_conf = (
min(sack_conf, box_conf) if not eff_filter or "box" in eff_filter else sack_conf
models.append(YOLO(mcfg.path))
eff_filters.append(
(class_filters or {}).get(mcfg.stem)
or (class_filters or {}).get(mcfg.filename)
or mcfg.known_classes
or None
)
detectors.append(BaseDetector(model, conf=det_conf, class_filter=eff_filter))
# Truck detector — the FSM's truck signal is the real detection in BOTH
# zone modes (FCP predict.py:882-886), so it always runs.
def _is_truck_only(ef: list[str] | tuple[str, ...] | None) -> bool:
return ef is not None and set(ef) == {"truck"}
# Primary tracker: first engine covering "sack" (FCP predict.py:474);
# otherwise first non-truck-only engine, fallback 0.
primary_idx = next(
(i for i, ef in enumerate(eff_filters) if ef is None or "sack" in ef),
next((i for i, ef in enumerate(eff_filters) if not _is_truck_only(ef)), 0),
)
primary_filter = eff_filters[primary_idx]
# Dedicated box tracker when a separate engine covers "box" (FCP predict.py:506-511).
box_idx = (
next(
(
i for i, ef in enumerate(eff_filters)
if i != primary_idx and (ef is None or "box" in ef)
),
None,
)
if primary_filter is not None and "box" not in primary_filter
else None
)
# Resolve truck source BEFORE building trackers so we include truck_conf in
# tracker conf when truck shares a model, and never share a YOLO instance
# between ByteTrackTracker (.track) and BaseDetector (.predict).
truck_det = None
truck_source: str | None = None
if truck_model_config is not None:
truck_shared = YOLO(truck_model_config.path)
truck_det = BaseDetector(truck_shared, conf=truck_conf, class_filter=("truck",))
# ponytail: first-match truck detector; could prefer dedicated truck model over sack model w/ truck class
truck_source = "detector"
else:
for i, mcfg in enumerate(model_configs):
if "truck" in (mcfg.known_classes or []):
truck_det = detectors[i]
break
truck_idx = next(
(
i for i, (mcfg, ef) in enumerate(zip(model_configs, eff_filters))
if (ef is None or "truck" in ef)
and ("truck" in (mcfg.known_classes or []) or (ef is not None and "truck" in ef))
),
None,
)
if truck_idx == primary_idx:
truck_source = "primary"
elif box_idx is not None and truck_idx == box_idx:
truck_source = "box"
elif truck_idx is not None:
truck_det = BaseDetector(models[truck_idx], conf=truck_conf, class_filter=("truck",))
truck_source = "detector"
# Single tracker using first model's weights
tracker_model = YOLO(model_configs[0].path)
primary_eff = (
(class_filters or {}).get(model_configs[0].stem)
or model_configs[0].known_classes
or None
)
effective_detector_conf = (
min(sack_conf, box_conf) if not primary_eff or "box" in primary_eff else sack_conf
min(sack_conf, box_conf) if not primary_filter or "box" in primary_filter else sack_conf
)
tracker = ByteTrackTracker(tracker_model, conf=effective_detector_conf)
if truck_source == "primary":
effective_detector_conf = min(effective_detector_conf, truck_conf)
primary_nms = (
cfg["iou"]["box_nms"]
if (primary_filter is not None and "sack" not in primary_filter and "box" in primary_filter)
else cfg["iou"]["sack_nms"]
)
tracker = ByteTrackTracker(
models[primary_idx], conf=effective_detector_conf, iou=primary_nms
)
box_tracker = None
box_stabilizer = None
box_filter: list[str] | None = None
if box_idx is not None:
box_filter = eff_filters[box_idx]
box_det_conf = min(box_conf, truck_conf) if truck_source == "box" else box_conf
box_tracker = ByteTrackTracker(
models[box_idx], conf=box_det_conf, iou=cfg["iou"]["box_nms"]
)
box_stabilizer = BboxStabilizer(
ema_alpha=cfg["stabilizer"]["ema_alpha"],
max_hold_frames=cfg["stabilizer"]["max_hold"],
)
# Supplementary detectors: any remaining non-truck-only engines.
extra_detectors = []
for i, ef in enumerate(eff_filters):
if i in (primary_idx, box_idx) or _is_truck_only(ef):
continue
det_conf = min(sack_conf, box_conf) if not ef or "box" in ef else sack_conf
extra_detectors.append(BaseDetector(models[i], conf=det_conf, class_filter=ef))
stabilizer = BboxStabilizer(
ema_alpha=cfg["stabilizer"]["ema_alpha"],
max_hold_frames=cfg["stabilizer"]["max_hold"],
)
min_areas = _scaled_min_areas(cfg, w, h)
synthetic = SyntheticIdAssigner(
iou_threshold=cfg["iou"]["synthetic"],
max_age=cfg["stabilizer"]["max_hold"],
@@ -916,13 +1020,6 @@ def run_merged_pipeline(
# Last truck detections — kept between detection frames (FCP caches
# last_detected_trucks, predict.py:882-886).
last_trucks: list[Detection] = []
# Primary model's class filter (mirrors eff_filter above) — applied to
# ByteTrack output so UI class checkboxes apply to the primary model too.
primary_filter = (
(class_filters or {}).get(model_configs[0].stem)
or model_configs[0].known_classes
or None
)
def on_batch_end(record):
nonlocal completed_batches
@@ -938,6 +1035,8 @@ def run_merged_pipeline(
# (predict.py:1021-1022).
counter.reset_state()
stabilizer.reset()
if box_stabilizer is not None:
box_stabilizer.reset()
batch_mgr.on_batch_start(on_batch_start)
batch_mgr.on_batch_end(on_batch_end)
@@ -959,12 +1058,28 @@ def run_merged_pipeline(
if cancel_check and frame_idx % 30 == 0 and cancel_check():
break
# Truck detection — every truck_det_interval frames, the result
# is cached in between (FCP predict.py:882-886 caches
# last_detected_trucks).
if truck_det is not None and frame_idx % truck_det_interval == 0:
last_trucks = truck_det.detect(frame)
# Primary & dedicated box trackers run every frame (FCP predict.py:1041, 1103).
raw_primary = tracker.update(frame, []) if frame_idx % detect_interval == 0 else []
raw_boxes_all = (
box_tracker.update(frame, [])
if (box_tracker is not None and frame_idx % detect_interval == 0)
else []
)
# Truck detection — separate model runs every truck_det_interval;
# shared tracker extracts truck candidates directly (FCP predict.py:1062-1071).
if truck_source == "detector" and truck_det is not None and frame_idx % truck_det_interval == 0:
last_trucks = truck_det.detect(frame)
elif truck_source == "primary" and frame_idx % detect_interval == 0:
last_trucks = _extract_valid_trucks(
raw_primary, truck_conf, min_areas.get("truck", 0)
)
elif truck_source == "box" and frame_idx % detect_interval == 0:
last_trucks = _extract_valid_trucks(
raw_boxes_all, truck_conf, min_areas.get("truck", 0)
)
has_truck_source = truck_source is not None
if fixed_zone is not None:
roi = fixed_zone
# The calibrated zone is a fixed AREA: it says where to count,
@@ -974,7 +1089,7 @@ def run_merged_pipeline(
truck_present = truck_centroid is not None
else:
roi = roi_tracker.roi
if truck_det is not None and frame_idx % truck_det_interval == 0:
if has_truck_source and frame_idx % truck_det_interval == 0:
roi = roi_tracker.update(last_trucks)
truck_present = roi is not None and roi.confidence > 0
truck_centroid = None
@@ -992,54 +1107,53 @@ def run_merged_pipeline(
roi.line_x_end if roi.line_x_end is not None else roi.x2
)
# Detection + tracking — on EVERY frame (FCP predict.py:1066-1067:
# "Run line crossing counter on every frame"). Gating it on an open
# batch would drop every crossing that happens before the batch
# opens.
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)
# Pre-stabilizer per-class filtering for primary & dedicated box streams
primary = _filter_raw_detections(
raw_primary, primary_filter, sack_conf, box_conf, min_areas
)
raw_boxes: list[Detection] = []
if box_tracker is not None and box_stabilizer is not None:
raw_boxes = _filter_raw_detections(
raw_boxes_all, box_filter, sack_conf, box_conf, min_areas
)
raw_boxes = [d for d in raw_boxes if d.class_name == "box"]
# 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:
extra_detectors = [d for i, d in enumerate(detectors) if i != 0]
if extra_detectors and frame_idx % sup_det_interval == 0:
with ThreadPoolExecutor(max_workers=len(extra_detectors)) as pool:
futures = {pool.submit(d.detect, frame): d for d in extra_detectors}
for future in as_completed(futures):
try:
extras.extend(future.result())
except Exception:
pass
extras = _apply_class_confs(extras, sack_conf, box_conf)
extras = _apply_min_area(extras, min_areas)
# 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.
# Deduplicate ACROSS models only — also compare extras against
# dedicated box_tracker so extra boxes do not double-count.
merged = _deduplicate_detections(
primary, extras, iou_threshold=cfg["iou"]["dedup"]
primary, extras, iou_threshold=cfg["iou"]["dedup"], extra_against=raw_boxes
)
# Give supplementary (track_id=None) dets stable negative ids
assigned = synthetic.assign(merged)
# Stabilize and filter to ROI
# Stabilize primary (+ supplementary), then dedicated box stream if configured
stable = stabilizer.update(assigned)
if box_stabilizer is not None:
stable = stable + box_stabilizer.update(raw_boxes)
stable = filter_by_counting_polygon(stable, counting_polygon)
stable = _suppress_sacks_under_boxes(
stable, iou_threshold=cfg["iou"]["suppress_sack_box"]
)
if roi is not None:
tracked = [d for d in stable if roi.contains_x((d.bbox[0] + d.bbox[2]) / 2.0)]
else:
tracked = stable
tracked = _suppress_sacks_under_boxes(
tracked, iou_threshold=cfg["iou"]["suppress_sack_box"]
)
tracked = _apply_class_confs(tracked, sack_conf, box_conf)
tracked = _apply_min_area(tracked, _scaled_min_areas(cfg, w, h))
# Count using only detections with track_id (tracker results)
counter_input = countable_detections(
[d for d in tracked if d.track_id is not None]
+5 -3
View File
@@ -72,13 +72,13 @@ def test_load_config_raises_on_invalid_value(tmp_path):
def test_partial_yaml_only_box_conf_merges(tmp_path):
"""Only detection.box_conf overrides; sack_conf stays at default 0.3."""
"""Only detection.box_conf overrides; sack_conf stays at default 0.35."""
p = tmp_path / "config.yaml"
p.write_text("detection:\n box_conf: 0.25\n", encoding="utf-8")
cfg = load_config(str(p))
assert cfg["detection"]["box_conf"] == 0.25
assert cfg["detection"]["sack_conf"] == 0.3
assert cfg["detection"]["sack_conf"] == 0.35
assert cfg["min_bbox_area"] == DEFAULTS["min_bbox_area"]
assert _section_keys(cfg) == _section_keys(DEFAULTS)
@@ -170,9 +170,11 @@ def test_truck_roi_tracker_accepts_sticky_iou():
def test_detection_thresholds_match_fcp():
cfg = load_config()
assert cfg["detection"]["sack_conf"] == 0.30
assert cfg["detection"]["sack_conf"] == 0.35
assert cfg["detection"]["box_conf"] == 0.35
assert cfg["detection"]["truck_conf"] == 0.45
assert cfg["iou"]["sack_nms"] == 0.45
assert cfg["iou"]["box_nms"] == 0.7
assert cfg["min_bbox_area"]["sack"] == 1500
assert cfg["min_bbox_area"]["box"] == 1000
assert cfg["min_bbox_area"]["truck"] == 5000
+447
View File
@@ -1784,3 +1784,450 @@ def test_pipeline_forwards_zone_polygons_to_dashboard(tmp_path, monkeypatch):
assert seen, "dashboard.draw() was never called"
assert all(call["counting_polygon"] is counting for call in seen)
assert all(call["truck_polygon"] is truck for call in seen)
# ── FCP full pipeline parity (pre-stabilizer filter, suppression, Mode D) ──
def test_truck_detection_centroid_picks_largest_valid_truck():
"""FCP picks the largest valid truck inside the counting polygon (predict.py:1088-1093)."""
from src.pipeline import truck_detection_centroid
poly = _fcp_polygon()
small = Detection(
bbox=(600.0, 100.0, 700.0, 200.0), confidence=0.95, class_id=2,
class_name="truck", track_id=1,
) # area 10_000, centroid (650, 150)
large = Detection(
bbox=(700.0, 200.0, 900.0, 400.0), confidence=0.70, class_id=2,
class_name="truck", track_id=2,
) # area 40_000, centroid (800, 300)
assert truck_detection_centroid([small, large], poly) == (800.0, 300.0)
# Equal-area tie-breaker picks higher confidence
eq_low = Detection(
bbox=(600.0, 100.0, 700.0, 200.0), confidence=0.60, class_id=2,
class_name="truck", track_id=3,
)
eq_high = Detection(
bbox=(700.0, 100.0, 800.0, 200.0), confidence=0.90, class_id=2,
class_name="truck", track_id=4,
)
assert truck_detection_centroid([eq_low, eq_high], poly) == (750.0, 150.0)
def test_subthreshold_box_does_not_suppress_valid_sack(tmp_path, monkeypatch):
"""Boxes below box_conf or min_bbox_area.box are dropped before suppression."""
from src import pipeline as pipe_mod
low_conf_box = Detection(
bbox=(590.0, 290.0, 650.0, 350.0), confidence=0.31, class_id=1,
class_name="box", track_id=2,
)
valid_sack_a = Detection(
bbox=(590.0, 290.0, 650.0, 350.0), confidence=0.90, class_id=0,
class_name="sack", track_id=1,
)
tiny_box = Detection(
bbox=(700.0, 290.0, 720.0, 330.0), confidence=0.90, class_id=1,
class_name="box", track_id=4,
) # area 800 < 1000
valid_sack_b = Detection(
bbox=(700.0, 290.0, 740.0, 330.0), confidence=0.90, class_id=0,
class_name="sack", track_id=3,
) # area 1600 >= 1500, IoU with tiny_box = 0.50
counter, _batch = _patch_counting_fakes(
monkeypatch, [valid_sack_a, low_conf_box, valid_sack_b, tiny_box]
)
_patch_stabilizer(monkeypatch, pipe_mod)
video_path = str(tmp_path / "t.mp4")
_write_video(video_path, frames=1)
run_pipeline(
video_path=video_path,
model_config=ModelConfig(
filename="test.pt",
path=str(tmp_path / "test.pt"),
stem="test",
known_classes=["sack", "box"],
),
output_path=str(tmp_path / "out.mp4"),
preview_enabled=False,
)
assert {d.track_id for d in counter.seen} == {1, 3}
def test_occluded_sack_held_by_stabilizer_survives_confidence_decay(tmp_path, monkeypatch):
"""Conf filtering runs before BboxStabilizer so 0.85x decay does not drop held sacks."""
from src import pipeline as pipe_mod
borderline_sack = Detection(
bbox=(590.0, 290.0, 650.0, 350.0), confidence=0.36, class_id=0,
class_name="sack", track_id=1,
) # >= 0.35 on frame 1; held frame 2 decays to 0.306 < 0.35
counter = _RecordingCounter()
batch = _AlwaysCountingBatch()
_patch_pipeline_fakes(monkeypatch)
_patch_tracker(monkeypatch, pipe_mod, [[borderline_sack], []])
monkeypatch.setattr(pipe_mod, "BatchLifecycleManager", lambda *a, **kw: batch)
monkeypatch.setattr(pipe_mod, "MultiClassLineCounter", lambda **kw: counter)
video_path = str(tmp_path / "t.mp4")
_write_video(video_path, frames=2)
run_pipeline(
video_path=video_path,
model_config=ModelConfig(
filename="test.pt",
path=str(tmp_path / "test.pt"),
stem="test",
known_classes=["sack"],
),
output_path=str(tmp_path / "out.mp4"),
preview_enabled=False,
)
assert len(counter.calls_seen) == 2
assert [d.track_id for d in counter.calls_seen[0]] == [1]
assert [d.track_id for d in counter.calls_seen[1]] == [1]
def test_merged_pipeline_selects_first_sack_model_as_primary_and_runs_dedicated_box_tracker(
tmp_path, monkeypatch
):
"""Mode D (truck, sack, box) runs ByteTrack on sack (iou=0.45) and box (iou=0.7) every frame."""
from src import pipeline as pipe_mod
from src.pipeline import run_merged_pipeline
_patch_pipeline_fakes(monkeypatch)
created_trackers: list[dict] = []
class _ModeFakeTracker:
def __init__(self, model, conf=0.0, **kwargs):
self.path = getattr(model, "ckpt_path", "")
self.calls = 0
created_trackers.append({"path": self.path, "conf": conf, "kwargs": kwargs, "inst": self})
def update(self, frame, dets):
self.calls += 1
if "best.pt" in self.path:
return [
Detection(
bbox=(590.0, 290.0, 650.0, 350.0), confidence=0.9,
class_id=0, class_name="sack", track_id=10,
)
]
if "yolo11n" in self.path:
return [
Detection(
bbox=(700.0, 290.0, 760.0, 350.0), confidence=0.9,
class_id=1, class_name="box", track_id=20,
)
]
return []
counter = _RecordingCounter()
batch = _AlwaysCountingBatch()
monkeypatch.setattr(pipe_mod, "ByteTrackTracker", _ModeFakeTracker)
monkeypatch.setattr(pipe_mod, "BatchLifecycleManager", lambda *a, **kw: batch)
monkeypatch.setattr(pipe_mod, "MultiClassLineCounter", lambda **kw: counter)
_patch_stabilizer(monkeypatch, pipe_mod)
video_path = str(tmp_path / "t.mp4")
_write_video(video_path, frames=2)
cfgs = [
ModelConfig(filename="v4-best.pt", path=str(tmp_path / "v4-best.pt"), stem="v4-best", known_classes=["truck", "sack"]),
ModelConfig(filename="best.pt", path=str(tmp_path / "best.pt"), stem="best", known_classes=["sack"]),
ModelConfig(filename="yolo11n.pt", path=str(tmp_path / "yolo11n.pt"), stem="yolo11n", known_classes=["sack", "box"]),
]
filters = {
"v4-best": ["truck"],
"best": ["sack"],
"yolo11n": ["box"],
}
run_merged_pipeline(
video_path=video_path,
model_configs=cfgs,
class_filters=filters,
output_path=str(tmp_path / "merged.mp4"),
preview_enabled=False,
)
assert len(created_trackers) == 2
assert created_trackers[0]["path"].endswith("best.pt")
assert created_trackers[0]["kwargs"].get("iou") == 0.45
assert created_trackers[0]["inst"].calls == 2
assert created_trackers[1]["path"].endswith("yolo11n.pt")
assert created_trackers[1]["kwargs"].get("iou") == 0.7
assert created_trackers[1]["inst"].calls == 2
# Frame 1 (despite sup_det_interval=5) receives both tracked sack and tracked box
assert {(d.class_name, d.track_id) for d in counter.calls_seen[0]} == {("sack", 10), ("box", 20)}
def test_merged_pipeline_mode_c_does_not_share_yolo_between_tracker_and_truck_det(
tmp_path, monkeypatch
):
"""Mode C extracts trucks from primary tracker rather than sharing YOLO with BaseDetector."""
from src import pipeline as pipe_mod
from src.pipeline import run_merged_pipeline
from src.truck_roi import TruckROI
_patch_pipeline_fakes(monkeypatch)
base_detector_paths: list[str] = []
class _RecordingDetector:
def __init__(self, model, conf=0.0, class_filter=None):
base_detector_paths.append(getattr(model, "ckpt_path", ""))
def detect(self, frame):
return []
truck_det = Detection(
bbox=(600.0, 100.0, 800.0, 300.0), confidence=0.8,
class_id=2, class_name="truck", track_id=99,
)
sack_det = Detection(
bbox=(590.0, 290.0, 650.0, 350.0), confidence=0.9,
class_id=0, class_name="sack", track_id=10,
)
box_det = Detection(
bbox=(700.0, 290.0, 760.0, 350.0), confidence=0.9,
class_id=1, class_name="box", track_id=20,
)
class _ModeCTracker:
def __init__(self, model, conf=0.0, **kwargs):
self.path = getattr(model, "ckpt_path", "")
def update(self, frame, dets):
if "v4-best" in self.path:
return [truck_det, sack_det]
if "yolo11n" in self.path:
return [box_det]
return []
batch = _IdleBatch()
counter = _RecordingCounter()
monkeypatch.setattr(pipe_mod, "BaseDetector", _RecordingDetector)
monkeypatch.setattr(pipe_mod, "ByteTrackTracker", _ModeCTracker)
monkeypatch.setattr(pipe_mod, "BatchLifecycleManager", lambda *a, **kw: batch)
monkeypatch.setattr(pipe_mod, "MultiClassLineCounter", lambda **kw: counter)
_patch_stabilizer(monkeypatch, pipe_mod)
video_path = str(tmp_path / "t.mp4")
_write_video(video_path, frames=5)
cfgs = [
ModelConfig(filename="v4-best.pt", path=str(tmp_path / "v4-best.pt"), stem="v4-best", known_classes=["truck", "sack"]),
ModelConfig(filename="yolo11n.pt", path=str(tmp_path / "yolo11n.pt"), stem="yolo11n", known_classes=["sack", "box"]),
]
run_merged_pipeline(
video_path=video_path,
model_configs=cfgs,
class_filters={"v4-best": ["truck", "sack"], "yolo11n": ["box"]},
fixed_zone=TruckROI(x1=400, y1=150, x2=950, y2=720, line_y=182, confidence=1.0, fixed=True),
counting_polygon=_fcp_polygon(),
output_path=str(tmp_path / "merged.mp4"),
preview_enabled=False,
)
assert not any("v4-best" in p for p in base_detector_paths)
assert batch.truck_calls[0] == (True, (700.0, 200.0))
assert {(d.class_name, d.track_id) for d in counter.calls_seen[0]} == {("sack", 10), ("box", 20)}
def test_merged_pipeline_mode_b_uses_single_sack_box_tracker_and_separate_truck_det(
tmp_path, monkeypatch
):
"""Mode B runs one ByteTrackTracker on yolo11n (sack+box) and separate truck_det on v4-best."""
from src import pipeline as pipe_mod
from src.pipeline import run_merged_pipeline
_patch_pipeline_fakes(monkeypatch)
created_trackers: list[dict] = []
detector_filters: list[tuple] = []
class _ModeBDetector:
def __init__(self, model, conf=0.0, class_filter=None):
detector_filters.append((getattr(model, "ckpt_path", ""), class_filter))
def detect(self, frame):
return []
class _ModeBTracker:
def __init__(self, model, conf=0.0, **kwargs):
self.path = getattr(model, "ckpt_path", "")
created_trackers.append({"path": self.path, "conf": conf, "kwargs": kwargs})
def update(self, frame, dets):
return [
Detection(bbox=(590.0, 290.0, 650.0, 350.0), confidence=0.9, class_id=0, class_name="sack", track_id=1),
Detection(bbox=(700.0, 290.0, 760.0, 350.0), confidence=0.9, class_id=1, class_name="box", track_id=2),
]
counter = _RecordingCounter()
batch = _AlwaysCountingBatch()
monkeypatch.setattr(pipe_mod, "BaseDetector", _ModeBDetector)
monkeypatch.setattr(pipe_mod, "ByteTrackTracker", _ModeBTracker)
monkeypatch.setattr(pipe_mod, "BatchLifecycleManager", lambda *a, **kw: batch)
monkeypatch.setattr(pipe_mod, "MultiClassLineCounter", lambda **kw: counter)
_patch_stabilizer(monkeypatch, pipe_mod)
video_path = str(tmp_path / "t.mp4")
_write_video(video_path, frames=1)
cfgs = [
ModelConfig(filename="v4-best.pt", path=str(tmp_path / "v4-best.pt"), stem="v4-best", known_classes=["truck", "sack"]),
ModelConfig(filename="yolo11n.pt", path=str(tmp_path / "yolo11n.pt"), stem="yolo11n", known_classes=["sack", "box"]),
]
run_merged_pipeline(
video_path=video_path,
model_configs=cfgs,
class_filters={"v4-best": ["truck"], "yolo11n": ["sack", "box"]},
output_path=str(tmp_path / "merged.mp4"),
preview_enabled=False,
)
assert len(created_trackers) == 1
assert created_trackers[0]["path"].endswith("yolo11n.pt")
assert created_trackers[0]["kwargs"].get("iou") == 0.45
assert any("v4-best" in p and cf == ("truck",) for p, cf in detector_filters)
assert {(d.class_name, d.track_id) for d in counter.calls_seen[0]} == {("sack", 1), ("box", 2)}
def test_merged_pipeline_deduplicates_extra_boxes_against_box_tracker(tmp_path, monkeypatch):
"""Extra supplementary model boxes overlapping box_tracker must not double-count."""
from src import pipeline as pipe_mod
from src.pipeline import run_merged_pipeline
_patch_pipeline_fakes(monkeypatch)
class _ExtraDetector:
def __init__(self, model, conf=0.0, class_filter=None):
self.path = getattr(model, "ckpt_path", "")
def detect(self, frame):
if "unified" in self.path:
return [
Detection(
bbox=(705.0, 292.0, 765.0, 352.0), confidence=0.85,
class_id=1, class_name="box", track_id=None,
)
]
return []
class _DualTracker:
def __init__(self, model, conf=0.0, **kwargs):
self.path = getattr(model, "ckpt_path", "")
def update(self, frame, dets):
if "best.pt" in self.path:
return [Detection(bbox=(590.0, 290.0, 650.0, 350.0), confidence=0.9, class_id=0, class_name="sack", track_id=10)]
if "yolo11n" in self.path:
return [Detection(bbox=(700.0, 290.0, 760.0, 350.0), confidence=0.9, class_id=1, class_name="box", track_id=20)]
return []
counter = _RecordingCounter()
batch = _AlwaysCountingBatch()
monkeypatch.setattr(pipe_mod, "BaseDetector", _ExtraDetector)
monkeypatch.setattr(pipe_mod, "ByteTrackTracker", _DualTracker)
monkeypatch.setattr(pipe_mod, "BatchLifecycleManager", lambda *a, **kw: batch)
monkeypatch.setattr(pipe_mod, "MultiClassLineCounter", lambda **kw: counter)
_patch_stabilizer(monkeypatch, pipe_mod)
video_path = str(tmp_path / "t.mp4")
_write_video(video_path, frames=5)
cfgs = [
ModelConfig(filename="best.pt", path=str(tmp_path / "best.pt"), stem="best", known_classes=["sack"]),
ModelConfig(filename="yolo11n.pt", path=str(tmp_path / "yolo11n.pt"), stem="yolo11n", known_classes=["box"]),
ModelConfig(filename="unified.pt", path=str(tmp_path / "unified.pt"), stem="unified", known_classes=["sack", "box"]),
]
run_merged_pipeline(
video_path=video_path,
model_configs=cfgs,
output_path=str(tmp_path / "merged.mp4"),
preview_enabled=False,
)
frame5_boxes = [d for d in counter.calls_seen[4] if d.class_name == "box"]
assert [d.track_id for d in frame5_boxes] == [20]
def test_merged_pipeline_batch_start_resets_box_stabilizer(tmp_path, monkeypatch):
"""on_batch_start resets both primary stabilizer and dedicated box_stabilizer."""
from src import pipeline as pipe_mod
from src.pipeline import run_merged_pipeline
_patch_pipeline_fakes(monkeypatch)
stabilizers: list = []
class _TrackingStabilizer(_RecordingStabilizer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
stabilizers.append(self)
batch = _BatchStartFiringBatch()
counter = _RecordingCounter()
monkeypatch.setattr(pipe_mod, "BboxStabilizer", _TrackingStabilizer)
monkeypatch.setattr(pipe_mod, "BatchLifecycleManager", lambda *a, **kw: batch)
monkeypatch.setattr(pipe_mod, "MultiClassLineCounter", lambda **kw: counter)
video_path = str(tmp_path / "t.mp4")
_write_video(video_path, frames=2)
cfgs = [
ModelConfig(filename="best.pt", path=str(tmp_path / "best.pt"), stem="best", known_classes=["sack"]),
ModelConfig(filename="yolo11n.pt", path=str(tmp_path / "yolo11n.pt"), stem="yolo11n", known_classes=["box"]),
]
run_merged_pipeline(
video_path=video_path,
model_configs=cfgs,
output_path=str(tmp_path / "merged.mp4"),
preview_enabled=False,
)
assert len(stabilizers) == 2
assert all(s.reset_calls == 1 for s in stabilizers)
def test_box_outside_roi_x_but_inside_counting_polygon_still_suppresses_sack(tmp_path, monkeypatch):
"""Cross-class suppression runs before roi.contains_x (FCP predict.py:1137->1227)."""
from src import pipeline as pipe_mod
from src.truck_roi import TruckROI
edge_box = Detection(
bbox=(355.0, 290.0, 425.0, 350.0), confidence=0.90, class_id=1,
class_name="box", track_id=2,
) # cx=390 (inside counting_poly, left of roi.x1=400)
mislabeled_sack = Detection(
bbox=(375.0, 290.0, 445.0, 350.0), confidence=0.90, class_id=0,
class_name="sack", track_id=1,
) # cx=410 (inside roi.x1=400), IoU = 50/90 = 0.556 >= 0.4
counter, _batch = _patch_counting_fakes(monkeypatch, [edge_box, mislabeled_sack])
_patch_stabilizer(monkeypatch, pipe_mod)
video_path = str(tmp_path / "t.mp4")
_write_video(video_path, frames=1)
poly = Polygon([(300, 100), (300, 700), (950, 700), (950, 100)])
fixed = TruckROI(x1=400, y1=200, x2=900, y2=700, line_y=220, confidence=1.0, fixed=True)
run_pipeline(
video_path=video_path,
model_config=ModelConfig(
filename="test.pt",
path=str(tmp_path / "test.pt"),
stem="test",
known_classes=["sack", "box"],
),
fixed_zone=fixed,
counting_polygon=poly,
output_path=str(tmp_path / "out.mp4"),
preview_enabled=False,
)
assert counter.seen == []
+8
View File
@@ -131,3 +131,11 @@ def test_two_sacks_unaffected():
def test_empty_input():
assert _suppress_sacks_under_boxes([]) == []
def test_overlapping_sack_at_exact_threshold_dropped():
"""IoU == threshold drops sack (>= parity with FCP); threshold <= 0 disables."""
box = det((0, 0, 100, 100), class_name="box")
sack = det((0, 0, 50, 100), class_name="sack") # IoU = 5000 / 10000 = 0.5 exact
assert [d.class_name for d in _suppress_sacks_under_boxes([box, sack], iou_threshold=0.5)] == ["box"]
assert _suppress_sacks_under_boxes([box, sack], iou_threshold=0.0) == [box, sack]