File size: 8,163 Bytes
166c438
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
"""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("Use a measured scene calibration with template_only=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("rotation_rad must be 0 for the supplied road-aligned coordinate conversion")
        ratios = []
        self.references = []
        for segment in config["reference_segments"]:
            a = np.asarray(segment["point_a"], dtype=float)
            b = np.asarray(segment["point_b"], dtype=float)
            if a.shape != (2,) or b.shape != (2,) or not np.isfinite([a, b]).all():
                raise ValueError("Reference endpoints must each contain two finite pixel coordinates")
            distance = np.linalg.norm(a - b)
            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)
            self.references.append({"name": segment.get("name", ""), "pixel_distance": float(distance),
                                    "real_distance_m": real, "scale_m_per_px": float(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]
        self.diagnostics = {"source": source, "master_source": config["master_source"],
                            "scale_m_per_px": self.scale, "references": self.references,
                            "control_points": [], "validation_points": [],
                            "review_blocked": bool(entry.get("review_blocked", False))}
        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")
            if any(np.linalg.matrix_rank(np.column_stack([p, np.ones(len(p))])) < 3 for p in (src, dst)):
                raise ValueError("Control points must not all be collinear")
            cv2.setRNGSeed(0)
            self.homography, mask = cv2.findHomography(src, dst, cv2.RANSAC, 3.0)
            if self.homography is None or mask is None or mask.sum() < 4:
                raise ValueError("Homography estimation failed")
            if not np.isfinite(self.homography).all() or np.linalg.matrix_rank(self.homography) != 3:
                raise ValueError("Non-finite or singular homography")
            predicted = cv2.perspectiveTransform(src.reshape(-1, 1, 2), self.homography).reshape(-1, 2)
            errors = np.linalg.norm(predicted - dst, axis=1)
            self.diagnostics["inlier_ratio"] = float(mask.mean())
            self.diagnostics["control_points"] = [
                {"point": int(i + 1), "source_px": a.tolist(), "master_px": b.tolist(),
                 "predicted_master_px": c.tolist(), "error_px": float(e),
                 "error_m": float(e * self.scale), "inlier": bool(m)}
                for i, (a, b, c, e, m) in enumerate(zip(src, dst, predicted, errors, mask.ravel()))]
            self.diagnostics["control_rmse_px"] = float(np.sqrt(np.mean(errors ** 2)))
        print(f"Source={source}; master={config['master_source']}; scale={self.scale:.10g} m/px")
        self.diagnostics["homography"] = self.homography.tolist()
        validation_src, validation_master = entry.get("validation_src"), entry.get("validation_master")
        if (validation_src is None) != (validation_master is None):
            raise ValueError("Supply both validation_src and validation_master, or leave both null")
        if validation_src is not None:
            points = np.asarray(validation_src, dtype=float)
            expected_points = np.asarray(validation_master, dtype=float)
            if points.ndim != 2 or points.shape[1:] != (2,) or len(points) == 0 or points.shape != expected_points.shape:
                raise ValueError("Independent validation points must be nonempty matched Nx2 arrays")
            check = self.transform(points)
            expected = (expected_points - 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)
            self.diagnostics["validation_rmse_m"] = float(np.sqrt(np.mean(error ** 2)))
            self.diagnostics["validation_max_m"] = float(error.max())
            self.diagnostics["validation_points"] = [
                {"point": i + 1, "source_px": a.tolist(), "master_px": b.tolist(), "error_m": float(e)}
                for i, (a, b, e) in enumerate(zip(points, expected_points, error))]
            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"Selected source calibration is disabled by its configuration: {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()