From fcdfed1e51e89ca806926d04349cce902f79b5a8 Mon Sep 17 00:00:00 2001 From: jetson Date: Tue, 27 Oct 2026 12:54:43 +0700 Subject: [PATCH] feat: analyse and write at 1280x720 with pinned 640x640 model input (FCP parity) --- app.py | 25 ++++---- src/detection.py | 2 +- src/pipeline.py | 37 +++++++++--- src/tracking.py | 1 + tests/test_app.py | 20 ++++++ tests/test_frame_geometry.py | 114 +++++++++++++++++++++++++++++++++++ tests/test_video_writer.py | 13 ++++ 7 files changed, 189 insertions(+), 23 deletions(-) create mode 100644 tests/test_frame_geometry.py diff --git a/app.py b/app.py index 09942b0..50728f2 100644 --- a/app.py +++ b/app.py @@ -21,6 +21,8 @@ from pathlib import Path 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 load_dotenv() @@ -131,6 +133,15 @@ def upload(): return redirect(url_for("status", job_id=job.job_id)) +def _static_roi(zone: dict) -> TruckROI: + """Build the fixed zone ROI in FCP's 1280x720 analysis frame. + + The zone preset is authored for 1280x720 (FCP predict.py:685-711), so it + must not be scaled to the uploaded clip's native size. + """ + return build_static_roi(zone, *ANALYSIS_SIZE) + + def _save_and_queue(video, model_configs, class_filters, output_height, zone_mode, zone_preset): """Save upload (collision-safe), transcode to 720p, resolve fixed zone, @@ -153,12 +164,7 @@ def _save_and_queue(video, model_configs, class_filters, if zone_mode == "fixed" and os.path.isfile(ZONES_PATH): zone = get_active_zone(ZONES_PATH, zone_preset or None) if zone: - import cv2 - cap = cv2.VideoCapture(video_path) - vw = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) - vh = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) - cap.release() - fixed_zone = build_static_roi(zone, vw, vh) + fixed_zone = _static_roi(zone) zone_preset = zone_preset or "default" return job_queue.add_job( @@ -292,12 +298,7 @@ def upload_reuse(): preset_name = request.form.get("zone_preset", "") zone = get_active_zone(ZONES_PATH, preset_name or None) if zone: - import cv2 - cap = cv2.VideoCapture(video_path) - vw = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) - vh = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) - cap.release() - fixed_zone = build_static_roi(zone, vw, vh) + fixed_zone = _static_roi(zone) zone_preset = preset_name or "default" job = job_queue.add_job( diff --git a/src/detection.py b/src/detection.py index 3454f8d..821d56f 100644 --- a/src/detection.py +++ b/src/detection.py @@ -41,7 +41,7 @@ class BaseDetector: def detect(self, frame: np.ndarray) -> list[Detection]: results = self._model.predict( - frame, conf=self._conf, verbose=False + frame, conf=self._conf, imgsz=640, verbose=False ) return self._parse(results[0]) diff --git a/src/pipeline.py b/src/pipeline.py index 71a408c..dfbb0da 100644 --- a/src/pipeline.py +++ b/src/pipeline.py @@ -28,6 +28,15 @@ from src.tracking import ByteTrackTracker from src.truck_roi import TruckROI, TruckROITracker from src.video_writer import AnnotatedVideoWriter +# Analysis frame space — FCP analyses every clip in a 1280x720 frame +# (predict.py:826 resizes the decoded frame, predict.py:531-532 pins the size). +ANALYSIS_SIZE: tuple[int, int] = (1280, 720) + + +def analysis_size(src_w: int, src_h: int) -> tuple[int, int]: + """Return FCP's fixed analysis frame size — 1280x720, source size ignored.""" + return ANALYSIS_SIZE + class _AsyncWriter: """Writer worker: preserves frame order, surfaces first error at close().""" @@ -199,8 +208,10 @@ def run_pipeline( fps = cap.get(cv2.CAP_PROP_FPS) or 25.0 total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) - w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) - h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) + src_w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) + src_h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) + # Analysis space is always FCP's 1280x720, whatever the clip's native size. + w, h = analysis_size(src_w, src_h) # Build detector with class filtering (single shared YOLO instance) effective_filter = class_filter or ( @@ -285,6 +296,8 @@ def run_pipeline( ret, frame = cap.read() if not ret: break + # FCP parity: every decoded frame is analysed at 1280x720. + frame = cv2.resize(frame, (w, h)) frame_idx += 1 timestamp = time.time() @@ -393,10 +406,10 @@ def run_pipeline( }) if preview_enabled and preview_path is not None and frame_idx % max(1, preview_every_n) == 0: - h, w = viz.shape[:2] - if max(h, w) > preview_max_dim: - scale = preview_max_dim / max(h, w) - preview_viz = cv2.resize(viz, (int(w * scale), int(h * scale))) + ph, pw = viz.shape[:2] + if max(ph, pw) > preview_max_dim: + scale = preview_max_dim / max(ph, pw) + preview_viz = cv2.resize(viz, (int(pw * scale), int(ph * scale))) else: preview_viz = viz tmp_path = preview_path + ".tmp.jpg" @@ -510,8 +523,8 @@ def _apply_min_area(dets, areas): # Platform (karung_counter_semarang) force-resizes frames to 1280x720 before -# detection, so its min_bbox_area values are authored in that space. Scale by -# frame area so the physical-size threshold matches on native 1080p input. +# detection, so its min_bbox_area values are authored in that space. We now +# analyse at 1280x720 too, so the scale below is always 1.0. PLATFORM_REF_AREA = 1280 * 720 @@ -577,8 +590,10 @@ def run_merged_pipeline( fps = cap.get(cv2.CAP_PROP_FPS) or 25.0 total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) - w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) - h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) + src_w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) + src_h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) + # Analysis space is always FCP's 1280x720, whatever the clip's native size. + w, h = analysis_size(src_w, src_h) # Load all detectors detectors = [] @@ -674,6 +689,8 @@ def run_merged_pipeline( ret, frame = cap.read() if not ret: break + # FCP parity: every decoded frame is analysed at 1280x720. + frame = cv2.resize(frame, (w, h)) frame_idx += 1 timestamp = time.time() diff --git a/src/tracking.py b/src/tracking.py index 30ab8b5..3bf9854 100644 --- a/src/tracking.py +++ b/src/tracking.py @@ -47,6 +47,7 @@ class ByteTrackTracker: frame, conf=self._conf, iou=self._iou, + imgsz=640, persist=True, tracker=self._tracker_cfg, verbose=False, diff --git a/tests/test_app.py b/tests/test_app.py index 4be6ac2..95289d0 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -327,3 +327,23 @@ def test_api_preview_yields_again_after_mtime_change(client): close() finally: _cleanup_preview_job(job) + + +# ── Zone ROI is FCP's calibration (1280x720 frame), not the clip's size ──── + +FCP_ZONE = { + "truck_area": [[600, 385], [609, 1076], [1404, 1078], [1381, 343]], + "counting_area": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]], + "count_line": {"x_start": 577, "x_end": 1401, "y": 330}, + "reference_resolution": [1920, 1080], +} + + +def test_zone_roi_is_built_at_1280x720(): + """The ROI is FCP's calibration, not the function clip's resolution.""" + import app as app_module + + roi = app_module._static_roi(FCP_ZONE) + assert roi.line_y == 220 + assert (roi.x1, roi.x2) == (400, 936) + diff --git a/tests/test_frame_geometry.py b/tests/test_frame_geometry.py new file mode 100644 index 0000000..a39a7df --- /dev/null +++ b/tests/test_frame_geometry.py @@ -0,0 +1,114 @@ +"""Frame geometry pinned to FCP's 1280x720 analysis space.""" + +import cv2 +import numpy as np + +import src.detection as detection_mod +import src.pipeline as pipeline_mod +import src.tracking as tracking_mod +from src.model_registry import ModelConfig +from src.pipeline import ANALYSIS_SIZE, analysis_size, run_pipeline + + +def _fake_yolo(recorder): + """Fake ultralytics YOLO records kwargs of track()/predict().""" + + class _Result: + boxes = None + + class _FakeYOLO: + names = {"sack": 0, "box": 0, "truck": 0} + + def __init__(self, path): + self.path = path + + def track(self, frame, **kwargs): + recorder.update(kwargs) + return [_Result()] + + def predict(self, frame, **kwargs): + recorder.update(kwargs) + return [_Result()] + + return _FakeYOLO + + +def test_analysis_size_is_always_1280x720(): + """Every clip is analysed in FCP's 1280x720 frame.""" + assert ANALYSIS_SIZE == (1280, 720) + assert analysis_size(1920, 1080) == (1280, 720) + assert analysis_size(960, 720) == (1280, 720) + assert analysis_size(1280, 960) == (1280, 720) + + +def test_tracker_pins_imgsz_640(monkeypatch): + """Tracking runs at 640x640 (FCP predict.py:467).""" + calls = {} + monkeypatch.setattr(tracking_mod, "YOLO", _fake_yolo(calls)) + tracker = tracking_mod.ByteTrackTracker("fake.engine", conf=0.3) + tracker.update(np.zeros((720, 1280, 3), dtype=np.uint8), []) + assert calls["imgsz"] == 640 + + +def test_detector_pins_imgsz_640(monkeypatch): + """Plain detection (truck detector) runs at 640x640 too.""" + calls = {} + monkeypatch.setattr(detection_mod, "YOLO", _fake_yolo(calls)) + detector = detection_mod.BaseDetector("fake.engine", conf=0.45) + detector.detect(np.zeros((720, 1280, 3), dtype=np.uint8)) + assert calls["imgsz"] == 640 + + +def test_pipeline_analyses_and_writes_at_1280x720(tmp_path, monkeypatch): + """A 320x240 clip is analysed and written at FCP's 1280x720 (predict.py:826).""" + video_path = str(tmp_path / "clip.mp4") + clip_writer = cv2.VideoWriter( + video_path, cv2.VideoWriter_fourcc(*"mp4v"), 25.0, (320, 240) + ) + for _ in range(3): + clip_writer.write(np.zeros((240, 320, 3), dtype=np.uint8)) + clip_writer.release() + + seen = {} + + class _Result: + boxes = None + + class _FakeModel: + names = {"sack": 0} + + def track(self, frame, **kwargs): + return [_Result()] + + def predict(self, frame, **kwargs): + seen["predict_shape"] = frame.shape + return [_Result()] + + monkeypatch.setattr(pipeline_mod, "YOLO", lambda path: _FakeModel()) + monkeypatch.setattr(tracking_mod, "YOLO", _FakeModel) + monkeypatch.setattr(detection_mod, "YOLO", _FakeModel) + + output_path = str(tmp_path / "out.mp4") + run_pipeline( + video_path=video_path, + model_config=ModelConfig( + filename="fake.engine", path="fake.engine", stem="fake", + known_classes=["sack"], + ), + truck_model_config=ModelConfig( + filename="fake-truck.engine", path="fake-truck.engine", stem="fake-truck", + known_classes=["truck"], + ), + truck_det_interval=1, + output_path=output_path, + preview_enabled=False, + ) + + # The model sees the resized frame, not the clip's native one. + assert seen["predict_shape"][:2] == (720, 1280) + # The annotated file carries the analysis frame size. + cap = cv2.VideoCapture(output_path) + assert cap.isOpened() + assert int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) == 1280 + assert int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) == 720 + cap.release() diff --git a/tests/test_video_writer.py b/tests/test_video_writer.py index 982a1bc..034ba6f 100644 --- a/tests/test_video_writer.py +++ b/tests/test_video_writer.py @@ -106,3 +106,16 @@ def test_explicit_codec_forces_fourcc(tmp_path): writer.write_frame(np.zeros((480, 640, 3), dtype=np.uint8)) writer.finish() assert out.exists() and out.stat().st_size > 0 + + +def test_writer_emits_exactly_1280x720(tmp_path): + """The annotated file is 1280x720, whatever clip was.""" + out = tmp_path / "out.mp4" + writer = AnnotatedVideoWriter( + str(out), fps=25, frame_size=(1280, 720) + ) + assert writer.written_size == (1280, 720) + writer.write_frame(np.zeros((720, 1280, 3), dtype=np.uint8)) + writer.finish() + _, width, height = probe(out) + assert (width, height) == (1280, 720)