From d74ca41e2e1d26576c49bd8eac2209867bb604c9 Mon Sep 17 00:00:00 2001 From: jetson Date: Tue, 27 Oct 2026 14:19:26 +0700 Subject: [PATCH] feat: filter counts calibrated counting polygon (FCP predict.py:939 parity) --- app.py | 42 +++++-- src/job.py | 7 ++ src/pipeline.py | 25 +++++ src/zone_config.py | 24 ++++ tests/test_pipeline.py | 225 ++++++++++++++++++++++++++++++++++++++ tests/test_zone_config.py | 64 ++++++++++- 6 files changed, 375 insertions(+), 12 deletions(-) diff --git a/app.py b/app.py index c4b93bf..8664df9 100644 --- a/app.py +++ b/app.py @@ -18,12 +18,17 @@ from werkzeug.utils import secure_filename from pathlib import Path +from shapely.geometry import Polygon + from src.job import JobQueue from src.model_registry import scan_models, scan_model_groups, ModelConfig from src.preview import extract_thumbnail, extract_sample_frames, probe_video, resize_video_to_max_height from src.pipeline import ANALYSIS_SIZE from src.truck_roi import TruckROI -from src.zone_config import load_zone_config, list_zone_presets, build_static_roi, get_active_zone +from src.zone_config import ( + load_zone_config, list_zone_presets, build_static_roi, build_counting_polygon, + get_active_zone, +) load_dotenv() @@ -142,16 +147,27 @@ def _static_roi(zone: dict) -> TruckROI: return build_static_roi(zone, *ANALYSIS_SIZE) -def _resolve_zone(zone_mode: str, zone_preset: str) -> tuple[str, TruckROI | None, str]: +def _static_polygon(zone: dict) -> Polygon | None: + """Build the counting polygon in FCP's 1280x720 analysis frame. + + Same arithmetic as FCP's hardcoded detection_polygon (predict.py:688-698): + the zone's counting_area scaled by 1280/1920 x 720/1080, truncated. + """ + return build_counting_polygon(zone, *ANALYSIS_SIZE) + + +def _resolve_zone( + zone_mode: str, zone_preset: str +) -> tuple[str, TruckROI | None, str, Polygon | None]: """Resolve the counting zone of a job. - Returns (zone_mode, fixed_zone, zone_preset). "fixed" needs a calibrated - preset on disk; without one the job falls back to "dynamic" so an - uncalibrated deployment still runs (FCP always counts on its calibrated - line, so "fixed" is the default). + Returns (zone_mode, fixed_zone, zone_preset, counting_polygon). "fixed" + needs a calibrated preset on disk; without one the job falls back to + "dynamic" so an uncalibrated deployment still runs (FCP always counts on + its calibrated line, so "fixed" is the default). """ if zone_mode != "fixed": - return zone_mode, None, zone_preset + return zone_mode, None, zone_preset, None zone = None reason = "no zone file" if os.path.isfile(ZONES_PATH): @@ -164,8 +180,8 @@ def _resolve_zone(zone_mode: str, zone_preset: str) -> tuple[str, TruckROI | Non reason = f"unreadable calibration ({exc})" if zone is None: print(f"[ZONE] {reason} at {ZONES_PATH} — falling back to dynamic") - return "dynamic", None, zone_preset - return "fixed", _static_roi(zone), zone_preset or "default" + return "dynamic", None, zone_preset, None + return "fixed", _static_roi(zone), zone_preset or "default", _static_polygon(zone) def _save_and_queue(video, model_configs, class_filters, @@ -186,7 +202,9 @@ def _save_and_queue(video, model_configs, class_filters, # Transcode to 720p max height to save storage and speed up processing video_path = resize_video_to_max_height(video_path, max_height=720) - zone_mode, fixed_zone, zone_preset = _resolve_zone(zone_mode, zone_preset) + zone_mode, fixed_zone, zone_preset, counting_polygon = _resolve_zone( + zone_mode, zone_preset + ) return job_queue.add_job( video_path=video_path, @@ -195,6 +213,7 @@ def _save_and_queue(video, model_configs, class_filters, class_filters=class_filters, zone_mode=zone_mode, fixed_zone=fixed_zone, + counting_polygon=counting_polygon, zone_preset=zone_preset, output_max_height=(int(output_height) if output_height else None), ) @@ -313,7 +332,7 @@ def upload_reuse(): output_height = request.form.get("output_height", "") zone_mode = request.form.get("zone_mode", "fixed") - zone_mode, fixed_zone, zone_preset = _resolve_zone( + zone_mode, fixed_zone, zone_preset, counting_polygon = _resolve_zone( zone_mode, request.form.get("zone_preset", "") ) @@ -323,6 +342,7 @@ def upload_reuse(): class_filters=class_filters, zone_mode=zone_mode, fixed_zone=fixed_zone, + counting_polygon=counting_polygon, zone_preset=zone_preset, output_max_height=(int(output_height) if output_height else None), ) diff --git a/src/job.py b/src/job.py index c65613a..357857d 100644 --- a/src/job.py +++ b/src/job.py @@ -11,6 +11,8 @@ from dataclasses import dataclass, field from enum import Enum, auto from pathlib import Path +from shapely.geometry import Polygon + from src.model_registry import ModelConfig, find_truck_detector from src.naming import annotated_output_name from src.pipeline import run_pipeline, run_merged_pipeline, PipelineResult, MergedPipelineResult @@ -71,6 +73,7 @@ class Job: preview_enabled: bool = True zone_mode: str = "fixed" fixed_zone: TruckROI | None = None + counting_polygon: Polygon | None = None zone_preset: str = "" output_max_height: int | None = None @@ -121,6 +124,7 @@ class JobQueue: source_stem: str = "", zone_mode: str = "fixed", fixed_zone: TruckROI | None = None, + counting_polygon: Polygon | None = None, zone_preset: str = "", output_max_height: int | None = None, ) -> Job: @@ -135,6 +139,7 @@ class JobQueue: output_dir=str(self._output_dir / job_id), zone_mode=zone_mode, fixed_zone=fixed_zone, + counting_polygon=counting_polygon, zone_preset=zone_preset, output_max_height=output_max_height, ) @@ -254,6 +259,7 @@ class JobQueue: class_filter=class_filter, truck_model_config=truck_model_config, fixed_zone=job.fixed_zone, + counting_polygon=job.counting_polygon, freeze_roi=(job.zone_mode == "freeze"), preview_path=job.preview_path, preview_enabled=job.preview_enabled, @@ -308,6 +314,7 @@ class JobQueue: class_filters=job.class_filters, truck_model_config=truck_model_config, fixed_zone=job.fixed_zone, + counting_polygon=job.counting_polygon, freeze_roi=(job.zone_mode == "freeze"), preview_path=job.preview_path, preview_enabled=job.preview_enabled, diff --git a/src/pipeline.py b/src/pipeline.py index 17fb222..d90bd0e 100644 --- a/src/pipeline.py +++ b/src/pipeline.py @@ -13,6 +13,7 @@ from dataclasses import dataclass import cv2 +from shapely.geometry import Point, Polygon from ultralytics import YOLO from src.batch import BatchLifecycleManager @@ -135,6 +136,26 @@ def countable_detections(detections: list[Detection]) -> list[Detection]: return [d for d in detections if d.class_name in ("sack", "box")] +def filter_by_counting_polygon( + detections: list[Detection], counting_polygon: Polygon | None +) -> list[Detection]: + """Drop detections whose bbox centre lies outside the counting polygon. + + FCP parity: predict.py:939-942 keeps a detection only when + detection_polygon.contains(Point((x1 + x2) / 2, (y1 + y3) / 2)) — the + centre of the bbox. A None polygon disables the filter. + """ + if counting_polygon is None: + return detections + return [ + d + for d in detections + if counting_polygon.contains( + Point((d.bbox[0] + d.bbox[2]) / 2.0, (d.bbox[1] + d.bbox[3]) / 2.0) + ) + ] + + def run_pipeline( video_path: str, model_config: ModelConfig, @@ -142,6 +163,7 @@ def run_pipeline( class_filter: list[str] | None = None, truck_model_config: ModelConfig | None = None, fixed_zone: TruckROI | None = None, + counting_polygon: Polygon | None = None, sack_conf: float | None = None, truck_conf: float | None = None, truck_det_interval: int | None = None, @@ -348,6 +370,7 @@ def run_pipeline( raw_tracked = tracker.update(frame, []) if frame_idx % detect_interval == 0 else [] stable = stabilizer.update(raw_tracked) stable = apply_class_filter(stable, effective_filter) + stable = filter_by_counting_polygon(stable, counting_polygon) if roi is not None: tracked_sacks = [ @@ -543,6 +566,7 @@ def run_merged_pipeline( class_filters: dict[str, list[str] | None] | None = None, truck_model_config: ModelConfig | None = None, fixed_zone: TruckROI | None = None, + counting_polygon: Polygon | None = None, sack_conf: float | None = None, truck_conf: float | None = None, truck_det_interval: int | None = None, @@ -762,6 +786,7 @@ def run_merged_pipeline( # Stabilize and filter to ROI stable = stabilizer.update(assigned) + stable = filter_by_counting_polygon(stable, counting_polygon) if roi is not None: tracked = [d for d in stable if roi.contains_x((d.bbox[0] + d.bbox[2]) / 2.0)] else: diff --git a/src/zone_config.py b/src/zone_config.py index 88fea25..a23a810 100644 --- a/src/zone_config.py +++ b/src/zone_config.py @@ -6,6 +6,8 @@ import json import os from typing import Any +from shapely.geometry import Polygon + from src.truck_roi import TruckROI @@ -73,6 +75,28 @@ def list_zone_presets(path: str) -> list[dict[str, Any]]: ] +def build_counting_polygon( + zone: dict[str, Any], video_w: int, video_h: int +) -> Polygon | None: + """Build the counting polygon of a zone, scaled to the video frame. + + zone["counting_area"] holds FCP's detection_poly_pts (predict.py:692-697) + at zone["reference_resolution"]. FCP hardcodes the 1280/1920 x 720/1080 + scale and truncates every coordinate with int() — the arithmetic here is + identical to build_static_roi's, so the polygon matches FCP's + detection_polygon exactly. + + Returns None when the zone has no usable counting_area (no polygon filter). + """ + pts = zone.get("counting_area") or [] + if len(pts) < 3: + return None + ref_w, ref_h = zone.get("reference_resolution", [1920, 1080]) + sx = video_w / ref_w if ref_w else 1.0 + sy = video_h / ref_h if ref_h else 1.0 + return Polygon([(int(p[0] * sx), int(p[1] * sy)) for p in pts]) + + def get_active_zone(path: str, preset_name: str | None = None) -> dict[str, Any] | None: """Get the active preset dict. Falls back to active_preset field if name not given.""" config = load_zone_config(path) diff --git a/tests/test_pipeline.py b/tests/test_pipeline.py index 6a43f6a..247d8de 100644 --- a/tests/test_pipeline.py +++ b/tests/test_pipeline.py @@ -387,6 +387,231 @@ def test_scaled_min_areas_platform_parity(): assert at_1080p["truck"] == 11250 +# ── Counting polygon filter (FCP detection_polygon parity) ────────────── + +# FCP's detection_poly_pts at reference resolution (predict.py:692-697). +FCP_ZONE = { + "counting_area": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]], + "reference_resolution": [1920, 1080], +} + +# centroid (620, 320) — inside FCP's polygon in the 1280x720 analysis frame. +INSIDE_SACK = Detection( + bbox=(590.0, 290.0, 650.0, 350.0), + confidence=0.9, + class_id=0, + class_name="sack", + track_id=1, +) +# centroid (70, 320) — left of FCP's polygon. +OUTSIDE_SACK = Detection( + bbox=(40.0, 290.0, 100.0, 350.0), + confidence=0.9, + class_id=0, + class_name="sack", + track_id=2, +) + + +class _RecordingCounter: + """Counter stub that records every detection set it is handed.""" + + def __init__(self, line_y=0, line_x_start=0, line_x_end=0, margin=0): + self.line_y = line_y + self.line_x_start = line_x_start + self.line_x_end = line_x_end + self.margin = margin + self.loading_count = 0 + self.unloading_count = 0 + self.box_loading_count = 0 + self.box_unloading_count = 0 + self.seen: list[Detection] = [] + + def update(self, detections): + self.seen.extend(detections) + return [] + + +class _AlwaysCountingBatch: + """Batch manager stub: the batch is open, so the counter is always fed.""" + + current_batch_id = 1 + history: list = [] + state = "COUNTING_SACKS" + batch_duration = 0.0 + stabilize_progress = 1.0 + waiting_duration = 0.0 + is_active = True + + def __init__(self, *args, **kwargs): + pass + + def on_batch_end(self, callback): + pass + + def update(self, **kwargs): + pass + + +def _patch_counting_fakes(monkeypatch, detections): + """Stub tracker/batch/counter so the pipeline runs offline.""" + from src import pipeline as pipe_mod + + _patch_pipeline_fakes(monkeypatch) + + class _FakeTracker: + def __init__(self, model, conf=0.0, **kwargs): + pass + + def update(self, frame, dets): + return list(detections) + + counter = _RecordingCounter() + monkeypatch.setattr(pipe_mod, "ByteTrackTracker", _FakeTracker) + monkeypatch.setattr(pipe_mod, "BatchLifecycleManager", _AlwaysCountingBatch) + monkeypatch.setattr(pipe_mod, "MultiClassLineCounter", lambda **kw: counter) + return counter + + +def _fcp_polygon(): + from src.zone_config import build_counting_polygon + + return build_counting_polygon(FCP_ZONE, 1280, 720) + + +def test_run_pipeline_drops_detection_outside_counting_polygon(tmp_path, monkeypatch): + """A centroid outside FCP's detection polygon never reaches the counter.""" + counter = _patch_counting_fakes(monkeypatch, [INSIDE_SACK, OUTSIDE_SACK]) + 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, + counting_polygon=_fcp_polygon(), + ) + + assert counter.seen, "counter never received a detection" + assert {d.bbox for d in counter.seen} == {INSIDE_SACK.bbox} + + +def test_run_pipeline_keeps_detection_inside_counting_polygon(tmp_path, monkeypatch): + """Without a polygon every detection reaches the counter (control).""" + counter = _patch_counting_fakes(monkeypatch, [INSIDE_SACK, OUTSIDE_SACK]) + 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 {d.bbox for d in counter.seen} == {INSIDE_SACK.bbox, OUTSIDE_SACK.bbox} + + +def test_run_merged_pipeline_drops_detection_outside_counting_polygon(tmp_path, monkeypatch): + """The merged pipeline applies the same polygon filter.""" + from src.pipeline import run_merged_pipeline + + counter = _patch_counting_fakes(monkeypatch, [INSIDE_SACK, OUTSIDE_SACK]) + 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, + counting_polygon=_fcp_polygon(), + ) + + assert counter.seen, "counter never received a detection" + assert {d.bbox for d in counter.seen} == {INSIDE_SACK.bbox} + + +def test_job_forwards_counting_polygon_to_both_pipelines(tmp_path, monkeypatch): + """Job.counting_polygon reaches run_pipeline and run_merged_pipeline.""" + import src.job as job_mod + from src.job import Job, JobQueue + from src.pipeline import MergedPipelineResult, PipelineResult + + polygon = _fcp_polygon() + seen: dict = {} + + def fake_run_pipeline(**kwargs): + seen.update(kwargs) + return PipelineResult( + output_path="out.mp4", frame_count=1, loading_count=0, unloading_count=0, + batch_count=0, duration_seconds=0.0, model_name="a.pt", class_filter=None, + ) + + def fake_run_merged(**kwargs): + seen.update(kwargs) + return MergedPipelineResult( + output_path="merged.mp4", frame_count=1, loading_count=0, unloading_count=0, + batch_count=0, duration_seconds=0.0, model_names=["a.pt"], class_filter=None, + ) + + monkeypatch.setattr(job_mod, "run_pipeline", fake_run_pipeline) + monkeypatch.setattr(job_mod, "run_merged_pipeline", fake_run_merged) + + q = JobQueue(output_dir=str(tmp_path)) + models = [ + ModelConfig( + filename="a.pt", path=str(tmp_path / "a.pt"), stem="a", + known_classes=["sack", "truck"], + ) + ] + + single = Job( + job_id="job-poly-single", + video_path="/tmp/test.mp4", + model_configs=models, + output_dir=str(tmp_path / "job-poly-single"), + counting_polygon=polygon, + ) + q._jobs[single.job_id] = single + q._run_job(single.job_id) + assert seen.get("counting_polygon") is polygon + + merged = Job( + job_id="job-poly-merged", + video_path="/tmp/test.mp4", + model_configs=models + [ + ModelConfig( + filename="b.pt", path=str(tmp_path / "b.pt"), stem="b", + known_classes=["sack"], + ) + ], + output_dir=str(tmp_path / "job-poly-merged"), + counting_polygon=polygon, + ) + q._jobs[merged.job_id] = merged + q._run_job(merged.job_id) + assert seen.get("counting_polygon") is polygon + + # ── Perf/output tuning params (signature contracts) ──────────────────── diff --git a/tests/test_zone_config.py b/tests/test_zone_config.py index 849894c..bf5ae15 100644 --- a/tests/test_zone_config.py +++ b/tests/test_zone_config.py @@ -1,7 +1,16 @@ import json import os import pytest -from src.zone_config import load_zone_config, build_static_roi, list_zone_presets +from shapely.geometry import Point +from src.zone_config import ( + build_counting_polygon, + build_static_roi, + list_zone_presets, + load_zone_config, +) + +# FCP's detection_poly_pts at reference resolution (predict.py:692-697). +FCP_COUNTING_AREA = [[574, 50], [586, 1077], [1418, 1076], [1397, 50]] def test_load_zone_config_reads_json(tmp_path): @@ -49,6 +58,59 @@ def test_build_static_roi_scales_from_1080p_to_720p(): assert roi.x2 == int(1404 * 1280 / 1920) +# ── Counting polygon (FCP detection_polygon parity) ────────────────────── + + +def _polygon_coords(poly): + """Polygon ring as a list of (x, y) int tuples.""" + return [(int(x), int(y)) for x, y in poly.exterior.coords] + + +def test_build_counting_polygon_matches_fcp_reference_polygon(): + """Scaled to 1280x720 the polygon equals FCP's hardcoded detection_polygon. + + FCP predict.py:688-698 scales 1920x1080 points by 1280/1920 and + 720/1080 and truncates with int(). + """ + zone = {"counting_area": FCP_COUNTING_AREA, "reference_resolution": [1920, 1080]} + poly = build_counting_polygon(zone, 1280, 720) + assert _polygon_coords(poly) == [ + (382, 33), (390, 718), (945, 717), (931, 33), (382, 33), + ] + + +def test_build_counting_polygon_defaults_to_1920x1080_reference(): + """A zone without reference_resolution uses FCP's 1920x1080 default.""" + poly = build_counting_polygon({"counting_area": FCP_COUNTING_AREA}, 1280, 720) + assert _polygon_coords(poly) == [ + (382, 33), (390, 718), (945, 717), (931, 33), (382, 33), + ] + + +def test_build_counting_polygon_at_reference_resolution_is_unscaled(): + """At the reference resolution the points are unchanged.""" + zone = {"counting_area": FCP_COUNTING_AREA, "reference_resolution": [1920, 1080]} + poly = build_counting_polygon(zone, 1920, 1080) + assert _polygon_coords(poly) == [ + (574, 50), (586, 1077), (1418, 1076), (1397, 50), (574, 50), + ] + + +def test_build_counting_polygon_none_without_counting_area(): + """No counting_area -> no polygon (the filter stays off).""" + assert build_counting_polygon({}, 1280, 720) is None + assert build_counting_polygon({"truck_area": [[0, 0]]}, 1280, 720) is None + assert build_counting_polygon({"counting_area": []}, 1280, 720) is None + + +def test_build_counting_polygon_contains_centroid_semantics(): + """contains() on the bbox centre mirrors FCP's detection_polygon check.""" + poly = build_counting_polygon({"counting_area": FCP_COUNTING_AREA}, 1280, 720) + assert poly.contains(Point((620.0, 320.0))) # inside + assert not poly.contains(Point((70.0, 320.0))) # left of the polygon + assert not poly.contains(Point((1200.0, 320.0))) # right of the polygon + + def test_list_zone_presets(tmp_path): cfg = {"presets": {"p1": {"description": "Zone 1"}, "p2": {"description": "Zone 2"}}} p = tmp_path / "zones.json"