| """ |
| Verify estimated pose by rendering the scene with the target object at the estimated position. |
| """ |
|
|
| import json |
| import os |
|
|
| import imageio |
| import numpy as np |
| import trimesh |
| from scipy.spatial.transform import Rotation as R |
| from trimesh.transformations import euler_matrix |
|
|
| import genesis as gs |
|
|
|
|
| def render_with_estimated_pose( |
| output_dir: str, |
| object_mesh_path: str, |
| container_mesh_path: str, |
| table_path: str = "../video_gen_assets/table.glb", |
| use_icp_pose: bool = True, |
| use_physics_pose: bool = False, |
| use_physics_initial: bool = False, |
| container_euler: list = None, |
| pose_idx: int = None, |
| wall_mode: bool = False, |
| wall_x: float = -0.5, |
| wall_height: float = 1.2, |
| container_pos: list = None, |
| object_scale: float = 1.0, |
| ): |
| """Render scene with target object at estimated pose.""" |
|
|
| pose_label = "estimated" |
|
|
| if use_physics_pose or use_physics_initial: |
| |
| pose_path = os.path.join(output_dir, "physics_refinement", "refined_poses.json") |
| with open(pose_path, "r") as f: |
| pose_data = json.load(f) |
|
|
| if pose_idx is not None: |
| best_pose = pose_data["valid_poses"][pose_idx] |
| print(f"Using physics pose at index {pose_idx}") |
| else: |
| best_pose = pose_data.get("best_pose") |
| if best_pose is None: |
| raise ValueError("No valid physics-refined pose found") |
|
|
| if use_physics_initial: |
| |
| if "init_pos" not in best_pose: |
| raise ValueError("Initial pose not stored. Re-run physics refinement.") |
| tvec_w = np.array(best_pose["init_pos"]) |
| quat_wxyz = best_pose["init_quat_wxyz"] |
| pose_label = "physics_initial" |
| print("Using physics INITIAL pose (before settling)") |
| else: |
| |
| tvec_w = np.array(best_pose["pos"]) |
| quat_wxyz = best_pose["quat_wxyz"] |
| pose_label = "physics_final" |
| print("Using physics FINAL pose (after settling)") |
|
|
| |
| quat_xyzw = [quat_wxyz[1], quat_wxyz[2], quat_wxyz[3], quat_wxyz[0]] |
| rvec_w = R.from_quat(quat_xyzw).as_rotvec() |
| print(f"Stability: pos_drift={best_pose['pos_drift']:.4f}m, rot_drift={best_pose['rot_drift_deg']:.2f}°") |
| else: |
| |
| pose_path = os.path.join(output_dir, "pose_estimation", "best_pose.json") |
| with open(pose_path, "r") as f: |
| pose_data = json.load(f) |
|
|
| if use_icp_pose and "tvec_w_icp" in pose_data: |
| tvec_w = np.array(pose_data["tvec_w_icp"]) |
| rvec_w = np.array(pose_data["rvec_w_icp"]) |
| print("Using ICP-refined pose") |
| else: |
| tvec_w = np.array(pose_data["tvec_w"]) |
| rvec_w = np.array(pose_data["rvec_w"]) |
| print("Using 3D-3D registration pose") |
|
|
| print(f"Position: {tvec_w}") |
| print(f"Rotation (rotvec): {rvec_w}") |
|
|
| |
| rot = R.from_rotvec(rvec_w) |
| quat_xyzw = rot.as_quat() |
| quat_wxyz = np.array([quat_xyzw[3], quat_xyzw[0], quat_xyzw[1], quat_xyzw[2]]) |
|
|
| |
| cam_pose = np.load(os.path.join(output_dir, "cam_pose.npy")) |
| intrinsic_K = np.load(os.path.join(output_dir, "intrinsic_K.npy")) |
|
|
| |
| |
| cam_pos = cam_pose[:3, 3] |
|
|
| |
| forward = cam_pose[:3, 2] |
|
|
| |
| lookat = cam_pos + forward * 1.0 |
|
|
| print(f"Camera position: {cam_pos}") |
| print(f"Camera forward: {forward}") |
| print(f"Camera lookat: {lookat}") |
|
|
| |
| gs.init(seed=0, precision="32", logging_level="warning") |
|
|
| |
| DEFAULT_HDR_PATH = os.environ.get( |
| "DEMO_HDR_PATH", |
| os.path.join( |
| os.path.dirname(os.path.abspath(__file__)), |
| "..", "video_gen_assets", |
| "9286496a-b761-4bdf-9f08-7966281b9c69.hdr", |
| ), |
| ) |
| renderer_kwargs = { |
| "env_radius": 200.0, |
| "lights": [ |
| {"pos": (0, -70, 40), "color": (255.0, 255.0, 255.0), |
| "radius": 7, "intensity": 0.42}, |
| ], |
| } |
| if os.path.exists(DEFAULT_HDR_PATH): |
| renderer_kwargs["env_surface"] = gs.surfaces.Emission( |
| emissive_texture=gs.textures.ImageTexture( |
| image_path=DEFAULT_HDR_PATH, |
| image_color=(0.5, 0.5, 0.5), |
| ) |
| ) |
|
|
| scene = gs.Scene( |
| sim_options=gs.options.SimOptions(dt=0.01, substeps=5, gravity=(0, 0, -9.8)), |
| show_viewer=False, |
| rigid_options=gs.options.RigidOptions(enable_collision=False), |
| renderer=gs.renderers.RayTracer(**renderer_kwargs), |
| ) |
|
|
| |
| cam = scene.add_camera( |
| pos=tuple(cam_pos), |
| lookat=tuple(lookat), |
| res=(1200, 896), |
| fov=50.0, |
| GUI=False, |
| spp=1024, |
| ) |
|
|
| mat_rigid = gs.materials.Rigid() |
|
|
| if wall_mode: |
| |
| from place_scene import add_wall, DEFAULT_WALL_TEXTURE |
| c_euler = container_euler if container_euler is not None else [-180, 0, 90] |
|
|
| |
| if os.path.exists(DEFAULT_WALL_TEXTURE): |
| add_wall(scene, wall_x, wall_x, -3, 3, height=3.0, |
| texture=DEFAULT_WALL_TEXTURE, wall_id=0) |
|
|
| |
| crx, cry, crz = np.deg2rad(c_euler) |
| cmesh = trimesh.load(container_mesh_path, force="mesh") |
| cmesh.apply_transform(euler_matrix(crx, cry, crz, "sxyz")) |
| min_x = cmesh.bounds[0][0] |
| container_x = wall_x - min_x |
| container_entity = scene.add_entity( |
| material=mat_rigid, |
| morph=gs.morphs.Mesh( |
| file=container_mesh_path, |
| pos=[container_x, 0.0, wall_height], |
| euler=c_euler, |
| collision=False, |
| ), |
| surface=gs.surfaces.Plastic(), |
| ) |
| else: |
| |
| scene.add_entity( |
| material=mat_rigid, |
| morph=gs.morphs.Mesh( |
| file=table_path, |
| pos=[0.0, 0.0, 0.485403], |
| euler=[90, 0, 90], |
| collision=False, |
| ), |
| ) |
|
|
| |
| DEFAULT_WALL_TEXTURE = os.environ.get( |
| "DEMO_WALL_TEXTURE", |
| os.path.join( |
| os.path.dirname(os.path.abspath(__file__)), |
| "..", "video_gen_assets", "wall-basecolor.jpg", |
| ), |
| ) |
| if os.path.exists(DEFAULT_WALL_TEXTURE): |
| from place_scene import add_wall |
| add_wall(scene, -0.345, -0.345, -3, 3, |
| texture=DEFAULT_WALL_TEXTURE, wall_id=0) |
|
|
| c_euler = container_euler if container_euler is not None else [90, 0, 0] |
| table_height = 0.7451 |
| if container_pos is not None: |
| c_pos = list(container_pos) |
| print(f"Container placed at pos={c_pos} (override)") |
| else: |
| crx, cry, crz = np.deg2rad(c_euler) |
| cmesh = trimesh.load(container_mesh_path, force="mesh") |
| cmesh.apply_transform(euler_matrix(crx, cry, crz, "sxyz")) |
| container_z = table_height - cmesh.bounds[0][2] |
| c_pos = [0.0, 0.0, container_z] |
| print(f"Container auto-placed at z={container_z:.4f}") |
| container_entity_kwargs = { |
| "material": mat_rigid, |
| "morph": gs.morphs.Mesh( |
| file=container_mesh_path, |
| pos=c_pos, |
| euler=c_euler, |
| collision=False, |
| ), |
| } |
| |
| if container_mesh_path.endswith(".obj"): |
| container_entity_kwargs["surface"] = gs.surfaces.Metal() |
| container_entity = scene.add_entity(**container_entity_kwargs) |
|
|
| |
| |
| euler_deg = rot.as_euler('xyz', degrees=True) |
|
|
| target_mesh_kwargs = { |
| "file": object_mesh_path, |
| "pos": list(tvec_w), |
| "quat": list(quat_wxyz), |
| "collision": False, |
| } |
| if object_scale != 1.0: |
| target_mesh_kwargs["scale"] = object_scale |
| target_entity = scene.add_entity( |
| material=mat_rigid, |
| morph=gs.morphs.Mesh(**target_mesh_kwargs), |
| ) |
|
|
| scene.build() |
|
|
| |
| img, depth, seg, _ = cam.render(depth=True, segmentation=True) |
|
|
| |
| verify_dir = os.path.join(output_dir, "pose_verification") |
| os.makedirs(verify_dir, exist_ok=True) |
|
|
| output_path = os.path.join(verify_dir, f"rendered_at_{pose_label}_pose.png") |
| imageio.imwrite(output_path, img) |
| print(f"\nSaved verification render: {output_path}") |
|
|
| |
| goal_image_path = os.path.join(output_dir, "image_goal.png") |
| if os.path.exists(goal_image_path): |
| goal_img = imageio.imread(goal_image_path) |
|
|
| |
| if goal_img.shape[:2] != img.shape[:2]: |
| from PIL import Image |
| goal_pil = Image.fromarray(goal_img) |
| goal_pil = goal_pil.resize((img.shape[1], img.shape[0]), Image.BILINEAR) |
| goal_img = np.array(goal_pil) |
|
|
| |
| comparison = np.concatenate([goal_img[:, :, :3], img], axis=1) |
| comparison_path = os.path.join(verify_dir, "comparison_goal_vs_estimated.png") |
| imageio.imwrite(comparison_path, comparison) |
| print(f"Saved comparison: {comparison_path}") |
|
|
| return img |
|
|
|
|
| def main(): |
| import argparse |
|
|
| parser = argparse.ArgumentParser(description="Verify estimated pose by rendering") |
| parser.add_argument("--output_dir", type=str, default="./outputs/mug_tree_goal", |
| help="Output directory with pipeline outputs") |
| parser.add_argument("--object_mesh_path", type=str, default="./assets/mug_0.glb", |
| help="Path to target object mesh") |
| parser.add_argument("--container_mesh_path", type=str, |
| default="./assets/metal_mug_holder/metal_mug_holder.obj", |
| help="Path to container mesh") |
| parser.add_argument("--table_path", type=str, |
| default="../video_gen_assets/table.glb", |
| help="Path to table mesh") |
| parser.add_argument("--no_icp", action="store_true", |
| help="Use pose before ICP refinement") |
| parser.add_argument("--physics", action="store_true", |
| help="Use physics-refined final pose (after settling)") |
| parser.add_argument("--physics_initial", action="store_true", |
| help="Use physics initial pose (before settling)") |
| parser.add_argument("--container_euler", type=float, nargs=3, default=None, |
| help="Container euler angles (default: [90, 0, 0])") |
| parser.add_argument("--pose_idx", type=int, default=None, |
| help="Index into valid_poses (default: use best_pose)") |
| parser.add_argument("--container_pos", type=float, nargs=3, default=None, |
| help="Override container position [x y z] (default: auto-compute from mesh bounds)") |
| parser.add_argument("--wall", action="store_true", |
| help="Use wall-mounted scene instead of table") |
| parser.add_argument("--wall_x", type=float, default=-0.5, |
| help="X position of wall plane (default: -0.5)") |
| parser.add_argument("--wall_height", type=float, default=1.2, |
| help="Z height to mount container on wall (default: 1.2)") |
| parser.add_argument("--object_scale", type=float, default=1.0, |
| help="Scale factor for target object mesh (default: 1.0)") |
|
|
| args = parser.parse_args() |
|
|
| render_with_estimated_pose( |
| output_dir=args.output_dir, |
| object_mesh_path=args.object_mesh_path, |
| container_mesh_path=args.container_mesh_path, |
| table_path=args.table_path, |
| use_icp_pose=not args.no_icp, |
| use_physics_pose=args.physics, |
| use_physics_initial=args.physics_initial, |
| container_euler=args.container_euler, |
| pose_idx=args.pose_idx, |
| wall_mode=args.wall, |
| wall_x=args.wall_x, |
| wall_height=args.wall_height, |
| container_pos=args.container_pos, |
| object_scale=args.object_scale, |
| ) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|