feat(zones): use native 1080p zones, sync FCP main, and auto-sync default preset
This commit is contained in:
1 parent
b9d4bd11b3
commit
1c26f9f95b
13 files changed
+995
-328
No files matched your search
@@ -23,7 +23,7 @@ Feedmill Recounter: AI video analysis for counting sacks/boxes in feedmill video
|
||||
- Zone writes go through `POST /api/zones/<preset>` (localhost-only, validated, atomic). Do not hand-edit `zones.json` while the web app runs — the editor merges over the stored preset.
|
||||
- The counting gates live in `config.yaml` under `counting:` and match FCP `main` (`capture_below_px=100`, `max_step_dy_px=160`, `max_gap_frames=15`, `unload_confirm_frames=1`).
|
||||
- `tools/calibrate_zone.py` and the `/calibrate` page produce the same geometry; keep their count-line derivation in sync (`x_start=min`, `x_end=max`, `y=round(mean(ys))`).
|
||||
- Config: `config.yaml` (tunables), `zones.json` (fixed zones, 1280x720 analysis space), `.env` (paths/secrets).
|
||||
- Config: `config.yaml` (tunables), `zones.json` (fixed zones, native 1920x1080 scaled to 1280x720 at runtime), `.env` (paths/secrets).
|
||||
|
||||
## Quirks
|
||||
- Model weights and `.engine` files are gitignored; local models required for real runs.
|
||||
@@ -33,9 +33,8 @@ Feedmill Recounter: AI video analysis for counting sacks/boxes in feedmill video
|
||||
- `README.md` says port 9000 in `.env.example`, but code defaults to 9050.
|
||||
- Conversion to `.engine` must start from `.pt`; Ultralytics cannot export from ONNX.
|
||||
- `.engine` conversion may take minutes on Jetson.
|
||||
- Zones live in `zones.json` in the **1280x720 analysis space**; `reference_resolution` is `[1280, 720]`, so the scale factor is 1.0. Never introduce a second coordinate space (the editor maps client -> source in the same 1280x720 space).
|
||||
- Two presets ship: `default` (the `feat/interactive-roi-line` branch's `95c031b` recalibration, count line y=182, plus FCP `main` `91d8b48`'s recalibrated `palet` zone `[[408, 1], [893, 1], [893, 178], [405, 178]]` above the truck — the active preset) and `fcp-2026-10-15` (pre-recalibration, count line y=220 — matches what the deployed live counter (commit `7beb820`) counts with today, because its `predict.py` hardcodes the line at y=220 and does not read `zones.json`).
|
||||
- The unload branch in `src/counting.py` is unreachable by design (parity with the deployed live counter, which runs the same gates — `7beb820` contains the gates commit `8448dcb`): `unloading` is always 0 and `net` equals the gross count. Do not "fix" it into a counted unload.
|
||||
- Zone writes are localhost-only; remote operators use an SSH tunnel (`ssh -L 9050:127.0.0.1:9050 jetson@<host>`).
|
||||
- Zones live in `zones.json` natively in **1920x1080** (`reference_resolution` `[1920, 1080]`, matching FCP `main`), and `src/zone_config.py` scales them to the `1280x720` analysis space at runtime via `int(round(v * scale))`. `sync_fcp_zones` automatically updates `"default"` from FCP's `zones.json` (`FCP_ZONES_PATH` or `/home/jetson/feedmill_semarang_project/karung_counter_semarang/zones.json`) whenever FCP's file has a newer `mtime`.
|
||||
- Two presets ship: `default` (synced to FCP `main` `91d8b48`: `palet` `[[612, 1], [1340, 1], [1340, 267], [608, 267]]`, `truck_area` `[[600, 290], [609, 1076], [1404, 1078], [1381, 290]]`, `counting_area` `[[574, 50], [586, 1077], [1418, 1076], [1397, 50]]`, `count_line` `y=215` -> runtime `143` at `720p`) and `fcp-2026-10-15` (pre-recalibration, `count_line` `y=330` -> runtime `220` at `720p` matching `7beb820`).
|
||||
- Zone writes are localhost-only; remote operators use an SSH tunnel (`ssh -L 9050:127.0.0.1:9050 jetson@<host>`). Both `POST /api/zones/<preset>` and `/calibrate` (Import JSON) accept FCP 1920x1080 flat JSON as well as recounter preset JSON (and scale legacy `1280x720` inputs up to `1920x1080`).
|
||||
- `tools/record_rtsp.sh` records an RTSP stream to a file for live-vs-recounter parity runs; the recounter stays file-based (no RTSP input path).
|
||||
- The `/calibrate` editor and `tools/calibrate_zone.py` both accept a pasted JSON preset (Import / Export JSON panel), so zones can be shared over chat or email and applied by paste.
|
||||
@@ -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
|
||||
- **Store `zones.json` natively in 1080p (`1920×1080`), sync with FCP `main` (`91d8b48`), and auto-sync from FCP `zones.json`**:
|
||||
- `zones.json`, `DEFAULT_ZONES`, `/calibrate`, and `tools/calibrate_zone.py` now author and store presets natively in `1920×1080` (`reference_resolution: [1920, 1080]`), and runtime scaling in `src/zone_config.py` uses `int(round(v * scale))` to match FCP `main` `predict.py:762, 781-783` at `1280×720`.
|
||||
- Added `normalize_zone_preset()` in `src/zone_config.py` (and matching client-side support in `static/calibrate.js`) so FCP flat `zones.json` payloads (`palet`, `truck`, `counting`, `line_y`/`line_x_start`/`line_x_end`, `counting_line`, `coord_space`) and legacy `1280×720` presets normalize cleanly to `[1920, 1080]`.
|
||||
- Added `sync_fcp_zones()` + shared `resolve_zone()` so both `app.py` and `cli.py` (`--zone-mode`, `--zone-preset`, `--zones-path`, defaulting to `fixed` from `zones.json`) automatically update `presets["default"]` whenever FCP's `zones.json` is newer.
|
||||
- Updated `presets["default"]` to FCP `main` (`91d8b48`: `count_line` `y=215` -> `143` at 720p) and `fcp-2026-10-15` to native `1920×1080` (`count_line` `y=330` -> `220` at 720p).
|
||||
- **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.
|
||||
|
||||
@@ -78,6 +78,9 @@ recounter --video PATH Input video file
|
||||
--output-dir DIR Output directory (default: ./output)
|
||||
--output-height INT Downscale annotated output to this height (e.g. 720)
|
||||
--models-dir DIR Models directory (default: ./models)
|
||||
--zone-mode MODE fixed (default, uses zones.json), dynamic, or freeze
|
||||
--zone-preset NAME Preset name in zones.json (default: active_preset)
|
||||
--zones-path PATH Path to zones.json (default: ./zones.json)
|
||||
```
|
||||
|
||||
## Web UI
|
||||
@@ -140,6 +143,8 @@ recounter --video PATH Input video file
|
||||
| `MODELS_DIR` | `./models` | Model weights directory |
|
||||
| `UPLOAD_DIR` | `./uploads` | Uploaded videos directory |
|
||||
| `OUTPUT_DIR` | `./output` | Annotated output directory |
|
||||
| `ZONES_PATH` | `./zones.json` | Fixed zone preset file (`1920x1080`) |
|
||||
| `FCP_ZONES_PATH` | host FCP `zones.json` | Optional override for auto-sync source (set empty `""` to disable) |
|
||||
| `config.yaml` | root | Tunable pipeline params (conf, IoU, ROI, intervals) |
|
||||
|
||||
Edit `config.yaml` instead of the code for these values; restart the job / re-run the CLI to apply.
|
||||
@@ -217,10 +222,13 @@ In multi-model runs, the first model covering `sack` runs primary ByteTrack trac
|
||||
|
||||
### Calibrating counting zone
|
||||
|
||||
The counting line, the counting ROI and the truck ROI are calibrated in
|
||||
**1280×720** pixels — the frame the pipeline analyses, and the frame the live
|
||||
counter uses. The editor, `zones.json` and the analysis frame are one
|
||||
coordinate space; there is no second scale factor.
|
||||
The counting line, the counting ROI and the truck ROI are stored in
|
||||
**1920×1080** pixels (`reference_resolution: [1920, 1080]`) matching FCP
|
||||
`main`'s `zones.json`, and scaled to the **1280×720** analysis frame at
|
||||
runtime (`int(round(v * scale))`). When FCP's `zones.json`
|
||||
(`/home/jetson/feedmill_semarang_project/karung_counter_semarang/zones.json`
|
||||
or `FCP_ZONES_PATH`) has a newer modification timestamp, the `"default"` preset
|
||||
automatically syncs from it for fixed-zone runs (web UI and CLI).
|
||||
|
||||
Open `http://<host>:9050/calibrate`:
|
||||
|
||||
@@ -228,21 +236,13 @@ Open `http://<host>:9050/calibrate`:
|
||||
2. Press **Unlock Edit**.
|
||||
3. Drag the vertices of the counting ROI (blue), the truck ROI (orange) and the
|
||||
two ends of the count line (green). The line stays horizontal; the shaded
|
||||
band is the ±20 px trigger zone.
|
||||
band is the ±30 px trigger zone at 1080p (±20 px in the 1280×720 analysis frame).
|
||||
4. **Save Zones**.
|
||||
|
||||
Two presets ship:
|
||||
|
||||
- `default` — the `feat/interactive-roi-line` branch's `95c031b` recalibration
|
||||
(count line y=182). It is the active preset (`active_preset`).
|
||||
- `fcp-2026-10-15` — the pre-recalibration geometry (count line y=220). The
|
||||
deployed live counter (commit `7beb820`) counts with this geometry today: its
|
||||
`predict.py` hardcodes the line (`static_line_y = int(330 * scale_y)`, i.e.
|
||||
y=220 in 1280×720) and does not read `zones.json`. Pick this preset to
|
||||
reproduce today's live numbers. Once the `feat/interactive-roi-line` branch is
|
||||
deployed, `default` is the matching preset, because that branch does read
|
||||
`zones.json`. The deploy script does not copy `zones.json`, so carry it by
|
||||
hand when deploying the branch, or the box keeps the old geometry.
|
||||
- `default` — synced to FCP `main` (`91d8b48`) in 1920×1080 (`count_line` y=215 -> y=143 in 720p). It is the active preset (`active_preset`).
|
||||
- `fcp-2026-10-15` — the pre-recalibration geometry (`count_line` y=330 -> y=220 in 720p), matching the legacy `7beb820` deployment.
|
||||
|
||||
The write API (`POST /api/zones/<preset>`, `POST /api/zones/<preset>/reset`) is
|
||||
**localhost-only**. From another machine, tunnel the port over SSH:
|
||||
@@ -257,20 +257,23 @@ Writes are atomic: the previous file is copied to `zones.json.bak`, the new
|
||||
one is written to a temp file, and the temp file replaces `zones.json`.
|
||||
|
||||
Zone changes apply to the **next** analysis; a running job keeps the zone it
|
||||
started with. `tools/calibrate_zone.py` does the same job in an OpenCV window
|
||||
on the box itself.
|
||||
started with. `tools/calibrate_zone.py` supports the same 1920×1080 calibration
|
||||
in an OpenCV window on the box itself (plus `--import-json PATH` for CLI import).
|
||||
|
||||
### Importing / exporting zone JSON
|
||||
|
||||
The calibrator also accepts a pasted JSON blob (useful for sharing zones over
|
||||
chat or email). Click **Import / Export JSON**, paste a preset object, and press
|
||||
**Import JSON**:
|
||||
The calibrator accepts pasted recounter presets (`1920x1080` or `1280x720`) AND
|
||||
FCP flat `zones.json` blobs (`palet`, `truck`, `counting`, `line_y`,
|
||||
`line_x_start`, `line_x_end`, optional `counting_line` / `coord_space`),
|
||||
converting inputs to `[1920, 1080]` automatically. Click **Import / Export JSON**,
|
||||
paste a JSON object, and press **Import JSON**:
|
||||
|
||||
```json
|
||||
{"truck_area":[[x,y],...],"counting_area":[[x,y],...],
|
||||
"count_line":{"x_start":0,"x_end":0,"y":0},
|
||||
"reference_resolution":[1280,720]}
|
||||
"reference_resolution":[1920,1080]}
|
||||
```
|
||||
|
||||
**Copy current zones** puts the active preset on the clipboard; **Download JSON**
|
||||
saves it to a file. The same shape is what `POST /api/zones/<preset>` accepts.
|
||||
saves it to a file. `POST /api/zones/<preset>` also accepts both FCP flat JSON
|
||||
and recounter preset JSON.
|
||||
@@ -20,7 +20,6 @@ from werkzeug.utils import secure_filename
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from shapely.errors import GEOSException
|
||||
from shapely.geometry import Polygon
|
||||
|
||||
from src.compress import compress_in_place
|
||||
@@ -39,10 +38,9 @@ from src.pipeline import ANALYSIS_SIZE
|
||||
from src.truck_roi import TruckROI
|
||||
from src.validation import ValidationError
|
||||
from src.zone_config import (
|
||||
load_zone_config, list_zone_presets, build_static_roi, build_counting_polygon,
|
||||
build_truck_polygon, get_active_zone,
|
||||
load_zone_config, list_zone_presets, build_static_roi, get_active_zone,
|
||||
DEFAULT_ZONES, ZONE_BOUNDS_H, ZONE_BOUNDS_W,
|
||||
save_zone_preset,
|
||||
resolve_zone, save_zone_preset, sync_fcp_zones,
|
||||
)
|
||||
|
||||
load_dotenv()
|
||||
@@ -158,74 +156,23 @@ def upload():
|
||||
def _static_roi(zone: dict) -> TruckROI:
|
||||
"""Build the fixed zone ROI in FCP's 1280x720 analysis frame.
|
||||
|
||||
Zone presets are authored in 1280x720 (zones.json reference_resolution is
|
||||
[1280, 720]), so the scale factor is 1.0. The zone must not be scaled to
|
||||
the uploaded clip's native size.
|
||||
Zone presets are stored in 1920x1080 (zones.json reference_resolution is
|
||||
[1920, 1080]) and scaled to 1280x720 at runtime.
|
||||
"""
|
||||
return build_static_roi(zone, *ANALYSIS_SIZE)
|
||||
|
||||
|
||||
def _static_polygon(zone: dict) -> Polygon | None:
|
||||
"""Build the counting polygon in FCP's 1280x720 analysis frame.
|
||||
|
||||
The zone's counting_area is in the same 1280x720 space (scale factor 1.0).
|
||||
"""
|
||||
return build_counting_polygon(zone, *ANALYSIS_SIZE)
|
||||
|
||||
|
||||
def _static_truck_polygon(zone: dict) -> Polygon | None:
|
||||
"""Build the truck-area polygon in FCP's 1280x720 analysis frame.
|
||||
|
||||
The zone's truck_area is in the same 1280x720 space (scale factor 1.0).
|
||||
"""
|
||||
return build_truck_polygon(zone, *ANALYSIS_SIZE)
|
||||
|
||||
|
||||
def _resolve_zone(
|
||||
zone_mode: str, zone_preset: str
|
||||
) -> tuple[str, TruckROI | None, str, Polygon | None, Polygon | None]:
|
||||
"""Resolve the counting zone of a job.
|
||||
|
||||
Returns (zone_mode, fixed_zone, zone_preset, counting_polygon,
|
||||
truck_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, None, None
|
||||
zone = None
|
||||
reason = "no zone file"
|
||||
roi: TruckROI | None = None
|
||||
polygon: Polygon | None = None
|
||||
truck_polygon: Polygon | None = None
|
||||
built = False
|
||||
if os.path.isfile(ZONES_PATH):
|
||||
try:
|
||||
zone = get_active_zone(ZONES_PATH, zone_preset or None)
|
||||
if zone is None:
|
||||
reason = "no active preset"
|
||||
else:
|
||||
# ROI + counting polygon + truck polygon come from the same zone
|
||||
# dict. A structurally invalid calibration must degrade to
|
||||
# dynamic, not 500 — so the builds stay inside this guard.
|
||||
roi = _static_roi(zone)
|
||||
polygon = _static_polygon(zone)
|
||||
truck_polygon = _static_truck_polygon(zone)
|
||||
if zone.get("counting_area") and polygon is None:
|
||||
# A counting area that is present but could not be built
|
||||
# means the calibration is broken. Counting without it
|
||||
# would widen the counting area, so degrade the zone.
|
||||
reason = "malformed counting_area"
|
||||
else:
|
||||
built = True
|
||||
except (OSError, ValueError, TypeError, AttributeError, IndexError,
|
||||
KeyError, OverflowError, GEOSException) as exc:
|
||||
# A corrupt/unreadable calibration must degrade to dynamic, not 500.
|
||||
reason = f"unreadable calibration — could not be read/applied ({exc})"
|
||||
if not built:
|
||||
print(f"[ZONE] {reason} at {ZONES_PATH} — falling back to dynamic")
|
||||
return "dynamic", None, zone_preset, None, None
|
||||
return "fixed", roi, zone_preset or "default", polygon, truck_polygon
|
||||
"""Resolve the counting zone of a job (auto-syncing FCP zones when newer)."""
|
||||
return resolve_zone(
|
||||
zone_mode,
|
||||
zone_preset,
|
||||
ZONES_PATH,
|
||||
ANALYSIS_SIZE,
|
||||
zone_reader=get_active_zone,
|
||||
)
|
||||
|
||||
|
||||
def _save_and_queue(video, model_configs, class_filters,
|
||||
@@ -698,6 +645,7 @@ def api_zones():
|
||||
"""Return zone presets from zones.json."""
|
||||
if not os.path.isfile(ZONES_PATH):
|
||||
return jsonify([])
|
||||
sync_fcp_zones(ZONES_PATH)
|
||||
try:
|
||||
presets = list_zone_presets(ZONES_PATH)
|
||||
return jsonify(presets)
|
||||
@@ -726,6 +674,7 @@ def _read_zones_config():
|
||||
"""
|
||||
if not os.path.isfile(ZONES_PATH):
|
||||
return None, (jsonify({"error": "zones.json not found"}), 404)
|
||||
sync_fcp_zones(ZONES_PATH)
|
||||
try:
|
||||
config = load_zone_config(ZONES_PATH)
|
||||
except OSError as exc:
|
||||
|
||||
@@ -6,9 +6,12 @@ import argparse
|
||||
import os
|
||||
import sys
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
from src.model_registry import ModelConfig, scan_models
|
||||
from src.naming import annotated_output_name
|
||||
from src.pipeline import run_pipeline
|
||||
from src.pipeline import ANALYSIS_SIZE, run_pipeline
|
||||
from src.zone_config import resolve_zone
|
||||
|
||||
|
||||
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
||||
@@ -37,10 +40,19 @@ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
||||
help="Output directory for annotated videos")
|
||||
parser.add_argument("--output-height", type=int, default=None,
|
||||
help="Downscale annotated output to this height (e.g. 720)")
|
||||
parser.add_argument("--zone-mode", choices=["fixed", "dynamic", "freeze"],
|
||||
default="fixed",
|
||||
help="Counting zone mode (default: fixed from zones.json)")
|
||||
parser.add_argument("--zone-preset", type=str, default="",
|
||||
help="Preset name in zones.json (default: active_preset)")
|
||||
parser.add_argument("--zones-path", type=str,
|
||||
default=os.getenv("ZONES_PATH", "./zones.json"),
|
||||
help="Path to zones.json (default: ./zones.json)")
|
||||
return parser.parse_args(argv)
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> None:
|
||||
load_dotenv()
|
||||
args = parse_args(argv)
|
||||
|
||||
discovered = scan_models(args.models_dir)
|
||||
@@ -92,6 +104,9 @@ def main(argv: list[str] | None = None) -> None:
|
||||
sys.exit(1)
|
||||
|
||||
class_filter = args.filter if args.filter else None
|
||||
resolved_mode, fixed_zone, _preset, counting_polygon, truck_polygon = resolve_zone(
|
||||
args.zone_mode, args.zone_preset, args.zones_path, ANALYSIS_SIZE
|
||||
)
|
||||
|
||||
for model_cfg in selected:
|
||||
if args.output and len(selected) == 1:
|
||||
@@ -119,8 +134,12 @@ def main(argv: list[str] | None = None) -> None:
|
||||
model_config=model_cfg,
|
||||
output_path=out_path,
|
||||
class_filter=class_filter,
|
||||
fixed_zone=fixed_zone,
|
||||
counting_polygon=counting_polygon,
|
||||
truck_polygon=truck_polygon,
|
||||
sack_conf=args.sack_conf,
|
||||
truck_conf=args.truck_conf,
|
||||
freeze_roi=(resolved_mode == "freeze"),
|
||||
output_max_height=args.output_height,
|
||||
progress_callback=progress_callback,
|
||||
)
|
||||
|
||||
+346
-60
@@ -61,13 +61,13 @@ def build_static_roi(zone: dict[str, Any], video_w: int, video_h: int) -> TruckR
|
||||
x2 = min(video_w, max(xs))
|
||||
y2 = min(video_h, max(ys))
|
||||
|
||||
# Calibrated count-line (FCP predict.py:702-703). The counter counts inside
|
||||
# Calibrated count-line (FCP predict.py:781-783). The counter counts inside
|
||||
# the x-window, not inside the truck-ROI bounds. The fallbacks are already
|
||||
# in frame space (x1/x2/y1/y2 are scaled) — never scale them twice.
|
||||
line_y = int(count_line["y"] * sy) if "y" in count_line else (y1 + y2) // 2
|
||||
line_y = int(round(count_line["y"] * sy)) if "y" in count_line else (y1 + y2) // 2
|
||||
if count_line:
|
||||
line_x_start = int(count_line["x_start"] * sx) if "x_start" in count_line else x1
|
||||
line_x_end = int(count_line["x_end"] * sx) if "x_end" in count_line else x2
|
||||
line_x_start = int(round(count_line["x_start"] * sx)) if "x_start" in count_line else x1
|
||||
line_x_end = int(round(count_line["x_end"] * sx)) if "x_end" in count_line else x2
|
||||
else:
|
||||
# No calibrated line — the counter falls back to the ROI bounds.
|
||||
line_x_start = None
|
||||
@@ -119,9 +119,9 @@ def _scaled_points(
|
||||
x, y = p
|
||||
if not isinstance(x, Real) or not isinstance(y, Real):
|
||||
return None
|
||||
if not (isfinite(x) and isfinite(y)):
|
||||
if not _is_finite_real(x) or not _is_finite_real(y):
|
||||
return None
|
||||
scaled.append((int(x * sx), int(y * sy)))
|
||||
scaled.append((int(round(x * sx)), int(round(y * sy))))
|
||||
return scaled
|
||||
except (TypeError, ValueError, IndexError, KeyError, OverflowError):
|
||||
return None
|
||||
@@ -150,11 +150,10 @@ def build_counting_polygon(
|
||||
) -> 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.
|
||||
zone["counting_area"] holds FCP's counting polygon (predict.py:761-769)
|
||||
at zone["reference_resolution"]. FCP scales from 1920x1080 to 1280x720
|
||||
using int(round(v * scale)) — the arithmetic here is identical, so the
|
||||
polygon matches FCP's detection_polygon pixel-for-pixel.
|
||||
|
||||
Returns None when the zone has no usable counting_area (no polygon filter).
|
||||
A malformed calibration degrades to None, it never raises.
|
||||
@@ -167,9 +166,9 @@ def build_truck_polygon(
|
||||
) -> Polygon | None:
|
||||
"""Build the truck-area polygon of a zone, scaled to the video frame.
|
||||
|
||||
zone["truck_area"] holds FCP's truck_poly_pts (predict.py:706-712) at
|
||||
zone["reference_resolution"]. The arithmetic is identical to
|
||||
build_static_roi's, so the polygon matches FCP's truck_polygon exactly.
|
||||
zone["truck_area"] holds FCP's truck polygon (predict.py:761-769) at
|
||||
zone["reference_resolution"]. The arithmetic uses int(round(v * scale))
|
||||
so the polygon matches FCP's truck_polygon pixel-for-pixel.
|
||||
|
||||
Returns None when the zone has no usable truck_area — a malformed
|
||||
calibration must degrade to "no truck area", never raise.
|
||||
@@ -185,16 +184,15 @@ def get_active_zone(path: str, preset_name: str | None = None) -> dict[str, Any]
|
||||
return presets.get(name)
|
||||
|
||||
|
||||
# The canonical zone presets, in the 1280x720 analysis space. Mirrors FCP's
|
||||
# hardcoded _DEFAULT_ZONES_7BEB820 (karung_counter_semarang/counter_dashboard.py:2279)
|
||||
# so a reset lands on the same geometry FCP ships.
|
||||
# The canonical zone presets, stored natively in 1920x1080 space and scaled
|
||||
# to 1280x720 at runtime (mirroring FCP main karung_counter_semarang/zones.json).
|
||||
DEFAULT_ZONES: dict[str, Any] = {
|
||||
"default": {
|
||||
"truck_area": [[398, 152], [359, 720], [876, 720], [949, 201]],
|
||||
"counting_area": [[362, 157], [306, 720], [912, 720], [979, 169]],
|
||||
"palet": [[408, 1], [893, 1], [893, 178], [405, 178]],
|
||||
"count_line": {"x_start": 423, "x_end": 939, "y": 182},
|
||||
"reference_resolution": [1280, 720],
|
||||
"truck_area": [[600, 290], [609, 1076], [1404, 1078], [1381, 290]],
|
||||
"counting_area": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]],
|
||||
"palet": [[612, 1], [1340, 1], [1340, 267], [608, 267]],
|
||||
"count_line": {"x_start": 577, "x_end": 1401, "y": 215},
|
||||
"reference_resolution": [1920, 1080],
|
||||
"left_limit": 0.27578,
|
||||
"right_limit": 0.72578,
|
||||
"duplicate_circle_radius": 30,
|
||||
@@ -205,14 +203,14 @@ DEFAULT_ZONES: dict[str, Any] = {
|
||||
"inference_stride": 2,
|
||||
"confirm_delay_sec": 0.5,
|
||||
"exit_confirm_delay_sec": 6.0,
|
||||
"description": "FCP 95c031b calibration (2026-11-11), 1280x720 analysis space",
|
||||
"description": "FCP main (91d8b48) calibration, native 1920x1080 (scaled to 1280x720 at runtime)",
|
||||
},
|
||||
"fcp-2026-10-15": {
|
||||
"truck_area": [[400, 257], [406, 717], [936, 719], [921, 229]],
|
||||
"counting_area": [[383, 33], [391, 718], [945, 717], [931, 33]],
|
||||
"palet": [[408, 419], [969, 420], [972, 716], [405, 714]],
|
||||
"count_line": {"x_start": 385, "x_end": 934, "y": 220},
|
||||
"reference_resolution": [1280, 720],
|
||||
"truck_area": [[600, 385], [609, 1076], [1404, 1078], [1381, 343]],
|
||||
"counting_area": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]],
|
||||
"palet": [[612, 628], [1454, 630], [1458, 1074], [608, 1071]],
|
||||
"count_line": {"x_start": 577, "x_end": 1401, "y": 330},
|
||||
"reference_resolution": [1920, 1080],
|
||||
"left_limit": 0.27578,
|
||||
"right_limit": 0.72578,
|
||||
"duplicate_circle_radius": 30,
|
||||
@@ -223,14 +221,166 @@ DEFAULT_ZONES: dict[str, Any] = {
|
||||
"inference_stride": 2,
|
||||
"confirm_delay_sec": 0.5,
|
||||
"exit_confirm_delay_sec": 6.0,
|
||||
"description": "FCP 7beb820 calibration (pre-2026-11-11 recalibration), 1280x720 analysis space",
|
||||
"description": "FCP 7beb820 calibration (pre-2026-11-11 recalibration), native 1920x1080",
|
||||
},
|
||||
}
|
||||
|
||||
ZONE_BOUNDS_W = 1280
|
||||
ZONE_BOUNDS_H = 720
|
||||
ZONE_BOUNDS_W = 1920
|
||||
ZONE_BOUNDS_H = 1080
|
||||
|
||||
_DEFAULT_FCP_ZONES_PATH = "/home/jetson/feedmill_semarang_project/karung_counter_semarang/zones.json"
|
||||
_REPO_ZONES_PATH = os.path.abspath(
|
||||
os.path.join(os.path.dirname(os.path.dirname(__file__)), "zones.json")
|
||||
)
|
||||
|
||||
_POLYGON_KEYS = ("truck_area", "counting_area", "palet")
|
||||
_FCP_FLAT_KEYS = (
|
||||
"truck",
|
||||
"counting",
|
||||
"line_y",
|
||||
"line_x_start",
|
||||
"line_x_end",
|
||||
"counting_line",
|
||||
"coord_space",
|
||||
)
|
||||
_FCP_TRANSIENT_KEYS = _FCP_FLAT_KEYS + ("roi",)
|
||||
|
||||
|
||||
def _is_finite_real(v: Any) -> bool:
|
||||
if not isinstance(v, Real) or isinstance(v, bool):
|
||||
return False
|
||||
try:
|
||||
return isfinite(float(v))
|
||||
except (OverflowError, TypeError, ValueError):
|
||||
return False
|
||||
|
||||
|
||||
def _resolve_source_resolution(raw: dict[str, Any]) -> tuple[float, float]:
|
||||
"""Return (src_w, src_h) encoded by raw's coord_space or reference_resolution."""
|
||||
if "coord_space" in raw and raw["coord_space"] is not None:
|
||||
raw_cs = str(raw["coord_space"]).strip().lower()
|
||||
parts = raw_cs.split("x")
|
||||
if len(parts) == 2:
|
||||
try:
|
||||
w, h = float(parts[0]), float(parts[1])
|
||||
if isfinite(w) and isfinite(h) and w > 0 and h > 0:
|
||||
return w, h
|
||||
except ValueError:
|
||||
pass
|
||||
raise ValueError(f"invalid coord_space: {raw['coord_space']!r}")
|
||||
|
||||
if "reference_resolution" in raw and raw["reference_resolution"] is not None:
|
||||
ref = raw["reference_resolution"]
|
||||
if (
|
||||
isinstance(ref, (list, tuple))
|
||||
and len(ref) == 2
|
||||
and _is_finite_real(ref[0])
|
||||
and _is_finite_real(ref[1])
|
||||
and float(ref[0]) > 0
|
||||
and float(ref[1]) > 0
|
||||
):
|
||||
return float(ref[0]), float(ref[1])
|
||||
raise ValueError("reference_resolution must be [width, height] of positive numbers")
|
||||
|
||||
return float(ZONE_BOUNDS_W), float(ZONE_BOUNDS_H)
|
||||
|
||||
|
||||
def _scale_coord(v: Any, scale: float) -> int | float:
|
||||
fv = float(v)
|
||||
if scale != 1.0:
|
||||
return int(round(fv * scale))
|
||||
return int(fv) if fv.is_integer() else fv
|
||||
|
||||
|
||||
def _scale_polygon(pts: Any, key: str, sx: float, sy: float) -> list[list[int | float]]:
|
||||
if not isinstance(pts, list):
|
||||
raise ValueError(f"{key} must be a polygon list")
|
||||
scaled = []
|
||||
for pt in pts:
|
||||
if not (isinstance(pt, (list, tuple)) and len(pt) == 2
|
||||
and _is_finite_real(pt[0]) and _is_finite_real(pt[1])):
|
||||
raise ValueError(f"{key} contains an invalid point")
|
||||
scaled.append([_scale_coord(pt[0], sx), _scale_coord(pt[1], sy)])
|
||||
return scaled
|
||||
|
||||
|
||||
def normalize_zone_preset(raw: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Normalize an FCP flat zones.json or recounter preset to [1920, 1080].
|
||||
|
||||
Accepts:
|
||||
- FCP flat schema: truck, counting, palet, line_y/line_x_start/line_x_end
|
||||
or 2-point counting_line, with optional coord_space (default 1920x1080).
|
||||
- Recounter preset schema: truck_area, counting_area, palet, count_line,
|
||||
with optional reference_resolution (scales 1280x720 -> 1920x1080).
|
||||
|
||||
Strips transient FCP flat keys and sets reference_resolution=[1920, 1080].
|
||||
"""
|
||||
if not isinstance(raw, dict):
|
||||
raise ValueError("preset must be an object")
|
||||
|
||||
src_w, src_h = _resolve_source_resolution(raw)
|
||||
sx = ZONE_BOUNDS_W / src_w
|
||||
sy = ZONE_BOUNDS_H / src_h
|
||||
|
||||
out: dict[str, Any] = {
|
||||
k: v for k, v in raw.items() if k not in _FCP_TRANSIENT_KEYS
|
||||
}
|
||||
|
||||
for target_key, flat_key in (
|
||||
("truck_area", "truck"),
|
||||
("counting_area", "counting"),
|
||||
("palet", "palet"),
|
||||
):
|
||||
pts = raw.get(target_key) if target_key in raw else raw.get(flat_key)
|
||||
if pts is not None:
|
||||
out[target_key] = _scale_polygon(pts, target_key, sx, sy)
|
||||
|
||||
if raw.get("count_line") is not None:
|
||||
line = raw["count_line"]
|
||||
if not isinstance(line, dict):
|
||||
raise ValueError("count_line must be an object")
|
||||
scaled_line = dict(line)
|
||||
for coord_key, sc in (("x_start", sx), ("x_end", sx), ("y", sy)):
|
||||
v = line.get(coord_key)
|
||||
if not _is_finite_real(v):
|
||||
raise ValueError("count_line needs integer x_start, x_end and y")
|
||||
scaled_line[coord_key] = _scale_coord(v, sc)
|
||||
out["count_line"] = scaled_line
|
||||
elif raw.get("counting_line") is not None:
|
||||
cl = raw["counting_line"]
|
||||
if not (
|
||||
isinstance(cl, list)
|
||||
and len(cl) == 2
|
||||
and all(
|
||||
isinstance(p, (list, tuple)) and len(p) == 2
|
||||
and _is_finite_real(p[0]) and _is_finite_real(p[1])
|
||||
for p in cl
|
||||
)
|
||||
):
|
||||
raise ValueError("counting_line must be 2 [x, y] points")
|
||||
xs = sorted([float(cl[0][0]), float(cl[1][0])])
|
||||
mean_y = (float(cl[0][1]) + float(cl[1][1])) / 2.0
|
||||
out["count_line"] = {
|
||||
"x_start": int(round(xs[0] * sx)),
|
||||
"x_end": int(round(xs[1] * sx)),
|
||||
"y": int(round(mean_y * sy)),
|
||||
}
|
||||
elif any(k in raw for k in ("line_y", "line_x_start", "line_x_end")):
|
||||
xs_raw, xe_raw, y_raw = (
|
||||
raw.get("line_x_start"),
|
||||
raw.get("line_x_end"),
|
||||
raw.get("line_y"),
|
||||
)
|
||||
if not (_is_finite_real(xs_raw) and _is_finite_real(xe_raw) and _is_finite_real(y_raw)):
|
||||
raise ValueError("count_line needs integer x_start, x_end and y")
|
||||
out["count_line"] = {
|
||||
"x_start": _scale_coord(xs_raw, sx),
|
||||
"x_end": _scale_coord(xe_raw, sx),
|
||||
"y": _scale_coord(y_raw, sy),
|
||||
}
|
||||
|
||||
out["reference_resolution"] = [ZONE_BOUNDS_W, ZONE_BOUNDS_H]
|
||||
return out
|
||||
|
||||
|
||||
def validate_zone_preset(preset: dict[str, Any]) -> dict[str, Any]:
|
||||
@@ -238,12 +388,12 @@ def validate_zone_preset(preset: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
Checks: truck_area present with exactly 4 points (the runtime needs 4);
|
||||
every polygon key that is present holds >=3 points of 2 finite numbers
|
||||
inside 0..1280 x 0..720 and forms a valid polygon with area > 0;
|
||||
inside 0..1920 x 0..1080 and forms a valid polygon with area > 0;
|
||||
count_line has finite integer x_start < x_end and a y inside the frame;
|
||||
reference_resolution, when present, is the analysis space [1280, 720].
|
||||
reference_resolution, when present, is [1920, 1080].
|
||||
Unknown keys (the tuning knobs) pass through untouched.
|
||||
|
||||
Returns a normalized copy: count_line numbers and reference_resolution
|
||||
Returns a validated copy: count_line numbers and reference_resolution
|
||||
become ints, so the caller persists exactly what was checked.
|
||||
"""
|
||||
if not isinstance(preset, dict):
|
||||
@@ -261,8 +411,7 @@ def validate_zone_preset(preset: dict[str, Any]) -> dict[str, Any]:
|
||||
raise ValueError(
|
||||
f"reference_resolution must be [{ZONE_BOUNDS_W}, {ZONE_BOUNDS_H}]"
|
||||
)
|
||||
# Always pin the analysis space: a preset without the key would fall back
|
||||
# to build_static_roi's 1920x1080 default and be scaled by 1280/1920.
|
||||
# Always pin the native 1920x1080 space (scaled to 1280x720 at runtime).
|
||||
normalized["reference_resolution"] = [ZONE_BOUNDS_W, ZONE_BOUNDS_H]
|
||||
|
||||
for key in _POLYGON_KEYS:
|
||||
@@ -318,7 +467,9 @@ def validate_zone_preset(preset: dict[str, Any]) -> dict[str, Any]:
|
||||
nums[name] = int(fv)
|
||||
x_start, x_end, y = nums["x_start"], nums["x_end"], nums["y"]
|
||||
if not (0 <= x_start < x_end <= ZONE_BOUNDS_W):
|
||||
raise ValueError("count_line x_start/x_end must satisfy 0 <= x_start < x_end <= 1280")
|
||||
raise ValueError(
|
||||
f"count_line x_start/x_end must satisfy 0 <= x_start < x_end <= {ZONE_BOUNDS_W}"
|
||||
)
|
||||
if not (0 <= y <= ZONE_BOUNDS_H):
|
||||
raise ValueError(f"count_line y={y} is outside 0..{ZONE_BOUNDS_H}")
|
||||
normalized["count_line"] = {**line, **nums}
|
||||
@@ -330,23 +481,51 @@ def validate_zone_preset(preset: dict[str, Any]) -> dict[str, Any]:
|
||||
_SAVE_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def _write_zone_config_atomic(path: str, config: dict[str, Any]) -> None:
|
||||
"""Atomically overwrite zones.json with a .bak backup, preserving file mode."""
|
||||
shutil.copy2(path, path + ".bak")
|
||||
directory = os.path.dirname(os.path.abspath(path))
|
||||
fd, tmp = tempfile.mkstemp(
|
||||
dir=directory, prefix=os.path.basename(path) + ".", suffix=".tmp"
|
||||
)
|
||||
try:
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
||||
json.dump(config, f, indent=2)
|
||||
f.write("\n")
|
||||
# mkstemp creates 0600; keep the mode the file had before.
|
||||
os.chmod(tmp, os.stat(path).st_mode & 0o777)
|
||||
os.replace(tmp, path)
|
||||
except BaseException:
|
||||
if os.path.exists(tmp):
|
||||
os.unlink(tmp)
|
||||
raise
|
||||
|
||||
|
||||
def save_zone_preset(path: str, name: str, preset: dict[str, Any],
|
||||
replace: bool = False) -> None:
|
||||
"""Merge a preset into zones.json under `name`, atomically, with a backup.
|
||||
|
||||
The posted preset is merged OVER the stored one, so a partial post (only
|
||||
the geometry) keeps the preset's tuning knobs. Sibling presets and
|
||||
active_preset are never touched. With replace=True the stored preset is
|
||||
replaced wholesale by the given one (used by the reset route).
|
||||
Accepts either a standard recounter preset or FCP's flat zones.json shape
|
||||
(auto-normalized to [1920, 1080] before merging). The preset is merged
|
||||
OVER the stored one unless replace=True.
|
||||
|
||||
The normalized preset returned by validate_zone_preset is what gets
|
||||
persisted, so a float count_line is stored as an int.
|
||||
|
||||
Raises FileNotFoundError if the file does not exist (this function never
|
||||
creates a zones.json) and ValueError if the file is not a usable config.
|
||||
Raises FileNotFoundError if the file does not exist and ValueError if the
|
||||
file or preset is unusable.
|
||||
"""
|
||||
if not os.path.isfile(path):
|
||||
raise FileNotFoundError(f"zones.json not found: {path}")
|
||||
if not isinstance(preset, dict):
|
||||
raise ValueError("preset must be an object")
|
||||
ref = preset.get("reference_resolution")
|
||||
is_legacy_720p = (
|
||||
isinstance(ref, (list, tuple))
|
||||
and len(ref) == 2
|
||||
and _is_finite_real(ref[0])
|
||||
and _is_finite_real(ref[1])
|
||||
and [float(ref[0]), float(ref[1])] == [1280.0, 720.0]
|
||||
)
|
||||
if any(k in preset for k in _FCP_FLAT_KEYS) or is_legacy_720p:
|
||||
preset = normalize_zone_preset(preset)
|
||||
with _SAVE_LOCK:
|
||||
config = load_zone_config(path)
|
||||
if not isinstance(config, dict):
|
||||
@@ -359,18 +538,125 @@ def save_zone_preset(path: str, name: str, preset: dict[str, Any],
|
||||
raise ValueError("zones.json 'presets' must be a JSON object")
|
||||
merged = preset if replace else {**presets.get(name, {}), **preset}
|
||||
presets[name] = validate_zone_preset(merged)
|
||||
shutil.copy2(path, path + ".bak")
|
||||
directory = os.path.dirname(os.path.abspath(path))
|
||||
fd, tmp = tempfile.mkstemp(dir=directory, prefix=os.path.basename(path) + ".",
|
||||
suffix=".tmp")
|
||||
_write_zone_config_atomic(path, config)
|
||||
|
||||
|
||||
def _resolve_fcp_zones_source(zones_path: str, fcp_zones_path: str | None) -> str | None:
|
||||
"""Return FCP zones.json path to sync from, or None when auto-sync is disabled."""
|
||||
if fcp_zones_path is not None:
|
||||
return fcp_zones_path.strip() or None
|
||||
if "FCP_ZONES_PATH" in os.environ:
|
||||
return os.environ["FCP_ZONES_PATH"].strip() or None
|
||||
if os.path.abspath(zones_path) == _REPO_ZONES_PATH:
|
||||
return _DEFAULT_FCP_ZONES_PATH
|
||||
return None
|
||||
|
||||
|
||||
def sync_fcp_zones(
|
||||
zones_path: str,
|
||||
fcp_zones_path: str | None = None,
|
||||
*,
|
||||
force: bool = False,
|
||||
) -> bool:
|
||||
"""Sync presets['default'] from FCP's zones.json when FCP's file is newer.
|
||||
|
||||
Returns True when zones_path was updated, False otherwise. Never raises on
|
||||
an unreadable/malformed external FCP file or write failure so fixed-zone
|
||||
inference and read routes degrade cleanly.
|
||||
"""
|
||||
src = _resolve_fcp_zones_source(zones_path, fcp_zones_path)
|
||||
if not src or not os.path.isfile(src) or not os.path.isfile(zones_path):
|
||||
return False
|
||||
if os.path.abspath(src) == os.path.abspath(zones_path):
|
||||
return False
|
||||
try:
|
||||
src_st = os.stat(src)
|
||||
dst_st = os.stat(zones_path)
|
||||
except OSError:
|
||||
return False
|
||||
if not force and src_st.st_mtime_ns <= dst_st.st_mtime_ns:
|
||||
return False
|
||||
try:
|
||||
raw_fcp = load_zone_config(src)
|
||||
normalized = normalize_zone_preset(raw_fcp)
|
||||
candidate = validate_zone_preset(normalized)
|
||||
except (OSError, ValueError, TypeError, OverflowError) as exc:
|
||||
print(f"[ZONE] ignoring unreadable FCP zones at {src}: {exc}")
|
||||
return False
|
||||
|
||||
with _SAVE_LOCK:
|
||||
try:
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
||||
json.dump(config, f, indent=2)
|
||||
f.write("\n")
|
||||
# mkstemp creates 0600; keep the mode the file had before.
|
||||
os.chmod(tmp, os.stat(path).st_mode & 0o777)
|
||||
os.replace(tmp, path)
|
||||
except BaseException:
|
||||
if os.path.exists(tmp):
|
||||
os.unlink(tmp)
|
||||
raise
|
||||
src_st = os.stat(src)
|
||||
dst_st = os.stat(zones_path)
|
||||
if not force and src_st.st_mtime_ns <= dst_st.st_mtime_ns:
|
||||
return False
|
||||
config = load_zone_config(zones_path)
|
||||
if not isinstance(config, dict):
|
||||
return False
|
||||
presets = config.get("presets")
|
||||
if presets is None:
|
||||
presets = {}
|
||||
config["presets"] = presets
|
||||
elif not isinstance(presets, dict):
|
||||
return False
|
||||
current = presets.get("default", {})
|
||||
if not isinstance(current, dict):
|
||||
current = {}
|
||||
merged = validate_zone_preset({**current, **candidate})
|
||||
if merged == current and not force:
|
||||
return False
|
||||
presets["default"] = merged
|
||||
_write_zone_config_atomic(zones_path, config)
|
||||
except (OSError, ValueError, TypeError, OverflowError) as exc:
|
||||
print(f"[ZONE] failed to sync FCP zones into {zones_path}: {exc}")
|
||||
return False
|
||||
print(f"[ZONE] synced 'default' preset from FCP zones: {src}")
|
||||
return True
|
||||
|
||||
|
||||
def resolve_zone(
|
||||
zone_mode: str,
|
||||
zone_preset: str,
|
||||
zones_path: str,
|
||||
analysis_size: tuple[int, int] = (1280, 720),
|
||||
*,
|
||||
zone_reader=None,
|
||||
) -> tuple[str, TruckROI | None, str, Polygon | None, Polygon | None]:
|
||||
"""Resolve the counting zone of a job or CLI run in analysis_size (1280x720).
|
||||
|
||||
Auto-syncs 'default' from FCP's zones.json when newer, then builds the
|
||||
fixed TruckROI + counting/truck polygons. Falls back to 'dynamic' if
|
||||
zones_path is missing or malformed.
|
||||
"""
|
||||
if zone_mode != "fixed":
|
||||
return zone_mode, None, zone_preset, None, None
|
||||
sync_fcp_zones(zones_path)
|
||||
reader = zone_reader or get_active_zone
|
||||
w, h = analysis_size
|
||||
reason = "no zone file"
|
||||
roi: TruckROI | None = None
|
||||
polygon: Polygon | None = None
|
||||
truck_polygon: Polygon | None = None
|
||||
built = False
|
||||
if os.path.isfile(zones_path):
|
||||
try:
|
||||
zone = reader(zones_path, zone_preset or None)
|
||||
if zone is None:
|
||||
reason = "no active preset"
|
||||
else:
|
||||
roi = build_static_roi(zone, w, h)
|
||||
polygon = build_counting_polygon(zone, w, h)
|
||||
truck_polygon = build_truck_polygon(zone, w, h)
|
||||
if zone.get("counting_area") and polygon is None:
|
||||
reason = "malformed counting_area"
|
||||
else:
|
||||
built = True
|
||||
except (
|
||||
OSError, ValueError, TypeError, AttributeError,
|
||||
IndexError, KeyError, OverflowError, GEOSException,
|
||||
) as exc:
|
||||
reason = f"unreadable calibration — could not be read/applied ({exc})"
|
||||
if not built:
|
||||
print(f"[ZONE] {reason} at {zones_path} — falling back to dynamic")
|
||||
return "dynamic", None, zone_preset, None, None
|
||||
return "fixed", roi, zone_preset or "default", polygon, truck_polygon
|
||||
+162
-64
@@ -1,15 +1,15 @@
|
||||
/* Interactive zone editor.
|
||||
*
|
||||
* The backdrop is a frame already resized to the 1280x720 analysis space and
|
||||
* the SVG overlay uses the same viewBox, so a page pixel maps to an analysis
|
||||
* pixel with one uniform scale (plus the letterbox offset of "xMidYMid meet").
|
||||
* The backdrop is a 16:9 frame (1280x720) and the SVG overlay uses a
|
||||
* 1920x1080 viewBox, so coordinates are edited directly in FCP's 1920x1080
|
||||
* zone space with uniform scaling and letterbox offset ("xMidYMid meet").
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
const ZONE_SOURCE_W = 1280;
|
||||
const ZONE_SOURCE_H = 720;
|
||||
const ZONE_LINE_MARGIN = 20; // the counter's trigger band (margin=20)
|
||||
const ZONE_SOURCE_W = 1920;
|
||||
const ZONE_SOURCE_H = 1080;
|
||||
const ZONE_LINE_MARGIN = 30; // 20px trigger band in 720p == 30px in 1080p
|
||||
|
||||
const SVG_NS = 'http://www.w3.org/2000/svg';
|
||||
|
||||
@@ -94,7 +94,7 @@
|
||||
}));
|
||||
pts.forEach(function (pt, i) {
|
||||
layer.appendChild(makeHandle(
|
||||
'zh-' + area.vis + '-' + i, area.color, pt[0], pt[1], 8,
|
||||
'zh-' + area.vis + '-' + i, area.color, pt[0], pt[1], 12,
|
||||
function (ev) { startZoneDrag(ev, area.key, 'poly', i); }
|
||||
));
|
||||
});
|
||||
@@ -129,7 +129,7 @@
|
||||
|
||||
line.forEach(function (pt, i) {
|
||||
layer.appendChild(makeHandle(
|
||||
'zh-line-' + i, '#16a34a', pt[0], lineY, 9,
|
||||
'zh-line-' + i, '#16a34a', pt[0], lineY, 13,
|
||||
function (ev) { startZoneDrag(ev, 'counting_line', 'line', i); }
|
||||
));
|
||||
});
|
||||
@@ -251,14 +251,103 @@
|
||||
renderZones();
|
||||
}
|
||||
|
||||
function applyPreset(preset) {
|
||||
function buildCurrentPresetPayload() {
|
||||
const xs = zonesData.counting_line.map(function (p) { return p[0]; });
|
||||
const ys = zonesData.counting_line.map(function (p) { return p[1]; });
|
||||
const obj = {
|
||||
truck_area: zonesData.truck_area,
|
||||
counting_area: zonesData.counting_area,
|
||||
count_line: {
|
||||
x_start: Math.min.apply(null, xs),
|
||||
x_end: Math.max.apply(null, xs),
|
||||
y: Math.round(ys.reduce(function (a, b) { return a + b; }, 0) / ys.length)
|
||||
},
|
||||
reference_resolution: [ZONE_SOURCE_W, ZONE_SOURCE_H]
|
||||
};
|
||||
if (Array.isArray(zonesData.palet) && zonesData.palet.length >= 3) {
|
||||
obj.palet = zonesData.palet;
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
|
||||
function isFiniteNumber(v) {
|
||||
return typeof v === 'number' && Number.isFinite(v);
|
||||
}
|
||||
|
||||
function resolveInputSpace(obj) {
|
||||
if ('coord_space' in obj && obj.coord_space !== undefined && obj.coord_space !== null) {
|
||||
if (typeof obj.coord_space !== 'string' || !obj.coord_space.trim()) {
|
||||
throw new Error('coord_space must be formatted like "1920x1080"');
|
||||
}
|
||||
const parts = obj.coord_space.trim().toLowerCase().split('x');
|
||||
if (parts.length === 2) {
|
||||
const w = Number(parts[0]);
|
||||
const h = Number(parts[1]);
|
||||
if (parts[0].trim() && parts[1].trim() && Number.isFinite(w) && Number.isFinite(h) && w > 0 && h > 0) {
|
||||
return [w, h];
|
||||
}
|
||||
}
|
||||
throw new Error('coord_space must be formatted like "1920x1080"');
|
||||
}
|
||||
if ('reference_resolution' in obj && obj.reference_resolution !== undefined && obj.reference_resolution !== null) {
|
||||
if (!Array.isArray(obj.reference_resolution) || obj.reference_resolution.length !== 2) {
|
||||
throw new Error('reference_resolution must be [width, height]');
|
||||
}
|
||||
const rw = obj.reference_resolution[0];
|
||||
const rh = obj.reference_resolution[1];
|
||||
if (!isFiniteNumber(rw) || !isFiniteNumber(rh) || rw <= 0 || rh <= 0) {
|
||||
throw new Error('reference_resolution values must be positive numbers');
|
||||
}
|
||||
return [rw, rh];
|
||||
}
|
||||
return [ZONE_SOURCE_W, ZONE_SOURCE_H];
|
||||
}
|
||||
|
||||
function scalePresetToSource(preset, srcW, srcH) {
|
||||
const sx = srcW ? (ZONE_SOURCE_W / srcW) : 1;
|
||||
const sy = srcH ? (ZONE_SOURCE_H / srcH) : 1;
|
||||
const scalePt = function (p) {
|
||||
return (sx === 1 && sy === 1)
|
||||
? [p[0], p[1]]
|
||||
: [Math.round(p[0] * sx), Math.round(p[1] * sy)];
|
||||
};
|
||||
const scaleVal = function (v, sc) {
|
||||
return sc === 1 ? v : Math.round(v * sc);
|
||||
};
|
||||
const line = (preset && preset.count_line) || {};
|
||||
const out = {
|
||||
truck_area: Array.isArray(preset.truck_area) ? preset.truck_area.map(scalePt) : [],
|
||||
counting_area: Array.isArray(preset.counting_area) ? preset.counting_area.map(scalePt) : [],
|
||||
count_line: {
|
||||
x_start: scaleVal(isFiniteNumber(line.x_start) ? line.x_start : 0, sx),
|
||||
x_end: scaleVal(isFiniteNumber(line.x_end) ? line.x_end : 0, sx),
|
||||
y: scaleVal(isFiniteNumber(line.y) ? line.y : 0, sy)
|
||||
},
|
||||
reference_resolution: [ZONE_SOURCE_W, ZONE_SOURCE_H]
|
||||
};
|
||||
if (Array.isArray(preset.palet)) {
|
||||
out.palet = preset.palet.map(scalePt);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function applyPreset(preset) {
|
||||
const raw = preset || {};
|
||||
let res = [ZONE_SOURCE_W, ZONE_SOURCE_H];
|
||||
try {
|
||||
res = resolveInputSpace(raw);
|
||||
} catch (e) {
|
||||
res = [ZONE_SOURCE_W, ZONE_SOURCE_H];
|
||||
}
|
||||
const normalized = scalePresetToSource(raw, res[0], res[1]);
|
||||
const line = normalized.count_line;
|
||||
zonesData = {
|
||||
truck_area: (preset && preset.truck_area) || [],
|
||||
counting_area: (preset && preset.counting_area) || [],
|
||||
truck_area: normalized.truck_area,
|
||||
counting_area: normalized.counting_area,
|
||||
palet: Array.isArray(normalized.palet) ? normalized.palet : null,
|
||||
counting_line: [
|
||||
[Number(line.x_start) || 0, Number(line.y) || 0],
|
||||
[Number(line.x_end) || 0, Number(line.y) || 0]
|
||||
[line.x_start, line.y],
|
||||
[line.x_end, line.y]
|
||||
]
|
||||
};
|
||||
renderZones();
|
||||
@@ -285,20 +374,7 @@
|
||||
setStatus('Nothing to save');
|
||||
return;
|
||||
}
|
||||
const xs = zonesData.counting_line.map(function (p) { return p[0]; });
|
||||
const ys = zonesData.counting_line.map(function (p) { return p[1]; });
|
||||
const payload = {
|
||||
preset: {
|
||||
truck_area: zonesData.truck_area,
|
||||
counting_area: zonesData.counting_area,
|
||||
count_line: {
|
||||
x_start: Math.min.apply(null, xs),
|
||||
x_end: Math.max.apply(null, xs),
|
||||
y: Math.round(ys.reduce(function (a, b) { return a + b; }, 0) / ys.length)
|
||||
},
|
||||
reference_resolution: [ZONE_SOURCE_W, ZONE_SOURCE_H]
|
||||
}
|
||||
};
|
||||
const payload = { preset: buildCurrentPresetPayload() };
|
||||
try {
|
||||
const res = await fetch('/api/zones/' + encodeURIComponent(currentPreset), {
|
||||
method: 'POST',
|
||||
@@ -321,29 +397,59 @@
|
||||
let obj;
|
||||
try { obj = JSON.parse(text); } catch (e) { throw new Error('Invalid JSON: ' + e.message); }
|
||||
if (!obj || typeof obj !== 'object' || Array.isArray(obj)) throw new Error('Expected a JSON object');
|
||||
const truck = obj.truck_area;
|
||||
const counting = obj.counting_area;
|
||||
const line = obj.count_line;
|
||||
if (!Array.isArray(truck) || truck.length !== 4) throw new Error('truck_area must be an array of 4 [x,y] points');
|
||||
if (!Array.isArray(counting) || counting.length < 3) throw new Error('counting_area must be an array of at least 3 [x,y] points');
|
||||
if (!line || typeof line !== 'object') throw new Error('count_line must be an object {x_start, x_end, y}');
|
||||
const xs = [Number(line.x_start), Number(line.x_end)];
|
||||
const y = Number(line.y);
|
||||
if (!xs.every(function (v) { return Number.isFinite(v); }) || !Number.isFinite(y)) throw new Error('count_line values must be finite numbers');
|
||||
for (let i = 0; i < truck.length; i++) {
|
||||
if (!Array.isArray(truck[i]) || truck[i].length !== 2) throw new Error('truck_area points must be [x,y]');
|
||||
if (!truck[i].every(function (v) { return Number.isFinite(Number(v)); })) throw new Error('truck_area values must be finite numbers');
|
||||
|
||||
const res = resolveInputSpace(obj);
|
||||
const truck = ('truck_area' in obj) ? obj.truck_area : obj.truck;
|
||||
const counting = ('counting_area' in obj) ? obj.counting_area : obj.counting;
|
||||
if (!Array.isArray(truck) || truck.length !== 4) throw new Error('truck_area/truck must be an array of 4 [x,y] points');
|
||||
if (!Array.isArray(counting) || counting.length < 3) throw new Error('counting_area/counting must be an array of at least 3 [x,y] points');
|
||||
|
||||
let x0, x1, lineY;
|
||||
if (obj.count_line && typeof obj.count_line === 'object' && !Array.isArray(obj.count_line)) {
|
||||
x0 = obj.count_line.x_start;
|
||||
x1 = obj.count_line.x_end;
|
||||
lineY = obj.count_line.y;
|
||||
} else if (Array.isArray(obj.counting_line) && obj.counting_line.length === 2
|
||||
&& Array.isArray(obj.counting_line[0]) && obj.counting_line[0].length === 2
|
||||
&& Array.isArray(obj.counting_line[1]) && obj.counting_line[1].length === 2) {
|
||||
x0 = obj.counting_line[0][0];
|
||||
x1 = obj.counting_line[1][0];
|
||||
lineY = (obj.counting_line[0][1] + obj.counting_line[1][1]) / 2;
|
||||
} else if ('line_y' in obj || 'line_x_start' in obj || 'line_x_end' in obj) {
|
||||
x0 = obj.line_x_start;
|
||||
x1 = obj.line_x_end;
|
||||
lineY = obj.line_y;
|
||||
} else {
|
||||
throw new Error('count_line or line_y/line_x_start/line_x_end is required');
|
||||
}
|
||||
for (let i = 0; i < counting.length; i++) {
|
||||
if (!Array.isArray(counting[i]) || counting[i].length !== 2) throw new Error('counting_area points must be [x,y]');
|
||||
if (!counting[i].every(function (v) { return Number.isFinite(Number(v)); })) throw new Error('counting_area values must be finite numbers');
|
||||
if (!isFiniteNumber(x0) || !isFiniteNumber(x1) || !isFiniteNumber(lineY)) {
|
||||
throw new Error('count_line values must be finite numbers');
|
||||
}
|
||||
return {
|
||||
truck_area: truck.map(function (p) { return [Number(p[0]), Number(p[1])]; }),
|
||||
counting_area: counting.map(function (p) { return [Number(p[0]), Number(p[1])]; }),
|
||||
count_line: { x_start: Math.min(xs[0], xs[1]), x_end: Math.max(xs[0], xs[1]), y: Math.round(y) },
|
||||
reference_resolution: Array.isArray(obj.reference_resolution) ? obj.reference_resolution : [ZONE_SOURCE_W, ZONE_SOURCE_H]
|
||||
|
||||
const checkPoly = function (pts, label) {
|
||||
for (let i = 0; i < pts.length; i++) {
|
||||
if (!Array.isArray(pts[i]) || pts[i].length !== 2) throw new Error(label + ' points must be [x,y]');
|
||||
if (!pts[i].every(isFiniteNumber)) {
|
||||
throw new Error(label + ' values must be finite numbers');
|
||||
}
|
||||
}
|
||||
};
|
||||
checkPoly(truck, 'truck_area');
|
||||
checkPoly(counting, 'counting_area');
|
||||
if (obj.palet !== undefined) {
|
||||
if (!Array.isArray(obj.palet) || obj.palet.length < 3) throw new Error('palet must be at least 3 [x,y] points');
|
||||
checkPoly(obj.palet, 'palet');
|
||||
}
|
||||
|
||||
const unscaled = {
|
||||
truck_area: truck,
|
||||
counting_area: counting,
|
||||
count_line: { x_start: Math.min(x0, x1), x_end: Math.max(x0, x1), y: Math.round(lineY) }
|
||||
};
|
||||
if (obj.palet !== undefined) unscaled.palet = obj.palet;
|
||||
const parsed = scalePresetToSource(unscaled, res[0], res[1]);
|
||||
parsed._source_resolution = res;
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function importJson() {
|
||||
@@ -351,8 +457,14 @@
|
||||
if (!ta) return;
|
||||
try {
|
||||
const preset = parseZoneJson(ta.value);
|
||||
const src = preset._source_resolution;
|
||||
delete preset._source_resolution;
|
||||
applyPreset(preset);
|
||||
setStatus('Imported — drag handles or Save');
|
||||
if (src && (src[0] !== ZONE_SOURCE_W || src[1] !== ZONE_SOURCE_H)) {
|
||||
setStatus('Imported (scaled ' + src[0] + 'x' + src[1] + ' -> 1920x1080) — drag handles or Save');
|
||||
} else {
|
||||
setStatus('Imported — drag handles or Save');
|
||||
}
|
||||
} catch (err) {
|
||||
setStatus('Import failed: ' + err.message);
|
||||
}
|
||||
@@ -360,14 +472,7 @@
|
||||
|
||||
function exportJson() {
|
||||
if (!zonesData) { setStatus('Nothing to export'); return; }
|
||||
const xs = zonesData.counting_line.map(function (p) { return p[0]; });
|
||||
const ys = zonesData.counting_line.map(function (p) { return p[1]; });
|
||||
const obj = {
|
||||
truck_area: zonesData.truck_area,
|
||||
counting_area: zonesData.counting_area,
|
||||
count_line: { x_start: Math.min.apply(null, xs), x_end: Math.max.apply(null, xs), y: Math.round(ys.reduce(function (a, b) { return a + b; }, 0) / ys.length) },
|
||||
reference_resolution: [ZONE_SOURCE_W, ZONE_SOURCE_H]
|
||||
};
|
||||
const obj = buildCurrentPresetPayload();
|
||||
const text = JSON.stringify(obj, null, 2);
|
||||
const ta = $('zone-json');
|
||||
if (ta) ta.value = text;
|
||||
@@ -380,14 +485,7 @@
|
||||
|
||||
function downloadJson() {
|
||||
if (!zonesData) { setStatus('Nothing to download'); return; }
|
||||
const xs = zonesData.counting_line.map(function (p) { return p[0]; });
|
||||
const ys = zonesData.counting_line.map(function (p) { return p[1]; });
|
||||
const obj = {
|
||||
truck_area: zonesData.truck_area,
|
||||
counting_area: zonesData.counting_area,
|
||||
count_line: { x_start: Math.min.apply(null, xs), x_end: Math.max.apply(null, xs), y: Math.round(ys.reduce(function (a, b) { return a + b; }, 0) / ys.length) },
|
||||
reference_resolution: [ZONE_SOURCE_W, ZONE_SOURCE_H]
|
||||
};
|
||||
const obj = buildCurrentPresetPayload();
|
||||
const blob = new Blob([JSON.stringify(obj, null, 2)], { type: 'application/json' });
|
||||
const a = document.createElement('a');
|
||||
a.href = URL.createObjectURL(blob);
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<div class="calibrate-heading">
|
||||
<h2>Zone Calibration</h2>
|
||||
<p>Drag the counting area, truck area and count line over a frame of an uploaded video, then save.
|
||||
Every coordinate is in the 1280×720 analysis space.
|
||||
Coordinates are stored in 1920×1080 (scaled to 1280×720 at runtime to match FCP).
|
||||
<a href="/" class="btn btn-ghost btn-sm" style="margin-left: var(--space-2);">← Back to Upload</a>
|
||||
</p>
|
||||
</div>
|
||||
@@ -38,7 +38,7 @@
|
||||
|
||||
<details class="calibrate-json-panel">
|
||||
<summary>Import / Export JSON</summary>
|
||||
<textarea id="zone-json" rows="6" placeholder='{"truck_area":[[x,y],...],"counting_area":[[x,y],...],"count_line":{"x_start":0,"x_end":0,"y":0},"reference_resolution":[1280,720]}'></textarea>
|
||||
<textarea id="zone-json" rows="6" placeholder='{"truck_area":[[x,y],...],"counting_area":[[x,y],...],"count_line":{"x_start":0,"x_end":0,"y":0},"reference_resolution":[1920,1080]}'></textarea>
|
||||
<div class="calibrate-json-actions">
|
||||
<button id="zone-import-btn" type="button" class="btn btn-secondary btn-sm">Import JSON</button>
|
||||
<button id="zone-copy-btn" type="button" class="btn btn-ghost btn-sm">Copy current zones</button>
|
||||
@@ -48,7 +48,7 @@
|
||||
|
||||
<div class="calibrate-stage">
|
||||
<img id="zone-backdrop" alt="Video frame under the zone overlay">
|
||||
<svg id="zoneOverlay" viewBox="0 0 1280 720" preserveAspectRatio="xMidYMid meet">
|
||||
<svg id="zoneOverlay" viewBox="0 0 1920 1080" preserveAspectRatio="xMidYMid meet">
|
||||
<g id="zoneLayer"></g>
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
@@ -13,6 +13,9 @@ def _isolate_job_queue(tmp_path, monkeypatch):
|
||||
# .env RECOUNTER_API_KEY must not leak into tests (it enables 401 auth);
|
||||
# auth tests set/override it via their own monkeypatch.setenv calls.
|
||||
monkeypatch.delenv("RECOUNTER_API_KEY", raising=False)
|
||||
# Prevent host FCP zones.json auto-sync during isolated unit tests unless
|
||||
# a test sets FCP_ZONES_PATH or passes fcp_zones_path explicitly.
|
||||
monkeypatch.setenv("FCP_ZONES_PATH", "")
|
||||
import app as app_module
|
||||
|
||||
q = app_module.job_queue
|
||||
|
||||
+158
-28
@@ -633,25 +633,25 @@ def _zones_file(tmp_path, preset):
|
||||
def test_post_zones_saves_valid_preset(client, tmp_path, monkeypatch):
|
||||
import app as app_module
|
||||
preset = {
|
||||
"truck_area": [[400, 257], [406, 717], [936, 719], [921, 229]],
|
||||
"counting_area": [[383, 33], [391, 718], [945, 717], [931, 33]],
|
||||
"count_line": {"x_start": 385, "x_end": 934, "y": 220},
|
||||
"reference_resolution": [1280, 720],
|
||||
"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],
|
||||
}
|
||||
zones = _zones_file(tmp_path, preset)
|
||||
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
|
||||
resp = client.post("/api/zones/default", json={"preset": {**preset, "count_line": {"x_start": 400, "x_end": 900, "y": 210}}})
|
||||
resp = client.post("/api/zones/default", json={"preset": {**preset, "count_line": {"x_start": 600, "x_end": 1350, "y": 315}}})
|
||||
assert resp.status_code == 200
|
||||
saved = json.loads(open(zones).read())
|
||||
assert saved["presets"]["default"]["count_line"]["y"] == 210
|
||||
assert saved["presets"]["default"]["count_line"]["y"] == 315
|
||||
|
||||
|
||||
def test_post_zones_invalid_is_400_and_file_unchanged(client, tmp_path, monkeypatch):
|
||||
import app as app_module
|
||||
preset = {
|
||||
"truck_area": [[400, 257], [406, 717], [936, 719], [921, 229]],
|
||||
"count_line": {"x_start": 385, "x_end": 934, "y": 220},
|
||||
"reference_resolution": [1280, 720],
|
||||
"truck_area": [[600, 385], [609, 1076], [1404, 1078], [1381, 343]],
|
||||
"count_line": {"x_start": 577, "x_end": 1401, "y": 330},
|
||||
"reference_resolution": [1920, 1080],
|
||||
}
|
||||
zones = _zones_file(tmp_path, preset)
|
||||
before = open(zones).read()
|
||||
@@ -663,7 +663,7 @@ def test_post_zones_invalid_is_400_and_file_unchanged(client, tmp_path, monkeypa
|
||||
|
||||
def test_post_zones_from_non_localhost_is_403(client, tmp_path, monkeypatch):
|
||||
import app as app_module
|
||||
zones = _zones_file(tmp_path, {"truck_area": [[0, 0], [10, 0], [10, 10]]})
|
||||
zones = _zones_file(tmp_path, {"truck_area": [[0, 0], [10, 0], [10, 10], [0, 10]]})
|
||||
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
|
||||
resp = client.post("/api/zones/default", json={"preset": {}},
|
||||
environ_base={"REMOTE_ADDR": "10.1.2.3"})
|
||||
@@ -672,36 +672,36 @@ def test_post_zones_from_non_localhost_is_403(client, tmp_path, monkeypatch):
|
||||
|
||||
def test_post_zones_reset_restores_the_default_preset(client, tmp_path, monkeypatch):
|
||||
import app as app_module
|
||||
zones = _zones_file(tmp_path, {"truck_area": [[0, 0], [10, 0], [10, 10]],
|
||||
zones = _zones_file(tmp_path, {"truck_area": [[0, 0], [10, 0], [10, 10], [0, 10]],
|
||||
"count_line": {"x_start": 1, "x_end": 2, "y": 3}})
|
||||
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
|
||||
resp = client.post("/api/zones/default/reset")
|
||||
assert resp.status_code == 200
|
||||
saved = json.loads(open(zones).read())
|
||||
assert saved["presets"]["default"]["count_line"] == {"x_start": 423, "x_end": 939, "y": 182}
|
||||
assert saved["presets"]["default"]["count_line"] == {"x_start": 577, "x_end": 1401, "y": 215}
|
||||
|
||||
|
||||
# --- fix round 1: route-level coverage for F1-F9 ---
|
||||
|
||||
def _route_preset(**overrides):
|
||||
"""A valid preset in the 1280x720 analysis space, with overrides applied."""
|
||||
"""A valid preset in the native 1920x1080 zone space, with overrides applied."""
|
||||
preset = {
|
||||
"truck_area": [[400, 257], [406, 717], [936, 719], [921, 229]],
|
||||
"count_line": {"x_start": 385, "x_end": 934, "y": 220},
|
||||
"reference_resolution": [1280, 720],
|
||||
"truck_area": [[600, 385], [609, 1076], [1404, 1078], [1381, 343]],
|
||||
"count_line": {"x_start": 577, "x_end": 1401, "y": 330},
|
||||
"reference_resolution": [1920, 1080],
|
||||
}
|
||||
preset.update(overrides)
|
||||
return preset
|
||||
|
||||
|
||||
def test_post_zones_rejects_a_foreign_reference_resolution(client, tmp_path, monkeypatch):
|
||||
"""F1: a 1920x1080 preset would be scaled twice; the file must not change."""
|
||||
"""F1: a foreign preset resolution is rejected when sent as a preset; the file must not change."""
|
||||
import app as app_module
|
||||
zones = _zones_file(tmp_path, _route_preset())
|
||||
before = open(zones).read()
|
||||
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
|
||||
resp = client.post("/api/zones/default",
|
||||
json={"preset": _route_preset(reference_resolution=[1920, 1080])})
|
||||
json={"preset": _route_preset(reference_resolution=[640, 480])})
|
||||
assert resp.status_code == 400
|
||||
assert "reference_resolution" in resp.get_json()["error"]
|
||||
assert open(zones).read() == before
|
||||
@@ -712,8 +712,8 @@ def test_post_zones_rejects_a_non_finite_count_line(client, tmp_path, monkeypatc
|
||||
import app as app_module
|
||||
zones = _zones_file(tmp_path, _route_preset())
|
||||
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
|
||||
body = ('{"preset": {"truck_area": [[400, 257], [406, 717], [936, 719], [921, 229]],'
|
||||
' "count_line": {"x_start": 385, "x_end": 934, "y": Infinity}}}')
|
||||
body = ('{"preset": {"truck_area": [[600, 385], [609, 1076], [1404, 1078], [1381, 343]],'
|
||||
' "count_line": {"x_start": 577, "x_end": 1401, "y": Infinity}}}')
|
||||
resp = client.post("/api/zones/default", data=body, content_type="application/json")
|
||||
assert resp.status_code == 400
|
||||
assert "count_line" in resp.get_json()["error"]
|
||||
@@ -725,21 +725,21 @@ def test_post_zones_rejects_a_fractional_count_line(client, tmp_path, monkeypatc
|
||||
zones = _zones_file(tmp_path, _route_preset())
|
||||
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
|
||||
resp = client.post("/api/zones/default",
|
||||
json={"preset": _route_preset(count_line={"x_start": 385, "x_end": 1280.9, "y": 220})})
|
||||
json={"preset": _route_preset(count_line={"x_start": 577, "x_end": 1920.9, "y": 330})})
|
||||
assert resp.status_code == 400
|
||||
assert "count_line" in resp.get_json()["error"]
|
||||
|
||||
|
||||
def test_post_zones_stores_an_integral_float_count_line_as_an_int(client, tmp_path, monkeypatch):
|
||||
"""F3: 1280.0 is an integer in disguise and must be persisted as 1280."""
|
||||
"""F3: 1920.0 is an integer in disguise and must be persisted as 1920."""
|
||||
import app as app_module
|
||||
zones = _zones_file(tmp_path, _route_preset())
|
||||
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
|
||||
resp = client.post("/api/zones/default",
|
||||
json={"preset": _route_preset(count_line={"x_start": 385, "x_end": 1280.0, "y": 220})})
|
||||
json={"preset": _route_preset(count_line={"x_start": 577, "x_end": 1920.0, "y": 330})})
|
||||
assert resp.status_code == 200
|
||||
x_end = json.loads(open(zones).read())["presets"]["default"]["count_line"]["x_end"]
|
||||
assert x_end == 1280
|
||||
assert x_end == 1920
|
||||
assert isinstance(x_end, int)
|
||||
|
||||
|
||||
@@ -749,7 +749,7 @@ def test_post_zones_rejects_a_three_point_truck_area(client, tmp_path, monkeypat
|
||||
zones = _zones_file(tmp_path, _route_preset())
|
||||
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
|
||||
resp = client.post("/api/zones/default",
|
||||
json={"preset": _route_preset(truck_area=[[400, 257], [406, 717], [936, 719]])})
|
||||
json={"preset": _route_preset(truck_area=[[600, 385], [609, 1076], [1404, 1078]])})
|
||||
assert resp.status_code == 400
|
||||
assert "truck_area" in resp.get_json()["error"]
|
||||
|
||||
@@ -829,7 +829,7 @@ def test_post_zones_reset_drops_keys_that_are_not_in_the_default(client, tmp_pat
|
||||
assert resp.status_code == 200
|
||||
saved = json.loads(open(zones).read())
|
||||
assert "custom_tuning" not in saved["presets"]["default"]
|
||||
assert saved["presets"]["default"]["count_line"] == {"x_start": 423, "x_end": 939, "y": 182}
|
||||
assert saved["presets"]["default"]["count_line"] == {"x_start": 577, "x_end": 1401, "y": 215}
|
||||
assert saved["presets"]["other"] == _route_preset()
|
||||
assert saved["active_preset"] == "default"
|
||||
|
||||
@@ -867,7 +867,7 @@ def test_post_zones_reset_without_a_zones_file_is_404_and_creates_nothing(client
|
||||
# --- fix round 2: R1 reference_resolution, R2/R3 file handling, R4 mode ---
|
||||
|
||||
def test_post_zones_injects_the_analysis_space_when_the_key_is_absent(client, tmp_path, monkeypatch):
|
||||
"""R1: a preset without reference_resolution would be scaled by 1280/1920."""
|
||||
"""R1: a preset without reference_resolution defaults to native [1920, 1080] and scales cleanly."""
|
||||
import app as app_module
|
||||
from src.zone_config import build_static_roi
|
||||
zones = _zones_file(tmp_path, _route_preset())
|
||||
@@ -877,7 +877,7 @@ def test_post_zones_injects_the_analysis_space_when_the_key_is_absent(client, tm
|
||||
resp = client.post("/api/zones/fresh", json={"preset": preset})
|
||||
assert resp.status_code == 200
|
||||
stored = json.loads(open(zones).read())["presets"]["fresh"]
|
||||
assert stored["reference_resolution"] == [1280, 720]
|
||||
assert stored["reference_resolution"] == [1920, 1080]
|
||||
roi = build_static_roi(stored, 1280, 720)
|
||||
assert (roi.x1, roi.x2) == (400, 936)
|
||||
|
||||
@@ -1073,3 +1073,133 @@ def test_open_cv_calibrator_merges_geometry_and_keeps_tuning_keys():
|
||||
assert preset["palet"] == stored["palet"]
|
||||
assert preset["left_limit"] == stored["left_limit"]
|
||||
assert preset["min_valid_area"] == stored["min_valid_area"]
|
||||
|
||||
|
||||
def test_post_zones_accepts_fcp_flat_1080p_json(client, tmp_path, monkeypatch):
|
||||
"""POST /api/zones/<preset> accepts FCP's flat 1920x1080 zones.json format."""
|
||||
import app as app_module
|
||||
|
||||
zones = _zones_file(tmp_path, _route_preset())
|
||||
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
|
||||
fcp_flat = {
|
||||
"palet": [[612, 1], [1340, 1], [1340, 267], [608, 267]],
|
||||
"truck": [[600, 290], [609, 1076], [1404, 1078], [1381, 290]],
|
||||
"counting": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]],
|
||||
"line_y": 215,
|
||||
"line_x_start": 577,
|
||||
"line_x_end": 1401,
|
||||
}
|
||||
resp = client.post("/api/zones/default", json=fcp_flat)
|
||||
assert resp.status_code == 200
|
||||
saved = json.loads(open(zones).read())["presets"]["default"]
|
||||
assert saved["reference_resolution"] == [1920, 1080]
|
||||
assert saved["truck_area"] == fcp_flat["truck"]
|
||||
assert saved["counting_area"] == fcp_flat["counting"]
|
||||
assert saved["palet"] == fcp_flat["palet"]
|
||||
assert saved["count_line"] == {"x_start": 577, "x_end": 1401, "y": 215}
|
||||
|
||||
|
||||
def test_resolve_zone_auto_syncs_when_fcp_zones_updated(tmp_path, monkeypatch):
|
||||
"""When FCP's zones.json is newer, app._resolve_zone refreshes preset 'default' first."""
|
||||
import os
|
||||
import app as app_module
|
||||
|
||||
zones = _zones_file(tmp_path, _route_preset())
|
||||
fcp_zones = tmp_path / "fcp_zones.json"
|
||||
fcp_zones.write_text(json.dumps({
|
||||
"palet": [[612, 1], [1340, 1], [1340, 267], [608, 267]],
|
||||
"truck": [[600, 290], [609, 1076], [1404, 1078], [1381, 290]],
|
||||
"counting": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]],
|
||||
"line_y": 215,
|
||||
"line_x_start": 577,
|
||||
"line_x_end": 1401,
|
||||
}))
|
||||
st = os.stat(zones)
|
||||
os.utime(fcp_zones, ns=(st.st_atime_ns, st.st_mtime_ns + 1_000_000_000))
|
||||
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
|
||||
monkeypatch.setenv("FCP_ZONES_PATH", str(fcp_zones))
|
||||
|
||||
mode, roi, preset, cpoly, tpoly = app_module._resolve_zone("fixed", "")
|
||||
assert mode == "fixed"
|
||||
assert preset == "default"
|
||||
assert roi.line_y == 143
|
||||
assert roi.line_x_start == 385
|
||||
assert roi.line_x_end == 934
|
||||
assert cpoly is not None and tpoly is not None
|
||||
|
||||
|
||||
def test_cli_uses_zones_json_fixed_mode_by_default(tmp_path, monkeypatch):
|
||||
"""CLI loads zones.json fixed areas by default (and auto-syncs FCP zones)."""
|
||||
import os
|
||||
import cli as cli_mod
|
||||
from src.model_registry import ModelConfig
|
||||
|
||||
clip = tmp_path / "clip.mp4"
|
||||
_write_clip(clip)
|
||||
zones = _zones_file(tmp_path, _route_preset())
|
||||
fcp_zones = tmp_path / "fcp_zones.json"
|
||||
fcp_zones.write_text(json.dumps({
|
||||
"palet": [[612, 1], [1340, 1], [1340, 267], [608, 267]],
|
||||
"truck": [[600, 290], [609, 1076], [1404, 1078], [1381, 290]],
|
||||
"counting": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]],
|
||||
"line_y": 215,
|
||||
"line_x_start": 577,
|
||||
"line_x_end": 1401,
|
||||
}))
|
||||
st = os.stat(zones)
|
||||
os.utime(fcp_zones, ns=(st.st_atime_ns, st.st_mtime_ns + 1_000_000_000))
|
||||
monkeypatch.setenv("FCP_ZONES_PATH", str(fcp_zones))
|
||||
|
||||
model_cfg = ModelConfig(
|
||||
filename="best.pt", path=str(tmp_path / "best.pt"),
|
||||
stem="best", known_classes=["sack"],
|
||||
)
|
||||
monkeypatch.setattr(cli_mod, "scan_models", lambda d: [model_cfg])
|
||||
seen = {}
|
||||
|
||||
class _Res:
|
||||
output_path = str(tmp_path / "out.mp4")
|
||||
frame_count = 5
|
||||
loading_count = 0
|
||||
unloading_count = 0
|
||||
net_count = 0
|
||||
batch_count = 0
|
||||
duration_seconds = 0.1
|
||||
|
||||
def fake_run_pipeline(**kwargs):
|
||||
seen.update(kwargs)
|
||||
return _Res()
|
||||
|
||||
monkeypatch.setattr(cli_mod, "run_pipeline", fake_run_pipeline)
|
||||
|
||||
cli_mod.main([
|
||||
"--video", str(clip),
|
||||
"--model", "best.pt",
|
||||
"--zones-path", zones,
|
||||
"--output", str(tmp_path / "out.mp4"),
|
||||
])
|
||||
assert seen["fixed_zone"] is not None
|
||||
assert seen["fixed_zone"].line_y == 143
|
||||
assert seen["fixed_zone"].line_x_start == 385
|
||||
assert seen["counting_polygon"] is not None
|
||||
assert seen["truck_polygon"] is not None
|
||||
assert seen["freeze_roi"] is False
|
||||
|
||||
|
||||
def test_post_zones_scales_legacy_720p_preset_to_1080p(client, tmp_path, monkeypatch):
|
||||
"""POST /api/zones/<preset> accepts legacy [1280, 720] presets and stores [1920, 1080]."""
|
||||
import app as app_module
|
||||
|
||||
zones = _zones_file(tmp_path, _route_preset())
|
||||
monkeypatch.setattr(app_module, "ZONES_PATH", zones)
|
||||
legacy_preset = {
|
||||
"truck_area": [[400, 194], [406, 718], [936, 718], [920, 194]],
|
||||
"counting_area": [[382, 34], [390, 718], [946, 718], [932, 34]],
|
||||
"count_line": {"x_start": 384, "x_end": 934, "y": 144},
|
||||
"reference_resolution": [1280, 720],
|
||||
}
|
||||
resp = client.post("/api/zones/default", json={"preset": legacy_preset})
|
||||
assert resp.status_code == 200
|
||||
saved = json.loads(open(zones).read())["presets"]["default"]
|
||||
assert saved["reference_resolution"] == [1920, 1080]
|
||||
assert saved["count_line"] == {"x_start": 576, "x_end": 1401, "y": 216}
|
||||
+211
-63
@@ -9,7 +9,10 @@ from src.zone_config import (
|
||||
build_truck_polygon,
|
||||
list_zone_presets,
|
||||
load_zone_config,
|
||||
normalize_zone_preset,
|
||||
resolve_zone,
|
||||
save_zone_preset,
|
||||
sync_fcp_zones,
|
||||
validate_zone_preset,
|
||||
)
|
||||
|
||||
@@ -92,15 +95,15 @@ def _polygon_coords(poly):
|
||||
|
||||
|
||||
def test_build_counting_polygon_matches_fcp_reference_polygon():
|
||||
"""Scaled to 1280x720 the polygon equals FCP's hardcoded detection_polygon.
|
||||
"""Scaled to 1280x720 the polygon equals FCP's detection_polygon.
|
||||
|
||||
FCP predict.py:688-698 scales 1920x1080 points by 1280/1920 and
|
||||
720/1080 and truncates with int().
|
||||
FCP main predict.py:761-769 scales 1920x1080 points by 1280/1920 and
|
||||
720/1080 and rounds with int(round(...)).
|
||||
"""
|
||||
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),
|
||||
(383, 33), (391, 718), (945, 717), (931, 33), (383, 33),
|
||||
]
|
||||
|
||||
|
||||
@@ -108,7 +111,7 @@ 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),
|
||||
(383, 33), (391, 718), (945, 717), (931, 33), (383, 33),
|
||||
]
|
||||
|
||||
|
||||
@@ -154,14 +157,14 @@ FCP_TRUCK_AREA = [[600, 385], [609, 1076], [1404, 1078], [1381, 343]]
|
||||
|
||||
|
||||
def test_build_truck_polygon_matches_fcp_reference_polygon():
|
||||
"""The truck polygon is FCP's, scaled to the analysis frame."""
|
||||
"""The truck polygon is FCP's, scaled to the analysis frame with int(round(...))."""
|
||||
poly = build_truck_polygon(
|
||||
{"truck_area": FCP_TRUCK_AREA, "reference_resolution": [1920, 1080]},
|
||||
1280,
|
||||
720,
|
||||
)
|
||||
assert list(poly.exterior.coords) == [
|
||||
(400.0, 256.0), (406.0, 717.0), (936.0, 718.0), (920.0, 228.0), (400.0, 256.0)
|
||||
(400.0, 257.0), (406.0, 717.0), (936.0, 719.0), (921.0, 229.0), (400.0, 257.0)
|
||||
]
|
||||
|
||||
|
||||
@@ -178,7 +181,7 @@ def test_build_truck_polygon_at_reference_resolution_is_unscaled():
|
||||
|
||||
def test_build_truck_polygon_defaults_to_1920x1080_reference():
|
||||
poly = build_truck_polygon({"truck_area": FCP_TRUCK_AREA}, 1280, 720)
|
||||
assert list(poly.exterior.coords)[0] == (400.0, 256.0)
|
||||
assert list(poly.exterior.coords)[0] == (400.0, 257.0)
|
||||
|
||||
|
||||
def test_build_counting_polygon_none_on_a_degenerate_polygon():
|
||||
@@ -278,8 +281,8 @@ def test_build_counting_polygon_none_on_non_finite_coordinates():
|
||||
def test_build_static_roi_carries_the_count_line_x_window():
|
||||
"""The ROI carries FCP's calibrated count-line x-window.
|
||||
|
||||
FCP predict.py:701-703 scales the count line to the 1280x720 analysis
|
||||
frame: x 384...934, y 220.
|
||||
FCP main predict.py:781-783 scales the count line to the 1280x720 analysis
|
||||
frame with int(round(...)): x 385...934, y 220.
|
||||
"""
|
||||
zone = {
|
||||
"truck_area": [[600, 385], [609, 1076], [1404, 1078], [1381, 343]],
|
||||
@@ -287,9 +290,9 @@ def test_build_static_roi_carries_the_count_line_x_window():
|
||||
"reference_resolution": [1920, 1080],
|
||||
}
|
||||
roi = build_static_roi(zone, video_w=1280, video_h=720)
|
||||
assert roi.line_x_start == 384 # int(577 * 1280 / 1920)
|
||||
assert roi.line_x_end == 934 # int(1401 * 1280 / 1920)
|
||||
assert roi.line_y == 220 # int(330 * 720 / 1080)
|
||||
assert roi.line_x_start == 385 # int(round(577 * 1280 / 1920))
|
||||
assert roi.line_x_end == 934 # int(round(1401 * 1280 / 1920))
|
||||
assert roi.line_y == 220 # int(round(330 * 720 / 1080))
|
||||
|
||||
|
||||
def test_build_static_roi_without_count_line_has_no_x_window():
|
||||
@@ -303,46 +306,48 @@ def test_build_static_roi_without_count_line_has_no_x_window():
|
||||
assert roi.line_x_end is None
|
||||
|
||||
|
||||
# ── Shipped preset (FCP's calibration in the 1280x720 analysis space) ──────
|
||||
# ── Shipped preset (FCP main calibration in native 1920x1080 space) ──────
|
||||
|
||||
|
||||
def test_shipped_default_preset_matches_fcp_live_calibration():
|
||||
"""The default preset is FCP's 2026-11-11 calibration in 1280x720."""
|
||||
"""The default preset is FCP main (91d8b48) in 1920x1080, scaled to 1280x720 at runtime."""
|
||||
zone = {
|
||||
"truck_area": [[398, 152], [359, 720], [876, 720], [949, 201]],
|
||||
"counting_area": [[362, 157], [306, 720], [912, 720], [979, 169]],
|
||||
"palet": [[408, 1], [893, 1], [893, 178], [405, 178]],
|
||||
"count_line": {"x_start": 423, "x_end": 939, "y": 182},
|
||||
"reference_resolution": [1280, 720],
|
||||
"truck_area": [[600, 290], [609, 1076], [1404, 1078], [1381, 290]],
|
||||
"counting_area": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]],
|
||||
"palet": [[612, 1], [1340, 1], [1340, 267], [608, 267]],
|
||||
"count_line": {"x_start": 577, "x_end": 1401, "y": 215},
|
||||
"reference_resolution": [1920, 1080],
|
||||
}
|
||||
roi = build_static_roi(zone, video_w=1280, video_h=720)
|
||||
assert (roi.x1, roi.y1, roi.x2, roi.y2) == (359, 152, 949, 720)
|
||||
assert roi.line_y == 182
|
||||
assert roi.line_x_start == 423
|
||||
assert roi.line_x_end == 939
|
||||
assert (roi.x1, roi.y1, roi.x2, roi.y2) == (400, 193, 936, 719)
|
||||
assert roi.line_y == 143
|
||||
assert roi.line_x_start == 385
|
||||
assert roi.line_x_end == 934
|
||||
assert roi.confidence == 1.0
|
||||
assert roi.fixed is True
|
||||
|
||||
|
||||
def test_shipped_default_preset_polygons_are_usable():
|
||||
"""Both shipped polygons are valid and the counting one covers the scene."""
|
||||
"""Both shipped polygons are valid and scaled accurately to 1280x720."""
|
||||
zone = {
|
||||
"truck_area": [[398, 152], [359, 720], [876, 720], [949, 201]],
|
||||
"counting_area": [[362, 157], [306, 720], [912, 720], [979, 169]],
|
||||
"reference_resolution": [1280, 720],
|
||||
"truck_area": [[600, 290], [609, 1076], [1404, 1078], [1381, 290]],
|
||||
"counting_area": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]],
|
||||
"reference_resolution": [1920, 1080],
|
||||
}
|
||||
counting = build_counting_polygon(zone, 1280, 720)
|
||||
truck = build_truck_polygon(zone, 1280, 720)
|
||||
assert counting is not None and counting.area > 0
|
||||
assert truck is not None and truck.area > 0
|
||||
assert _polygon_coords(counting) == [(383, 33), (391, 718), (945, 717), (931, 33), (383, 33)]
|
||||
assert _polygon_coords(truck) == [(400, 193), (406, 717), (936, 719), (921, 193), (400, 193)]
|
||||
assert counting.contains(Point(600, 300))
|
||||
|
||||
|
||||
GOOD_PRESET = {
|
||||
"truck_area": [[400, 257], [406, 717], [936, 719], [921, 229]],
|
||||
"counting_area": [[383, 33], [391, 718], [945, 717], [931, 33]],
|
||||
"count_line": {"x_start": 385, "x_end": 934, "y": 220},
|
||||
"reference_resolution": [1280, 720],
|
||||
"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],
|
||||
}
|
||||
|
||||
|
||||
@@ -351,19 +356,19 @@ def test_validate_zone_preset_accepts_good_geometry():
|
||||
|
||||
|
||||
def test_validate_zone_preset_rejects_degenerate_polygon():
|
||||
bad = {**GOOD_PRESET, "truck_area": [[400, 257], [400, 257], [400, 257]]}
|
||||
bad = {**GOOD_PRESET, "truck_area": [[600, 385], [600, 385], [600, 385], [600, 385]]}
|
||||
with pytest.raises(ValueError, match="truck_area"):
|
||||
validate_zone_preset(bad)
|
||||
|
||||
|
||||
def test_validate_zone_preset_rejects_out_of_bounds_point():
|
||||
bad = {**GOOD_PRESET, "counting_area": [[383, 33], [391, 718], [945, 717], [1400, 33]]}
|
||||
bad = {**GOOD_PRESET, "counting_area": [[574, 50], [586, 1077], [1418, 1076], [1950, 50]]}
|
||||
with pytest.raises(ValueError, match="counting_area"):
|
||||
validate_zone_preset(bad)
|
||||
|
||||
|
||||
def test_validate_zone_preset_rejects_inverted_count_line():
|
||||
bad = {**GOOD_PRESET, "count_line": {"x_start": 934, "x_end": 385, "y": 220}}
|
||||
bad = {**GOOD_PRESET, "count_line": {"x_start": 1401, "x_end": 577, "y": 330}}
|
||||
with pytest.raises(ValueError, match="count_line"):
|
||||
validate_zone_preset(bad)
|
||||
|
||||
@@ -399,60 +404,63 @@ def test_repo_zones_json_ships_the_fcp_calibrations():
|
||||
cfg = load_zone_config(repo_zones)
|
||||
assert cfg["active_preset"] == "default"
|
||||
live = cfg["presets"]["default"]
|
||||
assert live["reference_resolution"] == [1280, 720]
|
||||
assert live["count_line"] == {"x_start": 423, "x_end": 939, "y": 182}
|
||||
assert live["truck_area"] == [[398, 152], [359, 720], [876, 720], [949, 201]]
|
||||
assert live["counting_area"] == [[362, 157], [306, 720], [912, 720], [979, 169]]
|
||||
assert live["palet"] == [[408, 1], [893, 1], [893, 178], [405, 178]]
|
||||
assert DEFAULT_ZONES["default"]["palet"] == [[408, 1], [893, 1], [893, 178], [405, 178]]
|
||||
assert live["reference_resolution"] == [1920, 1080]
|
||||
assert live["count_line"] == {"x_start": 577, "x_end": 1401, "y": 215}
|
||||
assert live["truck_area"] == [[600, 290], [609, 1076], [1404, 1078], [1381, 290]]
|
||||
assert live["counting_area"] == [[574, 50], [586, 1077], [1418, 1076], [1397, 50]]
|
||||
assert live["palet"] == [[612, 1], [1340, 1], [1340, 267], [608, 267]]
|
||||
assert DEFAULT_ZONES["default"]["palet"] == [[612, 1], [1340, 1], [1340, 267], [608, 267]]
|
||||
roi = build_static_roi(live, 1280, 720)
|
||||
assert (roi.x1, roi.y1, roi.x2, roi.y2) == (400, 193, 936, 719)
|
||||
assert (roi.line_x_start, roi.line_x_end, roi.line_y) == (385, 934, 143)
|
||||
legacy = cfg["presets"]["fcp-2026-10-15"]
|
||||
assert legacy["reference_resolution"] == [1280, 720]
|
||||
assert legacy["count_line"] == {"x_start": 385, "x_end": 934, "y": 220}
|
||||
assert legacy["truck_area"] == [[400, 257], [406, 717], [936, 719], [921, 229]]
|
||||
assert legacy["counting_area"] == [[383, 33], [391, 718], [945, 717], [931, 33]]
|
||||
assert legacy["palet"] == [[408, 419], [969, 420], [972, 716], [405, 714]]
|
||||
assert DEFAULT_ZONES["fcp-2026-10-15"]["palet"] == [[408, 419], [969, 420], [972, 716], [405, 714]]
|
||||
assert legacy["reference_resolution"] == [1920, 1080]
|
||||
assert legacy["count_line"] == {"x_start": 577, "x_end": 1401, "y": 330}
|
||||
assert legacy["truck_area"] == [[600, 385], [609, 1076], [1404, 1078], [1381, 343]]
|
||||
assert legacy["counting_area"] == [[574, 50], [586, 1077], [1418, 1076], [1397, 50]]
|
||||
assert legacy["palet"] == [[612, 628], [1454, 630], [1458, 1074], [608, 1071]]
|
||||
assert DEFAULT_ZONES["fcp-2026-10-15"]["palet"] == [[612, 628], [1454, 630], [1458, 1074], [608, 1071]]
|
||||
|
||||
|
||||
# --- fix round 1: F1 reference_resolution, F2/F3 count_line, F4 truck_area ---
|
||||
|
||||
def test_validate_zone_preset_rejects_a_foreign_reference_resolution():
|
||||
"""F1: a 1920x1080 preset would be scaled a second time by build_static_roi."""
|
||||
bad = {**GOOD_PRESET, "reference_resolution": [1920, 1080]}
|
||||
"""F1: raw validate_zone_preset rejects un-normalized non-1080p presets."""
|
||||
bad = {**GOOD_PRESET, "reference_resolution": [1280, 720]}
|
||||
with pytest.raises(ValueError, match="reference_resolution"):
|
||||
validate_zone_preset(bad)
|
||||
|
||||
|
||||
def test_validate_zone_preset_accepts_a_preset_without_reference_resolution():
|
||||
"""F1: the key is optional; 1280x720 is the analysis space."""
|
||||
"""F1: the key is optional; 1920x1080 is the native zone space."""
|
||||
preset = {k: v for k, v in GOOD_PRESET.items() if k != "reference_resolution"}
|
||||
assert validate_zone_preset(preset) is not None
|
||||
|
||||
|
||||
def test_validate_zone_preset_rejects_a_non_finite_count_line():
|
||||
"""F2: int(float('inf')) raises OverflowError, which used to 500."""
|
||||
bad = {**GOOD_PRESET, "count_line": {"x_start": 385, "x_end": 934, "y": float("inf")}}
|
||||
bad = {**GOOD_PRESET, "count_line": {"x_start": 577, "x_end": 1401, "y": float("inf")}}
|
||||
with pytest.raises(ValueError, match="count_line"):
|
||||
validate_zone_preset(bad)
|
||||
|
||||
|
||||
def test_validate_zone_preset_rejects_a_fractional_count_line():
|
||||
"""F3: bounds were checked on the truncated int, the raw float was stored."""
|
||||
bad = {**GOOD_PRESET, "count_line": {"x_start": 385, "x_end": 1280.9, "y": 220}}
|
||||
bad = {**GOOD_PRESET, "count_line": {"x_start": 577, "x_end": 1920.9, "y": 330}}
|
||||
with pytest.raises(ValueError, match="count_line"):
|
||||
validate_zone_preset(bad)
|
||||
|
||||
|
||||
def test_validate_zone_preset_normalizes_an_integral_float_count_line():
|
||||
"""F3: 1280.0 is an integer in disguise and is stored as 1280."""
|
||||
out = validate_zone_preset({**GOOD_PRESET, "count_line": {"x_start": 385, "x_end": 1280.0, "y": 220.0}})
|
||||
assert out["count_line"] == {"x_start": 385, "x_end": 1280, "y": 220}
|
||||
"""F3: 1920.0 is an integer in disguise and is stored as 1920."""
|
||||
out = validate_zone_preset({**GOOD_PRESET, "count_line": {"x_start": 577, "x_end": 1920.0, "y": 330.0}})
|
||||
assert out["count_line"] == {"x_start": 577, "x_end": 1920, "y": 330}
|
||||
assert all(isinstance(v, int) for v in out["count_line"].values())
|
||||
|
||||
|
||||
def test_validate_zone_preset_requires_four_truck_area_points():
|
||||
"""F4: build_static_roi needs 4 points; 3 would silently degrade the job."""
|
||||
bad = {**GOOD_PRESET, "truck_area": [[400, 257], [406, 717], [936, 719]]}
|
||||
bad = {**GOOD_PRESET, "truck_area": [[600, 385], [609, 1076], [1404, 1078]]}
|
||||
with pytest.raises(ValueError, match="truck_area"):
|
||||
validate_zone_preset(bad)
|
||||
|
||||
@@ -463,10 +471,10 @@ def test_save_zone_preset_persists_the_normalized_preset(tmp_path):
|
||||
cfg = {"presets": {"default": GOOD_PRESET}, "active_preset": "default"}
|
||||
with open(path, "w") as f:
|
||||
json.dump(cfg, f)
|
||||
save_zone_preset(path, "default", {**GOOD_PRESET, "count_line": {"x_start": 385, "x_end": 1280.0, "y": 220.0}})
|
||||
save_zone_preset(path, "default", {**GOOD_PRESET, "count_line": {"x_start": 577, "x_end": 1920.0, "y": 330.0}})
|
||||
saved = json.load(open(path))
|
||||
assert saved["presets"]["default"]["count_line"] == {"x_start": 385, "x_end": 1280, "y": 220}
|
||||
# 1280.0 == 1280 in Python, so the type is the real assertion here
|
||||
assert saved["presets"]["default"]["count_line"] == {"x_start": 577, "x_end": 1920, "y": 330}
|
||||
# 1920.0 == 1920 in Python, so the type is the real assertion here
|
||||
assert all(isinstance(v, int) for v in saved["presets"]["default"]["count_line"].values())
|
||||
|
||||
|
||||
@@ -510,14 +518,14 @@ def test_save_zone_preset_uses_a_unique_temp_file(tmp_path):
|
||||
# --- fix round 2: R1 reference_resolution injection, R2/R3 file handling, R4 mode, R5 lock ---
|
||||
|
||||
def test_validate_zone_preset_injects_the_analysis_space_when_the_key_is_absent():
|
||||
"""R1: without the key, build_static_roi would scale the zone by 1280/1920."""
|
||||
"""R1: missing reference_resolution defaults to native [1920, 1080]."""
|
||||
preset = {k: v for k, v in GOOD_PRESET.items() if k != "reference_resolution"}
|
||||
out = validate_zone_preset(preset)
|
||||
assert out["reference_resolution"] == [1280, 720]
|
||||
assert out["reference_resolution"] == [1920, 1080]
|
||||
|
||||
|
||||
def test_save_zone_preset_persists_the_injected_analysis_space(tmp_path):
|
||||
"""R1: the injected key must reach the file, so the runtime scale is 1.0."""
|
||||
"""R1: the injected key must reach the file so build_static_roi scales 1080p -> 720p."""
|
||||
path = str(tmp_path / "zones.json")
|
||||
cfg = {"presets": {}, "active_preset": "default"}
|
||||
with open(path, "w") as f:
|
||||
@@ -525,7 +533,7 @@ def test_save_zone_preset_persists_the_injected_analysis_space(tmp_path):
|
||||
preset = {k: v for k, v in GOOD_PRESET.items() if k != "reference_resolution"}
|
||||
save_zone_preset(path, "fresh", preset)
|
||||
saved = json.load(open(path))
|
||||
assert saved["presets"]["fresh"]["reference_resolution"] == [1280, 720]
|
||||
assert saved["presets"]["fresh"]["reference_resolution"] == [1920, 1080]
|
||||
roi = build_static_roi(saved["presets"]["fresh"], 1280, 720)
|
||||
assert (roi.x1, roi.x2) == (400, 936)
|
||||
|
||||
@@ -604,3 +612,143 @@ def test_save_zone_preset_serializes_concurrent_writes(tmp_path, monkeypatch):
|
||||
assert not errors
|
||||
saved = json.load(open(path))
|
||||
assert set(saved["presets"]) == {"one", "two"}
|
||||
|
||||
|
||||
# ── 1080p normalizer and FCP zones.json auto-sync ────────────────────────
|
||||
|
||||
|
||||
def test_normalize_zone_preset_converts_fcp_flat_1080p_schema():
|
||||
"""FCP main's flat zones.json maps cleanly to [1920, 1080] recounter format."""
|
||||
fcp_flat = {
|
||||
"palet": [[612, 1], [1340, 1], [1340, 267], [608, 267]],
|
||||
"truck": [[600, 290], [609, 1076], [1404, 1078], [1381, 290]],
|
||||
"counting": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]],
|
||||
"line_y": 215,
|
||||
"line_x_start": 577,
|
||||
"line_x_end": 1401,
|
||||
"left_limit": 0.27578,
|
||||
"external_stream_url": "http://192.168.192.96:8888/cam/",
|
||||
}
|
||||
out = normalize_zone_preset(fcp_flat)
|
||||
assert out["reference_resolution"] == [1920, 1080]
|
||||
assert out["palet"] == [[612, 1], [1340, 1], [1340, 267], [608, 267]]
|
||||
assert out["truck_area"] == [[600, 290], [609, 1076], [1404, 1078], [1381, 290]]
|
||||
assert out["counting_area"] == [[574, 50], [586, 1077], [1418, 1076], [1397, 50]]
|
||||
assert out["count_line"] == {"x_start": 577, "x_end": 1401, "y": 215}
|
||||
assert out["left_limit"] == 0.27578
|
||||
for transient in ("palet_area", "truck", "counting", "line_y", "line_x_start", "line_x_end"):
|
||||
assert transient not in out
|
||||
roi = build_static_roi(out, 1280, 720)
|
||||
assert (roi.line_x_start, roi.line_x_end, roi.line_y) == (385, 934, 143)
|
||||
|
||||
|
||||
def test_normalize_zone_preset_scales_720p_preset_to_1080p():
|
||||
"""Legacy 1280x720 presets are scaled up by 1.5x into [1920, 1080]."""
|
||||
legacy_720p = {
|
||||
"truck_area": [[400, 194], [406, 718], [936, 718], [920, 194]],
|
||||
"counting_area": [[382, 34], [390, 718], [946, 718], [932, 34]],
|
||||
"count_line": {"x_start": 384, "x_end": 934, "y": 144},
|
||||
"reference_resolution": [1280, 720],
|
||||
}
|
||||
out = normalize_zone_preset(legacy_720p)
|
||||
assert out["reference_resolution"] == [1920, 1080]
|
||||
assert out["truck_area"] == [[600, 291], [609, 1077], [1404, 1077], [1380, 291]]
|
||||
assert out["counting_area"] == [[573, 51], [585, 1077], [1419, 1077], [1398, 51]]
|
||||
assert out["count_line"] == {"x_start": 576, "x_end": 1401, "y": 216}
|
||||
|
||||
|
||||
def test_normalize_zone_preset_supports_two_point_counting_line():
|
||||
"""FCP's 2-point counting_line and coord_space='1280x720' normalize to [1920, 1080]."""
|
||||
flat_720 = {
|
||||
"coord_space": "1280x720",
|
||||
"truck": [[400, 200], [400, 720], [936, 720], [920, 200]],
|
||||
"counting": [[380, 40], [380, 720], [940, 720], [940, 40]],
|
||||
"counting_line": [[934, 200], [384, 180]],
|
||||
}
|
||||
out = normalize_zone_preset(flat_720)
|
||||
assert out["reference_resolution"] == [1920, 1080]
|
||||
assert out["count_line"] == {"x_start": 576, "x_end": 1401, "y": 285}
|
||||
assert "coord_space" not in out
|
||||
assert "counting_line" not in out
|
||||
|
||||
|
||||
def test_save_zone_preset_accepts_fcp_flat_payload(tmp_path):
|
||||
path = str(tmp_path / "zones.json")
|
||||
with open(path, "w") as f:
|
||||
json.dump({"presets": {"default": GOOD_PRESET}, "active_preset": "default"}, f)
|
||||
fcp_flat = {
|
||||
"palet": [[612, 1], [1340, 1], [1340, 267], [608, 267]],
|
||||
"truck": [[600, 290], [609, 1076], [1404, 1078], [1381, 290]],
|
||||
"counting": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]],
|
||||
"line_y": 215,
|
||||
"line_x_start": 577,
|
||||
"line_x_end": 1401,
|
||||
}
|
||||
save_zone_preset(path, "default", fcp_flat)
|
||||
saved = json.load(open(path))["presets"]["default"]
|
||||
assert saved["reference_resolution"] == [1920, 1080]
|
||||
assert saved["count_line"] == {"x_start": 577, "x_end": 1401, "y": 215}
|
||||
assert "truck" not in saved
|
||||
assert "line_y" not in saved
|
||||
|
||||
|
||||
def test_sync_fcp_zones_updates_default_when_fcp_file_is_newer(tmp_path):
|
||||
recounter_zones = tmp_path / "recounter_zones.json"
|
||||
fcp_zones = tmp_path / "fcp_zones.json"
|
||||
recounter_zones.write_text(json.dumps({
|
||||
"presets": {"default": GOOD_PRESET, "other": GOOD_PRESET},
|
||||
"active_preset": "default",
|
||||
}))
|
||||
fcp_zones.write_text(json.dumps({
|
||||
"palet": [[612, 1], [1340, 1], [1340, 267], [608, 267]],
|
||||
"truck": [[600, 290], [609, 1076], [1404, 1078], [1381, 290]],
|
||||
"counting": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]],
|
||||
"line_y": 250,
|
||||
"line_x_start": 590,
|
||||
"line_x_end": 1410,
|
||||
}))
|
||||
# Ensure FCP file mtime is strictly newer than recounter zones.json.
|
||||
st = recounter_zones.stat()
|
||||
os.utime(fcp_zones, ns=(st.st_atime_ns, st.st_mtime_ns + 1_000_000_000))
|
||||
|
||||
updated = sync_fcp_zones(str(recounter_zones), str(fcp_zones))
|
||||
assert updated is True
|
||||
saved = json.loads(recounter_zones.read_text())
|
||||
assert saved["presets"]["default"]["count_line"] == {"x_start": 590, "x_end": 1410, "y": 250}
|
||||
assert saved["presets"]["other"] == GOOD_PRESET
|
||||
|
||||
|
||||
def test_sync_fcp_zones_skips_when_local_zones_file_is_newer(tmp_path):
|
||||
recounter_zones = tmp_path / "recounter_zones.json"
|
||||
fcp_zones = tmp_path / "fcp_zones.json"
|
||||
fcp_zones.write_text(json.dumps({
|
||||
"truck": [[600, 290], [609, 1076], [1404, 1078], [1381, 290]],
|
||||
"counting": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]],
|
||||
"line_y": 250,
|
||||
"line_x_start": 590,
|
||||
"line_x_end": 1410,
|
||||
}))
|
||||
recounter_zones.write_text(json.dumps({
|
||||
"presets": {"default": GOOD_PRESET},
|
||||
"active_preset": "default",
|
||||
}))
|
||||
st = fcp_zones.stat()
|
||||
os.utime(recounter_zones, ns=(st.st_atime_ns, st.st_mtime_ns + 1_000_000_000))
|
||||
|
||||
updated = sync_fcp_zones(str(recounter_zones), str(fcp_zones))
|
||||
assert updated is False
|
||||
saved = json.loads(recounter_zones.read_text())
|
||||
assert saved["presets"]["default"] == GOOD_PRESET
|
||||
|
||||
|
||||
def test_resolve_zone_loads_fixed_zone_and_polygons(tmp_path):
|
||||
zones = tmp_path / "zones.json"
|
||||
zones.write_text(json.dumps({
|
||||
"presets": {"default": GOOD_PRESET},
|
||||
"active_preset": "default",
|
||||
}))
|
||||
mode, roi, preset, cpoly, tpoly = resolve_zone("fixed", "", str(zones), (1280, 720))
|
||||
assert mode == "fixed"
|
||||
assert preset == "default"
|
||||
assert roi is not None and roi.line_y == 220
|
||||
assert cpoly is not None and tpoly is not None
|
||||
+32
-5
@@ -36,6 +36,8 @@ def save_zones(config: dict, path: str):
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
||||
json.dump(config, f, indent=2)
|
||||
f.write("\n")
|
||||
if os.path.exists(path):
|
||||
os.chmod(tmp, os.stat(path).st_mode & 0o777)
|
||||
os.replace(tmp, path)
|
||||
except BaseException:
|
||||
try:
|
||||
@@ -128,9 +130,10 @@ def run(video_path: str, preset_name: str, zones_path: str):
|
||||
h, w = frame.shape[:2]
|
||||
print(f"Video: {w}x{h}")
|
||||
|
||||
# The analysis space is 1280x720: resize before the clicks are taken, so
|
||||
# the mouse coordinates match the space zones.json is authored in.
|
||||
frame = cv2.resize(frame, (1280, 720))
|
||||
# Authored zone space is 1920x1080 (scaled to 1280x720 at runtime): resize
|
||||
# the frame to 1920x1080 before taking clicks while sizing the display window
|
||||
# to fit smaller monitors.
|
||||
frame = cv2.resize(frame, (1920, 1080))
|
||||
|
||||
points = []
|
||||
all_sizes = list(ZONE_SIZES) + [LINE_POINTS]
|
||||
@@ -186,7 +189,7 @@ def run(video_path: str, preset_name: str, zones_path: str):
|
||||
xs = sorted([points[offset][0], points[offset + 1][0]])
|
||||
line_y = round((points[offset][1] + points[offset + 1][1]) / 2)
|
||||
preset["count_line"] = {"x_start": xs[0], "x_end": xs[1], "y": line_y}
|
||||
preset["reference_resolution"] = [1280, 720]
|
||||
preset["reference_resolution"] = [1920, 1080]
|
||||
|
||||
config = load_zones(zones_path)
|
||||
merge_preset(config, preset_name, preset)
|
||||
@@ -198,12 +201,36 @@ def run(video_path: str, preset_name: str, zones_path: str):
|
||||
cv2.destroyAllWindows()
|
||||
|
||||
|
||||
def import_json_preset(json_path: str, preset_name: str, zones_path: str) -> None:
|
||||
"""Import FCP flat or recounter JSON file into zones_path as [1920, 1080]."""
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
from src.zone_config import normalize_zone_preset, validate_zone_preset
|
||||
|
||||
with open(json_path, encoding="utf-8") as f:
|
||||
raw = json.load(f)
|
||||
normalized = normalize_zone_preset(raw)
|
||||
config = load_zones(zones_path)
|
||||
merge_preset(config, preset_name, normalized)
|
||||
config["presets"][preset_name] = validate_zone_preset(config["presets"][preset_name])
|
||||
if config.get("active_preset") is None:
|
||||
config["active_preset"] = preset_name
|
||||
save_zones(config, zones_path)
|
||||
print(f"Imported '{json_path}' as preset '{preset_name}' into {zones_path}")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Interactive zone calibration tool")
|
||||
parser.add_argument("video_path", help="Path to video file")
|
||||
parser.add_argument("video_path", nargs="?", default=None, help="Path to video file")
|
||||
parser.add_argument("--preset", default="calibrated", help="Preset name (default: calibrated)")
|
||||
parser.add_argument("--zones", default="zones.json", help="Path to zones.json")
|
||||
parser.add_argument("--import-json", dest="import_json", default=None,
|
||||
help="Import FCP 1080p flat or recounter preset JSON into --zones")
|
||||
args = parser.parse_args()
|
||||
if args.import_json:
|
||||
import_json_preset(args.import_json, args.preset, args.zones)
|
||||
return
|
||||
if not args.video_path:
|
||||
parser.error("video_path is required unless --import-json is specified")
|
||||
run(args.video_path, args.preset, args.zones)
|
||||
|
||||
|
||||
|
||||
+12
-12
@@ -1,11 +1,11 @@
|
||||
{
|
||||
"presets": {
|
||||
"default": {
|
||||
"truck_area": [[398, 152], [359, 720], [876, 720], [949, 201]],
|
||||
"counting_area": [[362, 157], [306, 720], [912, 720], [979, 169]],
|
||||
"palet": [[408, 1], [893, 1], [893, 178], [405, 178]],
|
||||
"count_line": {"x_start": 423, "x_end": 939, "y": 182},
|
||||
"reference_resolution": [1280, 720],
|
||||
"truck_area": [[600, 290], [609, 1076], [1404, 1078], [1381, 290]],
|
||||
"counting_area": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]],
|
||||
"palet": [[612, 1], [1340, 1], [1340, 267], [608, 267]],
|
||||
"count_line": {"x_start": 577, "x_end": 1401, "y": 215},
|
||||
"reference_resolution": [1920, 1080],
|
||||
"left_limit": 0.27578,
|
||||
"right_limit": 0.72578,
|
||||
"duplicate_circle_radius": 30,
|
||||
@@ -16,14 +16,14 @@
|
||||
"inference_stride": 2,
|
||||
"confirm_delay_sec": 0.5,
|
||||
"exit_confirm_delay_sec": 6.0,
|
||||
"description": "FCP 95c031b calibration (2026-11-11), 1280x720 analysis space"
|
||||
"description": "FCP main (91d8b48) calibration, native 1920x1080 (scaled to 1280x720 at runtime)"
|
||||
},
|
||||
"fcp-2026-10-15": {
|
||||
"truck_area": [[400, 257], [406, 717], [936, 719], [921, 229]],
|
||||
"counting_area": [[383, 33], [391, 718], [945, 717], [931, 33]],
|
||||
"palet": [[408, 419], [969, 420], [972, 716], [405, 714]],
|
||||
"count_line": {"x_start": 385, "x_end": 934, "y": 220},
|
||||
"reference_resolution": [1280, 720],
|
||||
"truck_area": [[600, 385], [609, 1076], [1404, 1078], [1381, 343]],
|
||||
"counting_area": [[574, 50], [586, 1077], [1418, 1076], [1397, 50]],
|
||||
"palet": [[612, 628], [1454, 630], [1458, 1074], [608, 1071]],
|
||||
"count_line": {"x_start": 577, "x_end": 1401, "y": 330},
|
||||
"reference_resolution": [1920, 1080],
|
||||
"left_limit": 0.27578,
|
||||
"right_limit": 0.72578,
|
||||
"duplicate_circle_radius": 30,
|
||||
@@ -34,7 +34,7 @@
|
||||
"inference_stride": 2,
|
||||
"confirm_delay_sec": 0.5,
|
||||
"exit_confirm_delay_sec": 6.0,
|
||||
"description": "FCP 7beb820 calibration (pre-2026-11-11 recalibration), 1280x720 analysis space"
|
||||
"description": "FCP 7beb820 calibration (pre-2026-11-11 recalibration), native 1920x1080"
|
||||
}
|
||||
},
|
||||
"active_preset": "default"
|
||||
|
||||
Reference in new issue
Block a user