DROID-Sim / package /tools /render_orbit.py
shutzang's picture
Add files using upload-large-folder tool
da6a6c0 verified
Raw History Blame Contribute Delete
6.33 kB
"""Render a slow shared-camera orbit, keeping mesh and real Gaussian assets loaded.
The camera moves around the foreground bounds' center in the gravity XY plane.
No input/completed-background image is used for compositing. Output is isolated.
"""
import argparse
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
from render_scene import orbit_camera
def gaussian_tensors(vertices, device):
import torch
stack = lambda names: kernels.stack_fields(vertices, names)
to = lambda v: torch.from_numpy(np.ascontiguousarray(v)).to(device)
quats = stack(['rot_0', 'rot_1', 'rot_2', 'rot_3'])
quats /= np.linalg.norm(quats, axis=1, keepdims=True)
return dict(means=to(stack(['x', 'y', 'z'])),
scales=to(np.exp(stack(['scale_0', 'scale_1', 'scale_2']))),
quats=to(quats), opacities=to(1. / (1. + np.exp(-vertices['opacity'].astype(np.float32)))),
harmonics=to(stack(['f_dc_0', 'f_dc_1', 'f_dc_2'])[:, None, :]))
def render(scene, output, device='cuda:0', width=320, amplitude=10., frames=81, fps=10):
import pyrender
import trimesh
import torch
from plyfile import PlyData
started = time.monotonic()
contract_path = scene / 'render/scene.json'
contract = json.loads(contract_path.read_text())
assert contract['same_camera'] and contract['compositing_policy'] == 'foreground_alpha_priority_over_real_gs'
fg_path, bg_path = scene / contract['foreground'], scene / contract['background']
hashes = dict(camera_contract=digest(contract_path), foreground=digest(fg_path), background=digest(bg_path))
source_w, source_h = contract['image_size_wh']
height = round(width * source_h / source_w)
k = np.asarray(contract['intrinsic'], dtype=float)
k[0] *= width / source_w
k[1] *= height / source_h
mesh = trimesh.load(fg_path, force='scene', process=False)
pivot = np.asarray(mesh.bounds).mean(axis=0)
ps = pyrender.Scene.from_trimesh_scene(mesh, bg_color=np.zeros(4), ambient_light=np.ones(3) * .75)
camera = pyrender.IntrinsicsCamera(fx=k[0, 0], fy=k[1, 1], cx=k[0, 2], cy=k[1, 2], znear=.01, zfar=10000.)
cam_node = ps.add(camera)
light_node = ps.add(pyrender.DirectionalLight(color=np.ones(3), intensity=2.))
wb0 = np.asarray(contract['world_to_camera_background'])
gauge = contract['background_gauge']
proof = None
if contract['background_renderer'] == 'camera_gauge_sh0':
vertices = PlyData.read(str(bg_path))['vertex'].data
normalized, proof = kernels.normalize_reloaded_output_for_render(vertices, wb0, k, float(gauge))
gaussians = gaussian_tensors(normalized, device)
del vertices, normalized
else:
assert contract['background_renderer'] == 'world'
gaussians = kernels.load_gaussians(bg_path, device)
output.mkdir(parents=True, exist_ok=True)
if proof:
write_json(output / 'normalization.json', proof)
# Constant angular speed except for reversals; begin and end at frame zero.
angles = np.interp(np.linspace(0, 1, frames), [0, .25, .75, 1], [0, amplitude, -amplitude, 0])
renderer = pyrender.OffscreenRenderer(width, height)
rows = []
images = []
try:
for index, angle in enumerate(angles):
wf, wb = orbit_camera(contract, float(angle), pivot)
pose = np.linalg.inv(wf) @ np.diag([1., -1., -1., 1.])
ps.set_pose(cam_node, pose)
ps.set_pose(light_node, pose)
rgba, depth = renderer.render(ps, flags=pyrender.RenderFlags.RGBA | pyrender.RenderFlags.SKIP_CULL_FACES)
bg_view = wb.copy()
if contract['background_renderer'] == 'camera_gauge_sh0':
bg_view = wb @ np.linalg.inv(wb0)
bg_view[:3, 3] /= float(gauge)
if angle == 0:
bg_view = np.eye(4)
with torch.inference_mode():
bg, _, coverage = kernels.render_gaussians(gaussians, bg_view, k, width, height, contract['background_color'])
fg = rgba.astype(np.float32) / 255.
alpha = (fg[:, :, 3] * (depth > 0))[:, :, None]
rgb = np.rint(np.clip(fg[:, :, :3] * alpha + bg * (1 - alpha), 0, 1) * 255).astype(np.uint8)
im = Image.fromarray(rgb)
im.save(output / f'frame_{index:03d}.png')
images.append(im)
rows.append(dict(frame=index, angle_degrees=float(angle), foreground_coverage=float((depth > 0).mean()),
background_coverage=float((coverage > .02).mean()), world_to_camera_foreground=wf.tolist(),
world_to_camera_background=wb.tolist()))
assert digest(fg_path) == hashes['foreground'] and digest(contract_path) == hashes['camera_contract'], 'Input changed during rendering'
images[0].save(output / 'orbit.gif', save_all=True, append_images=images[1:], duration=round(1000 / fps), loop=0)
report = dict(scene=scene.name, status='rendered', hashes=hashes, frames=rows, fps=fps,
amplitude_degrees=amplitude, image_size_wh=[width, height], pivot_world=pivot.tolist(),
background_source='marble_gaussian_ply', same_camera=True,
compositing_policy=contract['compositing_policy'],
elapsed_seconds=round(time.monotonic() - started, 3))
write_json(output / 'orbit.json', report)
print(json.dumps({k: v for k, v in report.items() if k != 'frames'}), flush=True)
finally:
renderer.delete()
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, default=320)
p.add_argument('--amplitude', type=float, default=10)
p.add_argument('--frames', type=int, default=81)
p.add_argument('--fps', type=int, default=10)
a = p.parse_args()
assert a.frames >= 2 and a.fps > 0 and a.width > 0
render(a.scene, a.output_dir, a.device, a.width, a.amplitude, a.frames, a.fps)
if __name__ == '__main__':
main()