"""Source pixels -> master frame -> road-aligned local metric coordinates.""" import json import cv2 import numpy as np from _common import numeric, parser, read_csv, save_csv, unique class Calibration: def __init__(self, config, source): if config.get("template_only", False): raise ValueError("Fill the calibration template before setting template_only to false") self.origin = np.asarray(config["origin_px"], dtype=float) if self.origin.shape != (2,) or not np.isfinite(self.origin).all(): raise ValueError("origin_px must contain two finite coordinates") if config.get("rotation_rad", 0) != 0: raise ValueError("This release implements the supplied no-rotation workflow") ratios = [] for segment in config["reference_segments"]: distance = np.linalg.norm(np.asarray(segment["point_a"], dtype=float) - np.asarray(segment["point_b"], dtype=float)) real = float(segment["real_distance_m"]) if not np.isfinite([distance, real]).all() or min(distance, real) <= 0: raise ValueError("Reference distances must be finite and positive") ratios.append(real / distance) if not ratios: raise ValueError("At least one measured master-frame reference is required") self.scale = float(np.mean(ratios)) self.source = source if config["master_source"] not in config["sources"] or source not in config["sources"]: raise ValueError("master_source and --source must identify entries in sources") self.master = source == config["master_source"] entry = config["sources"][source] if self.master: self.homography = np.eye(3) else: src = np.asarray(entry["src_points"], dtype=np.float32) dst = np.asarray(entry["master_points"], dtype=np.float32) if src.shape != dst.shape or src.ndim != 2 or src.shape[1] != 2 or len(src) < 4: raise ValueError("At least four corresponding 2D control points are required") if not np.isfinite(src).all() or not np.isfinite(dst).all(): raise ValueError("Non-finite control points") cv2.setRNGSeed(0) self.homography, mask = cv2.findHomography(src, dst, cv2.RANSAC, 3.0) if self.homography is None or mask.sum() < 4: raise ValueError("Homography estimation failed") print(f"Source={source}; master={config['master_source']}; scale={self.scale:.10g} m/px") if entry.get("validation_src") is not None: check = self.transform(entry["validation_src"]) expected = (np.asarray(entry["validation_master"], dtype=float) - self.origin) * [self.scale, -self.scale] if check.shape != expected.shape or not np.isfinite(expected).all(): raise ValueError("Invalid independent validation points") error = np.linalg.norm(check - expected, axis=1) print(f"Independent checkpoints={len(error)}; RMSE={np.sqrt(np.mean(error ** 2)):.6f} m; max={error.max():.6f} m") if entry.get("review_blocked", False): raise ValueError(f"Calibration blocked pending author review: {entry.get('review_note', source)}") def transform(self, points): points = np.asarray(points, dtype=float).reshape(-1, 2) if not np.isfinite(points).all(): raise ValueError("Non-finite pixel coordinates") if not self.master: denominator = points @ self.homography[2, :2] + self.homography[2, 2] if np.any(np.abs(denominator) < 1e-10): raise ValueError("Points lie on the homography horizon") points = cv2.perspectiveTransform(points.astype(np.float32).reshape(-1, 1, 2), self.homography).reshape(-1, 2).astype(float) result = (points - self.origin) * [self.scale, -self.scale] if not np.isfinite(result).all(): raise ValueError("Non-finite transformed coordinates") return result def load_calibration(path, source): with open(path, encoding="utf-8") as handle: return Calibration(json.load(handle), source) def main(): p = parser(__doc__) p.add_argument("--input", required=True, help="Raw pixel trajectory CSV") p.add_argument("--calibration", required=True, help="Scene calibration JSON") p.add_argument("--source", required=True, help="Source video key in the calibration JSON") p.add_argument("--output", required=True, help="New metric trajectory CSV") args = p.parse_args() df = read_csv(args.input) numeric(df, ["Frame", "Vehicle_ID"], integer=True) numeric(df, ["x_center_px", "y_center_px"]) unique(df, ["Frame", "Vehicle_ID"]) if "Source_ID" in df and not df.Source_ID.eq(args.source).all(): raise ValueError("Process one source at a time; Source_ID disagrees with --source") cal = load_calibration(args.calibration, args.source) df[["x_center", "y_center"]] = cal.transform(df[["x_center_px", "y_center_px"]]) df["Source_ID"] = args.source save_csv(df, args.output) if __name__ == "__main__": main()