kinejing-open-source / projects /spatial-0 /scripts /prepare_fusion_sequence.py
zoah111's picture
Publish reviewed KineJing technical release (dataset, batch 13/16)
6da4e64 verified
Raw History Blame Contribute Delete
5 kB
"""Create a private, provenance-labelled observed+generated fusion experiment.
Generated frames are never evaluation ground truth. Does not publish anything.
"""
import argparse
import hashlib
import json
from pathlib import Path
import numpy as np
from PIL import Image
def digest(path):
with path.open("rb") as stream:
return hashlib.file_digest(stream, "sha256").hexdigest()
def validate_bundle(bundle, count):
if bundle.get("pose_convention") != "camera_to_world":
raise ValueError("Expected C2W cameras")
if bundle.get("frame_count") != count or bundle.get("provenance") != ["observed"] + ["generated"]*(count-1):
raise ValueError("Expected exactly one observed prefix, followed by generated views")
poses, intrs = np.asarray(bundle["camera_poses"]), np.asarray(bundle["camera_intrinsics"])
if poses.shape != (count, 4, 4) or intrs.shape != (count, 3, 3):
raise ValueError("Invalid camera array shapes")
if not np.isfinite(poses).all() or not np.isfinite(intrs).all():
raise ValueError("Nonfinite cameras")
if not np.allclose(poses[:, 3], [0, 0, 0, 1], atol=1e-5):
raise ValueError("Invalid homogeneous cameras")
return poses, intrs
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("observed", type=Path)
parser.add_argument("completion", type=Path)
parser.add_argument("output", type=Path)
args = parser.parse_args()
run_path, bundle_path = args.completion/"run.json", args.completion/"cameras.json"
run = json.loads(run_path.read_text(encoding="utf-8"))
if run.get("status") != "completed" or not run.get("trajectory_anchor_normalized"):
raise ValueError("Require completed, anchor-normalized generation")
checksum = digest(args.observed)
if checksum != run["input_sha256"]:
raise ValueError("Completion did not use this observed reconstruction")
files = sorted(args.completion.glob("frame-*.png"))
if len(files) < 2:
raise ValueError("No generated frames")
pose_gen, intr_gen = validate_bundle(json.loads(bundle_path.read_text(encoding="utf-8")), len(files))
tracked = [args.observed, run_path, bundle_path, *files]
fingerprints = {str(p.resolve()): digest(p) for p in tracked}
with np.load(args.observed, allow_pickle=False) as data:
images = data["image"].copy()
intrs = data["intrinsics"].copy()
w2cs = np.repeat(np.eye(4)[None], len(images), axis=0)
w2cs[:, :3] = data["extrinsics"]
poses = np.linalg.inv(w2cs)
anchor = run["anchor"]
if not 0 <= anchor < len(images):
raise ValueError("Invalid source anchor")
if not np.allclose(pose_gen[0], poses[anchor], atol=2e-4) or not np.allclose(intr_gen[0], intrs[anchor], atol=2e-3):
raise ValueError("Source anchor camera does not match reconstruction")
with Image.open(files[0]) as image:
source = np.asarray(image.convert("RGB"))
if source.shape != images[anchor].shape or np.abs(source.astype(float)-images[anchor]).max() > 2:
raise ValueError("Observed prefix differs from the source image")
args.output.mkdir(parents=True, exist_ok=False)
frames_dir = args.output/"images"
frames_dir.mkdir()
records = []
for index in range(len(images)+len(files)-1):
name = f"frame-{index:04d}.png"
target = frames_dir/name
is_observed = index < len(images)
if is_observed:
Image.fromarray(images[index]).save(target)
source_ref = {"reconstruction_index": index}
else:
generated_index = index-len(images)+1
with Image.open(files[generated_index]) as image:
if image.size != (images.shape[2], images.shape[1]):
raise ValueError("Generated and observed image sizes disagree")
image.convert("RGB").save(target)
source_ref = {"generation_index": generated_index}
records.append({"name": name, "sha256": digest(target),
"provenance": "observed" if is_observed else "generated", **source_ref})
if any(digest(Path(p)) != checksum for p, checksum in fingerprints.items()):
raise RuntimeError("Source changed during fusion preparation")
np.savez_compressed(args.output/"camera-priors.npz",
frame_names=np.asarray([r["name"] for r in records]),
image_sha256=np.asarray([r["sha256"] for r in records]),
c2w=np.concatenate([poses, pose_gen[1:]]).astype(np.float32),
intrinsics=np.concatenate([intrs, intr_gen[1:]]).astype(np.float32))
(args.output/"manifest.json").write_text(json.dumps({
"status": "prepared", "inputs": fingerprints, "frames": records,
"caveat": "Experimental fusion; generated views are hypotheses, never ground truth."
}, indent=2), encoding="utf-8")
print(f"Prepared {len(images)} observed + {len(files)-1} generated views")
if __name__ == "__main__":
main()