Download package/tools/render_scene.py from shutzang/DROID-Sim: direct link, hf CLI and curl.
- Browser
- Download file 6.73 kB
-
https://huggingface.co/datasets/shutzang/DROID-Sim/resolve/main/package/tools/render_scene.py
- Command line
-
hf download hf://datasets/shutzang/DROID-Sim/package/tools/render_scene.py
-
curl -L -o render_scene.py https://huggingface.co/datasets/shutzang/DROID-Sim/resolve/main/package/tools/render_scene.py
6.73 kB
| """Render real Marble GS and mesh foreground through the release camera contract. | |
| Outputs only to --output-dir; never replaces accepted assets. The background | |
| cache is invalidated by PLY, camera, renderer, resolution, or policy changes. | |
| """ | |
| import argparse | |
| import hashlib | |
| import json | |
| from pathlib import Path | |
| import time | |
| import numpy as np | |
| from PIL import Image | |
| from package_trajectories import digest, write_json | |
| import render_kernels as kernels | |
| def orbit_camera(contract, angle_degrees, pivot): | |
| from scipy.spatial.transform import Rotation | |
| wf = np.asarray(contract['world_to_camera_foreground'], dtype=np.float64) | |
| if angle_degrees == 0: | |
| return wf, np.asarray(contract['world_to_camera_background'], dtype=np.float64) | |
| transform = np.eye(4) | |
| transform[:3, :3] = Rotation.from_euler('z', angle_degrees, degrees=True).as_matrix() | |
| transform[:3, 3] = pivot - transform[:3, :3] @ pivot | |
| new_wf = np.linalg.inv(transform @ np.linalg.inv(wf)) | |
| new_wb = new_wf @ np.asarray(contract['transform_foreground_from_background']) | |
| return new_wf, new_wb | |
| def render(scene, output, device='cuda:0', width=None, angle=0.0, use_cache=True): | |
| start = time.monotonic() | |
| contract_path = scene / 'render/scene.json' | |
| contract_hash = digest(contract_path) | |
| contract = json.loads(contract_path.read_text()) | |
| assert contract['format'] == 'droid_sim_render_v1' and contract['same_camera'] | |
| assert contract['compositing_policy'] == 'foreground_alpha_priority_over_real_gs' | |
| fg_path, bg_path = scene / contract['foreground'], scene / contract['background'] | |
| fg_hash, bg_hash = digest(fg_path), digest(bg_path) | |
| source_width, source_height = contract['image_size_wh'] | |
| width = width or source_width | |
| height = round(width * source_height / source_width) | |
| k = np.asarray(contract['intrinsic'], dtype=np.float64) | |
| k[0] *= width / source_width | |
| k[1] *= height / source_height | |
| if angle: | |
| import trimesh | |
| mesh_scene = trimesh.load(fg_path, force='scene', process=False) | |
| pivot = np.asarray(mesh_scene.bounds).mean(axis=0) | |
| else: | |
| pivot = np.zeros(3) | |
| wf, wb = orbit_camera(contract, angle, pivot) | |
| output.mkdir(parents=True, exist_ok=True) | |
| cache_key = dict(background_sha256=bg_hash, w2c=wb.tolist(), intrinsic=k.tolist(), | |
| width=width, height=height, mode=contract['background_renderer'], | |
| gauge=contract['background_gauge'], color=contract['background_color'], | |
| kernel_sha256=digest(Path(kernels.__file__))) | |
| key = hashlib.sha256(json.dumps(cache_key, sort_keys=True).encode()).hexdigest() | |
| cache = output / 'background_cache.npz' | |
| cached = False | |
| if use_cache and cache.exists(): | |
| with np.load(cache, allow_pickle=False) as f: | |
| if str(f['cache_key']) == key: | |
| bg, bg_depth, bg_alpha = f['rgb'], f['depth'], f['alpha'] | |
| cached = True | |
| if not cached: | |
| if contract['background_renderer'] == 'camera_gauge_sh0': | |
| from plyfile import PlyData | |
| vertices = PlyData.read(str(bg_path))['vertex'].data | |
| gauge = float(contract['background_gauge']) | |
| normalized, proof = kernels.normalize_reloaded_output_for_render(vertices, wb, k, gauge) | |
| bg, bg_depth, bg_alpha = kernels.render_gaussian_vertices(normalized, np.eye(4), k, width, height, device) | |
| bg_depth *= gauge | |
| write_json(output / 'normalization.json', proof) | |
| elif contract['background_renderer'] == 'world': | |
| gaussians = kernels.load_gaussians(bg_path, device) | |
| bg, bg_depth, bg_alpha = kernels.render_gaussians(gaussians, wb, k, width, height, contract['background_color']) | |
| else: | |
| raise ValueError('Unknown background renderer') | |
| assert np.isfinite(bg).all() and np.isfinite(bg_depth).all() | |
| np.savez_compressed(cache, cache_key=np.asarray(key), rgb=bg, depth=bg_depth, alpha=bg_alpha) | |
| foreground, fg_depth = kernels.render_mesh(fg_path, wf, k, width, height) | |
| alpha = (foreground[:, :, 3] * (fg_depth > 0))[:, :, None] | |
| rgb = np.rint(np.clip(foreground[:, :, :3] * alpha + bg * (1 - alpha), 0, 1) * 255).astype(np.uint8) | |
| assert digest(fg_path) == fg_hash, 'GLB changed during rendering; output not published' | |
| assert digest(contract_path) == contract_hash, 'Camera changed during rendering; output not published' | |
| Image.fromarray(rgb).save(output / 'layered_composite.png') | |
| Image.fromarray(np.rint(np.clip(bg, 0, 1) * 255).astype(np.uint8)).save(output / 'background_render.png') | |
| Image.fromarray(np.rint(np.clip(foreground, 0, 1) * 255).astype(np.uint8)).save(output / 'foreground_render.png') | |
| target = Image.open(scene / contract['target_image']).convert('RGB').resize((width, height), Image.Resampling.LANCZOS) | |
| overlay = Image.blend(target, Image.fromarray(rgb), 0.5) | |
| Image.fromarray(np.concatenate([np.asarray(target), rgb, np.asarray(overlay)], axis=1)).save(output / 'comparison.png') | |
| metrics = dict(scene=scene.name, foreground_sha256=fg_hash, background_sha256=bg_hash, | |
| camera_contract_sha256=digest(contract_path), background_cache_used=cached, | |
| background_source='marble_gaussian_ply', image_size_wh=[width, height], | |
| angle_degrees=angle, same_camera=True, | |
| foreground_coverage=float((fg_depth > 0).mean()), | |
| background_coverage=float((bg_alpha > .02).mean()), | |
| compositing_policy=contract['compositing_policy'], | |
| elapsed_seconds=round(time.monotonic() - start, 3)) | |
| if not angle and width == source_width: | |
| accepted = np.asarray(Image.open(scene / 'layered_composite.png').convert('RGB')) | |
| error = np.abs(accepted.astype(float) - rgb.astype(float)) | |
| metrics['accepted_composite_difference'] = dict(mae=float(error.mean()), max=float(error.max()), | |
| different_pixel_fraction=float(np.any(error > 0, axis=-1).mean())) | |
| write_json(output / 'render_status.json', metrics) | |
| return metrics | |
| def main(): | |
| p = argparse.ArgumentParser(description=__doc__) | |
| p.add_argument('--scene', type=Path, required=True) | |
| p.add_argument('--output-dir', type=Path, required=True) | |
| p.add_argument('--device', default='cuda:0') | |
| p.add_argument('--width', type=int) | |
| p.add_argument('--orbit-deg', type=float, default=0.0) | |
| p.add_argument('--no-cache', action='store_true') | |
| a = p.parse_args() | |
| print(json.dumps(render(a.scene, a.output_dir, a.device, a.width, a.orbit_deg, not a.no_cache), indent=2)) | |
| if __name__ == '__main__': | |
| main() | |