File size: 8,903 Bytes
6da4e64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
#!/usr/bin/env python3
"""Fail-closed geometric reprojection gate for generated Spatial-0 views.

The gate back-projects pixels from one observed anchor using observed depth, projects
them into each generated camera, resolves visibility with a z-buffer, and measures
photometric agreement only on the observed-overlap support. Generated pixels never
become evidence; passing only makes a frame eligible for a controlled fusion ablation.
"""

from __future__ import annotations

import argparse
import glob
import hashlib
import json
from pathlib import Path

import cv2
import numpy as np


def sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as source:
        for block in iter(lambda: source.read(1024 * 1024), b""):
            digest.update(block)
    return digest.hexdigest()


def load_depth(path: Path, key: str) -> np.ndarray:
    if path.suffix.lower() == ".npy":
        depth = np.load(path)
    elif path.suffix.lower() == ".npz":
        archive = np.load(path)
        if key not in archive:
            raise SystemExit(f"Depth key {key!r} not found; available: {archive.files}")
        depth = archive[key]
    else:
        depth = cv2.imread(str(path), cv2.IMREAD_UNCHANGED)
        if depth is None:
            raise SystemExit(f"Could not read depth: {path}")
    depth = np.asarray(depth, dtype=np.float64).squeeze()
    if depth.ndim != 2:
        raise SystemExit(f"Expected HxW depth, received {depth.shape}")
    return depth


def load_rgb(path: Path) -> np.ndarray:
    image = cv2.imread(str(path), cv2.IMREAD_COLOR)
    if image is None:
        raise SystemExit(f"Could not read image: {path}")
    return cv2.cvtColor(image, cv2.COLOR_BGR2RGB)


def evaluate_view(
    anchor: np.ndarray,
    depth: np.ndarray,
    target: np.ndarray,
    anchor_k: np.ndarray,
    target_k: np.ndarray,
    anchor_c2w: np.ndarray,
    target_c2w: np.ndarray,
    stride: int,
    depth_scale: float = 1.0,
) -> dict[str, float | int]:
    if not np.isfinite(depth_scale) or depth_scale <= 0:
        raise ValueError("depth_scale must be finite and positive")
    if stride < 1:
        raise ValueError("stride must be positive")
    height, width = anchor.shape[:2]
    if depth.shape != (height, width):
        depth = cv2.resize(depth, (width, height), interpolation=cv2.INTER_NEAREST)
    target_h, target_w = target.shape[:2]
    # WorldStereo exports K in its final pixel space (normally 1920x1080), while
    # observed depth can be stored at a smaller resolution. Principal point is
    # centered by the exporter, so 2*cx and 2*cy recover that reference raster.
    reference_w = 2.0 * float(anchor_k[0, 2])
    reference_h = 2.0 * float(anchor_k[1, 2])
    if reference_w <= 0 or reference_h <= 0:
        raise ValueError("Camera bundle has invalid principal point")
    anchor_k = anchor_k.copy()
    anchor_k[0] *= width / reference_w
    anchor_k[1] *= height / reference_h
    target_k = target_k.copy()
    target_k[0] *= target_w / reference_w
    target_k[1] *= target_h / reference_h

    yy, xx = np.mgrid[0:height:stride, 0:width:stride]
    zz = depth[yy, xx] * depth_scale
    valid_depth = np.isfinite(zz) & (zz > 0)
    xx, yy, zz = xx[valid_depth], yy[valid_depth], zz[valid_depth]
    if zz.size == 0:
        return {"sample_count": 0, "overlap_count": 0, "overlap_ratio": 0.0,
                "median_mae_0_255": 255.0, "p90_mae_0_255": 255.0}

    rays = np.linalg.inv(anchor_k) @ np.vstack((xx, yy, np.ones_like(xx)))
    points_anchor = rays * zz
    points_world = anchor_c2w[:3, :3] @ points_anchor + anchor_c2w[:3, 3:4]
    target_w2c = np.linalg.inv(target_c2w)
    points_target = target_w2c[:3, :3] @ points_world + target_w2c[:3, 3:4]
    positive = points_target[2] > 1e-6
    projected = target_k @ points_target[:, positive]
    uu = np.rint(projected[0] / projected[2]).astype(np.int64)
    vv = np.rint(projected[1] / projected[2]).astype(np.int64)
    zz_target = points_target[2, positive]
    source_x, source_y = xx[positive], yy[positive]
    inside = (uu >= 0) & (uu < target_w) & (vv >= 0) & (vv < target_h)
    uu, vv, zz_target = uu[inside], vv[inside], zz_target[inside]
    source_x, source_y = source_x[inside], source_y[inside]

    if uu.size:
        flat = vv * target_w + uu
        order = np.lexsort((zz_target, flat))
        flat_ordered = flat[order]
        visible = order[np.r_[True, flat_ordered[1:] != flat_ordered[:-1]]]
        uu, vv = uu[visible], vv[visible]
        source_x, source_y = source_x[visible], source_y[visible]
    errors = np.abs(anchor[source_y, source_x].astype(np.float32) - target[vv, uu].astype(np.float32))
    per_pixel = errors.mean(axis=1) if errors.size else np.asarray([], dtype=np.float32)
    sample_count = int(zz.size)
    overlap_count = int(per_pixel.size)
    return {
        "sample_count": sample_count,
        "overlap_count": overlap_count,
        "overlap_ratio": round(overlap_count / sample_count, 6),
        "median_mae_0_255": round(float(np.median(per_pixel)), 6) if overlap_count else 255.0,
        "p90_mae_0_255": round(float(np.percentile(per_pixel, 90)), 6) if overlap_count else 255.0,
    }


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("anchor_image", type=Path)
    parser.add_argument("anchor_depth", type=Path)
    parser.add_argument("camera_bundle", type=Path)
    parser.add_argument("generated_glob")
    parser.add_argument("output_json", type=Path)
    parser.add_argument("--depth-key", default="depth")
    parser.add_argument("--stride", type=int, default=4)
    parser.add_argument("--min-overlap", type=float, default=0.15)
    parser.add_argument("--max-median-mae", type=float, default=32.0)
    parser.add_argument("--max-p90-mae", type=float, default=80.0)
    parser.add_argument("--depth-scale", type=float, default=1.0)
    parser.add_argument("--depth-scale-source", default="identity")
    args = parser.parse_args()
    if args.stride < 1:
        raise SystemExit("stride must be positive")
    if not np.isfinite(args.depth_scale) or args.depth_scale <= 0:
        raise SystemExit("depth-scale must be finite and positive")

    bundle = json.loads(args.camera_bundle.read_text(encoding="utf-8"))
    if bundle.get("schema") != "kineworld.camera-bundle.v1":
        raise SystemExit("Unsupported camera bundle schema")
    paths = [Path(item).resolve() for item in sorted(glob.glob(args.generated_glob))]
    if len(paths) != bundle["frame_count"]:
        raise SystemExit("Frame and camera counts differ")
    anchor = load_rgb(args.anchor_image)
    depth = load_depth(args.anchor_depth, args.depth_key)
    anchor_k = np.asarray(bundle["camera_intrinsics"][0], dtype=np.float64)
    anchor_c2w = np.asarray(bundle["camera_poses"][0], dtype=np.float64)

    frames = []
    for index in range(1, bundle["frame_count"]):
        metrics = evaluate_view(
            anchor, depth, load_rgb(paths[index]), anchor_k,
            np.asarray(bundle["camera_intrinsics"][index], dtype=np.float64),
            anchor_c2w, np.asarray(bundle["camera_poses"][index], dtype=np.float64), args.stride,
            args.depth_scale,
        )
        passed = (
            metrics["overlap_ratio"] >= args.min_overlap
            and metrics["median_mae_0_255"] <= args.max_median_mae
            and metrics["p90_mae_0_255"] <= args.max_p90_mae
        )
        frames.append({"index": index, "file": paths[index].name, "sha256": sha256(paths[index]),
                       **metrics, "decision": "ACCEPT_CANDIDATE" if passed else "REJECT"})

    accepted = [item["index"] for item in frames if item["decision"] == "ACCEPT_CANDIDATE"]
    record = {
        "schema": "kineworld.geometric-reprojection-gate.v1",
        "method": "observed anchor depth backprojection, target-camera z-buffer, observed-overlap RGB residual",
        "thresholds": {"min_overlap": args.min_overlap, "max_median_mae_0_255": args.max_median_mae,
                       "max_p90_mae_0_255": args.max_p90_mae, "stride": args.stride},
        "scale_registration": {"depth_scale": args.depth_scale, "source": args.depth_scale_source},
        "inputs": {"anchor_sha256": sha256(args.anchor_image), "depth_sha256": sha256(args.anchor_depth),
                   "camera_bundle_sha256": sha256(args.camera_bundle)},
        "frames": frames,
        "accepted_generated_indices": accepted,
        "decision": "PASS_SOME_CANDIDATES" if accepted else "FAIL_CLOSED",
        "boundary": "Passing permits fusion ablation only; it does not make generated pixels observed evidence.",
    }
    args.output_json.parent.mkdir(parents=True, exist_ok=True)
    args.output_json.write_text(json.dumps(record, indent=2) + "\n", encoding="utf-8")
    print(json.dumps({"decision": record["decision"], "accepted_generated_indices": accepted}, indent=2))


if __name__ == "__main__":
    main()