Files

239 lines
8.1 KiB
Python
Executable File

#!/usr/bin/env python3
"""Interactive zone calibration tool.
Click 4 points for truck area, 4 for counting area, 2 for count line.
Keys: s=save, c=clear/restart, q/ESC=quit.
"""
import argparse
import json
import os
import shutil
import sys
import tempfile
import cv2
import numpy as np
ZONE_KEYS = ["truck_area", "counting_area"]
ZONE_SIZES = [4, 4]
LINE_POINTS = 2
def load_zones(path: str) -> dict:
try:
with open(path) as f:
return json.load(f)
except FileNotFoundError:
return {"presets": {}, "active_preset": None}
def save_zones(config: dict, path: str):
if os.path.exists(path):
shutil.copy2(path, path + ".bak")
fd, tmp = tempfile.mkstemp(prefix=".zones.", suffix=".tmp",
dir=os.path.dirname(path) or ".")
try:
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:
os.remove(tmp)
except OSError:
pass
raise
def merge_preset(config: dict, preset_name: str, preset: dict) -> None:
"""Merge the measured geometry into a preset, keeping its tuning keys.
Same contract as the web editor's server-side merge
(src/zone_config.py save_zone_preset): only the geometry this tool
measured is overwritten, so calibrating a shipped preset does not drop
its palet or tuning knobs.
"""
presets = config.setdefault("presets", {})
merged = dict(presets.get(preset_name, {}))
merged.update(preset)
presets[preset_name] = merged
def draw_state(frame, points, current_zone, zone_idx, zone_sizes, zone_names):
vis = frame.copy()
colors = [(0, 255, 0), (255, 0, 0), (0, 0, 255)]
total_zones = len(zone_names)
all_zones = []
offset = 0
for i, sz in enumerate(zone_sizes):
all_zones.append(points[offset : offset + sz])
offset += sz
if current_zone < total_zones:
all_zones.append(points[offset:])
for i, zone_pts in enumerate(all_zones):
if not zone_pts:
continue
color = colors[i % len(colors)]
if i < total_zones:
name = zone_names[i]
need = zone_sizes[i]
else:
name = "count_line"
need = LINE_POINTS
if len(zone_pts) > 1:
pts = np.array(zone_pts, dtype=np.int32)
if len(zone_pts) >= 3 and i < total_zones:
cv2.polylines(vis, [pts], True, color, 2)
else:
cv2.polylines(vis, [pts], False, color, 2)
for j, pt in enumerate(zone_pts):
cv2.circle(vis, pt, 6, color, -1)
cv2.putText(vis, str(j + 1), (pt[0] + 8, pt[1] - 8),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
if i == current_zone:
status = f"[{name}] {len(zone_pts)}/{need} pts"
else:
status = f"{name}: {len(zone_pts)}/{need}"
y_pos = 30 + i * 25
cv2.putText(vis, status, (10, y_pos),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)
if current_zone < total_zones:
cur_name = zone_names[current_zone]
else:
cur_name = "count_line"
hint = f"Click {cur_name} point. s=save c=clear q=quit"
cv2.putText(vis, hint, (10, vis.shape[0] - 20),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)
return vis
def run(video_path: str, preset_name: str, zones_path: str):
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
print(f"Error: cannot open {video_path}")
sys.exit(1)
ret, frame = cap.read()
cap.release()
if not ret:
print("Error: cannot read frame from video")
sys.exit(1)
h, w = frame.shape[:2]
print(f"Video: {w}x{h}")
# 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]
all_names = list(ZONE_KEYS) + ["count_line"]
zone_idx = 0
def mouse_cb(event, x, y, flags, param):
nonlocal points, zone_idx
if event == cv2.EVENT_LBUTTONDOWN:
total = sum(all_sizes)
if len(points) < total:
points.append((x, y))
cur_total = sum(all_sizes[:zone_idx])
if zone_idx < len(all_sizes):
cur_total += len(points) - sum(all_sizes[:zone_idx])
if cur_total >= all_sizes[zone_idx] and zone_idx < len(all_sizes) - 1:
zone_idx += 1
win = "Calibrate Zone"
cv2.namedWindow(win, cv2.WINDOW_NORMAL)
cv2.resizeWindow(win, min(w, 1280), min(h, 720))
cv2.setMouseCallback(win, mouse_cb)
while True:
vis = draw_state(frame, points, zone_idx, all_sizes, all_names)
cv2.imshow(win, vis)
key = cv2.waitKey(30) & 0xFF
if key in (ord("q"), 27):
cv2.destroyAllWindows()
print("Quit.")
return
if key == ord("c"):
points.clear()
zone_idx = 0
print("Cleared.")
if key == ord("s"):
total_needed = sum(all_sizes)
if len(points) < total_needed:
print(f"Need {total_needed} points, have {len(points)}. Continue clicking.")
continue
offset = 0
preset = {}
for i, sz in enumerate(ZONE_SIZES):
preset[ZONE_KEYS[i]] = [list(p) for p in points[offset : offset + sz]]
offset += sz
# FCP count-line semantics: the line stays horizontal at the
# mean y of its two endpoints, and the x endpoints are sorted.
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"] = [1920, 1080]
config = load_zones(zones_path)
merge_preset(config, preset_name, preset)
save_zones(config, zones_path)
print(f"Saved preset '{preset_name}' to {zones_path}")
cv2.destroyAllWindows()
return
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", 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)
if __name__ == "__main__":
main()