Download projects/spatial-0/scripts/render_frozen_brush.py from KineJIng/kinejing-open-source: direct link, hf CLI and curl.
- Browser
- Download file 7.32 kB
-
https://huggingface.co/datasets/KineJIng/kinejing-open-source/resolve/main/projects/spatial-0/scripts/render_frozen_brush.py
- Command line
-
hf download hf://datasets/KineJIng/kinejing-open-source/projects/spatial-0/scripts/render_frozen_brush.py
-
curl -L -o render_frozen_brush.py https://huggingface.co/datasets/KineJIng/kinejing-open-source/resolve/main/projects/spatial-0/scripts/render_frozen_brush.py
7.32 kB
| """Render saved splats through Brush's existing evaluation renderer. | |
| The binary lacks a render-only command. Run one no-op optimization step on a | |
| COPY: positive f64 mean/scale rates underflow to zero in f32; other rates are | |
| zero, noise is zero and iteration zero never refines. Verify all saved fields | |
| against the copied input before accepting results. Original asset is untouched. | |
| No accuracy claims: placeholder reference images only allocate render sizes. | |
| """ | |
| import argparse | |
| import hashlib | |
| import json | |
| from pathlib import Path | |
| import shutil | |
| import subprocess | |
| import numpy as np | |
| from PIL import Image | |
| from plyfile import PlyData | |
| ROOT = Path(__file__).resolve().parents[1] | |
| def digest(path): | |
| with path.open("rb") as stream: | |
| return hashlib.file_digest(stream, "sha256").hexdigest() | |
| def compare_splats(source, target): | |
| a, b = PlyData.read(source)["vertex"].data, PlyData.read(target)["vertex"].data | |
| names = a.dtype.names | |
| if len(a) != len(b) or set(names) != set(b.dtype.names): | |
| raise ValueError("Frozen render changed point count or fields") | |
| differences = {} | |
| for name in names: | |
| left, right = a[name].astype(float), b[name].astype(float) | |
| if not np.isfinite(left).all() or not np.isfinite(right).all(): | |
| raise ValueError(f"Nonfinite field: {name}") | |
| maximum = float(np.max(np.abs(left-right))) | |
| differences[name] = maximum | |
| # Native serializer renormalizes quaternions on export. | |
| tolerance = 2e-6 if name.startswith("rot_") else 0. | |
| if maximum > tolerance: | |
| raise ValueError(f"Frozen render changed {name}: max difference {maximum}") | |
| return differences | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("ply", type=Path) | |
| parser.add_argument("cameras", type=Path, help="NPZ with c2w/intrinsics; all views rendered") | |
| parser.add_argument("output", type=Path) | |
| parser.add_argument("--width", type=int, required=True) | |
| parser.add_argument("--height", type=int, required=True) | |
| parser.add_argument("--white-alpha", action="store_true", help="White constant SH gives opacity on black background") | |
| parser.add_argument("--ascii-input", action="store_true", help="Diagnostic alternative for binary PLY reader failures") | |
| args = parser.parse_args() | |
| args.ply, args.cameras, args.output = args.ply.resolve(), args.cameras.resolve(), args.output.resolve() | |
| if not 16 <= args.width <= 2048 or not 16 <= args.height <= 2048: | |
| parser.error("Render dimensions must be 16..2048") | |
| with np.load(args.cameras, allow_pickle=False) as cameras: | |
| poses, intrs = cameras["c2w"].copy(), cameras["intrinsics"].copy() | |
| if poses.ndim != 3 or poses.shape[1:] != (4, 4) or intrs.shape != (len(poses), 3, 3): | |
| raise ValueError("Invalid camera arrays") | |
| if not len(poses) or not np.isfinite(poses).all() or not np.isfinite(intrs).all(): | |
| raise ValueError("Empty or nonfinite cameras") | |
| args.output.mkdir(parents=True, exist_ok=False) | |
| dataset = args.output / "dataset" | |
| dataset.mkdir() | |
| scene = dataset/"scene.ply" | |
| source_hash = digest(args.ply) | |
| camera_hash = digest(args.cameras) | |
| shutil.copy2(args.ply, scene) | |
| ply = PlyData.read(scene, mmap=False) | |
| vertex = ply["vertex"].data | |
| rest_count = len([name for name in vertex.dtype.names if name.startswith("f_rest_")]) | |
| degree = int(np.sqrt(rest_count/3+1)-1) | |
| if 3*((degree+1)**2-1) != rest_count: | |
| raise ValueError("Unsupported SH layout") | |
| if args.white_alpha: | |
| for name in vertex.dtype.names: | |
| if name.startswith("f_dc_"): | |
| vertex[name] = .5/0.28209479177387814 | |
| elif name.startswith("f_rest_"): | |
| vertex[name] = 0 | |
| ply.write(scene) | |
| if args.ascii_input: | |
| from plyfile import PlyElement | |
| PlyData([PlyElement.describe(vertex.copy(), "vertex")], text=True).write(scene) | |
| # Brush's image-header probe uses read_exact on a growing buffer and can | |
| # reject tiny, highly compressed constant PNGs. Store the same pixels raw. | |
| Image.new("RGB", (args.width, args.height), (128, 128, 128)).save(dataset/"placeholder.png", compress_level=0) | |
| cv_to_gl = np.diag([1., -1., -1., 1.]) | |
| frames = [] | |
| for i, (pose, intr) in enumerate(zip(poses, intrs)): | |
| name = f"view-{i:04d}.png" | |
| shutil.copy2(dataset/"placeholder.png", dataset/name) | |
| frames.append({"file_path": name, "w": args.width, "h": args.height, | |
| "fl_x": float(intr[0, 0]), "fl_y": float(intr[1, 1]), | |
| "cx": float(intr[0, 2]), "cy": float(intr[1, 2]), | |
| "transform_matrix": (pose @ cv_to_gl).tolist()}) | |
| # A duplicate of each requested camera serves only as the no-op train view; | |
| # evaluation selects every second entry, covering every requested camera. | |
| for name, subset in [("transforms.json", [frame for frame in frames for _ in range(2)])]: | |
| (dataset/name).write_text(json.dumps({"camera_model": "OPENCV", "ply_file_path": "scene.ply", | |
| "k1": 0., "k2": 0., "p1": 0., "p2": 0., "frames": subset}), encoding="utf-8") | |
| binary = ROOT.parent/"tools/brush/bin/brush_app.exe" | |
| output = args.output/"render" | |
| command = [str(binary), str(dataset), "--total-steps", "1", "--sh-degree", str(degree), "--eval-split-every", "2", | |
| "--lr-mean", "1e-50", "--lr-mean-end", "1e-50", "--lr-scale", "1e-50", "--lr-scale-end", "1e-50", | |
| "--lr-coeffs-dc", "0", "--lr-rotation", "0", "--lr-opac", "0", "--mean-noise-weight", "0", | |
| "--max-resolution", str(max(args.width, args.height)), "--eval-every", "1", "--eval-save-to-disk", | |
| "--export-every", "1", "--export-path", str(output), "--export-name", "frozen.ply"] | |
| report = {"status": "running", "source_sha256": source_hash, "camera_sha256": camera_hash, | |
| "binary_sha256": digest(binary), "mode": "white_alpha" if args.white_alpha else "rgb", | |
| "caveat": "No-op-step rendering adapter. Ignore Brush placeholder-reference PSNR/SSIM."} | |
| report_path = args.output/"render.json" | |
| report_path.write_text(json.dumps(report, indent=2), encoding="utf-8") | |
| try: | |
| with (args.output/"brush.log").open("w", encoding="utf-8") as log: | |
| subprocess.run(command, stdout=log, stderr=subprocess.STDOUT, check=True) | |
| report["field_max_abs_differences"] = compare_splats(scene, output/"frozen.ply") | |
| if digest(args.ply) != source_hash or digest(args.cameras) != camera_hash: | |
| raise RuntimeError("Source changed during rendering") | |
| rendered = sorted((output/"eval_1").glob("view-*.png")) | |
| if len(rendered) != len(frames): | |
| raise RuntimeError("Missing render outputs") | |
| report.update(status="completed", frame_count=len(rendered), original_unchanged=True) | |
| report["outputs"] = [{"name": path.name, "sha256": digest(path)} for path in rendered] | |
| except Exception as error: | |
| report.update(status="failed", error=f"{type(error).__name__}: {error}") | |
| raise | |
| finally: | |
| report_path.write_text(json.dumps(report, indent=2), encoding="utf-8") | |
| print(json.dumps({k: report[k] for k in ("status", "frame_count", "original_unchanged")})) | |
| if __name__ == "__main__": | |
| main() | |