Datasets:
Download graspnet_example/reconstruct_scene.py from lipeize/graspnet-infinite-objects: direct link, hf CLI and curl.
- Browser
- Download file 5.68 kB
-
https://huggingface.co/datasets/lipeize/graspnet-infinite-objects/resolve/main/graspnet_example/reconstruct_scene.py
- Command line
-
hf download hf://datasets/lipeize/graspnet-infinite-objects/graspnet_example/reconstruct_scene.py
-
curl -L -o reconstruct_scene.py https://huggingface.co/datasets/lipeize/graspnet-infinite-objects/resolve/main/graspnet_example/reconstruct_scene.py
5.68 kB
| """Reconstruct a GraspNet-1Billion scene from its stored object poses, and check it against the depth image. | |
| Adapted from graspnetAPI (Fang et al., CVPR 2020; `GraspNet.loadSceneModel` / `generate_scene_model`) as vendored in | |
| GraspFormer (graspformer/data/graspnet_api). Standalone: numpy, scipy, Pillow, trimesh. | |
| GraspNet conventions used here | |
| scene_XXXX/<camera>/meta/VVVV.mat poses (3,4,N): object -> camera transforms (metres) for view VVVV; | |
| cls_indexes (N,): GraspNet object id + 1; intrinsic_matrix (3,3); factor_depth (1000) | |
| scene_XXXX/<camera>/depth/VVVV.png 16-bit depth in millimetres (divide by factor_depth) | |
| scene_XXXX/<camera>/label/VVVV.png object id + 1 per pixel, 0 = background | |
| scene_XXXX/<camera>/camera_poses.npy (256,4,4): pose of camera VVVV with respect to camera 0 (view 0) | |
| scene_XXXX/<camera>/cam0_wrt_table.npy (4,4): pose of camera 0 with respect to the table frame (z up) | |
| models/OID/textured.obj (+ .mtl, texture_map.png), nontextured.ply : object meshes in metres, object frame | |
| Usage: | |
| python reconstruct_scene.py --scene scene_0000 --models models --view 0 --out out/ # camera frame of view 0 | |
| python reconstruct_scene.py ... --table-frame # table frame (z up) | |
| Writes out/scene_<view>.glb (textured meshes at their poses), out/depth_<view>.ply (back-projected depth, coloured), | |
| prints the pose table and the median distance between depth points on objects and the reconstructed surfaces. | |
| """ | |
| import argparse, os | |
| import numpy as np, scipy.io as sio, trimesh | |
| from PIL import Image | |
| def load_view(scene_dir, camera, view): | |
| cam = os.path.join(scene_dir, camera) | |
| meta = sio.loadmat(os.path.join(cam, "meta", f"{view:04d}.mat")) | |
| poses = meta["poses"].transpose(2, 0, 1).astype(np.float64) # (N,3,4) object -> camera, metres | |
| ids = meta["cls_indexes"].ravel().astype(int) - 1 # GraspNet object ids 0..87 | |
| K = meta["intrinsic_matrix"].astype(np.float64); depth_scale = float(meta["factor_depth"].ravel()[0]) | |
| depth = np.array(Image.open(os.path.join(cam, "depth", f"{view:04d}.png")), dtype=np.float32) / depth_scale # metres | |
| rgb = np.array(Image.open(os.path.join(cam, "rgb", f"{view:04d}.png")).convert("RGB")) | |
| label = np.array(Image.open(os.path.join(cam, "label", f"{view:04d}.png"))) | |
| cam_wrt_cam0 = np.load(os.path.join(cam, "camera_poses.npy"))[view] | |
| cam0_wrt_table = np.load(os.path.join(cam, "cam0_wrt_table.npy")) | |
| return dict(poses=poses, ids=ids, K=K, depth=depth, rgb=rgb, label=label, cam_wrt_table=cam0_wrt_table @ cam_wrt_cam0) | |
| def backproject(depth, K, rgb=None, mask=None): | |
| """Pixels -> camera-frame points (metres); returns (points, colours).""" | |
| h, w = depth.shape; u, v = np.meshgrid(np.arange(w), np.arange(h)) | |
| z = depth; x = (u - K[0, 2]) * z / K[0, 0]; y = (v - K[1, 2]) * z / K[1, 1] | |
| pts = np.stack([x, y, z], -1).reshape(-1, 3); keep = z.reshape(-1) > 0 | |
| if mask is not None: keep &= mask.reshape(-1) | |
| return pts[keep], (rgb.reshape(-1, 3)[keep] if rgb is not None else None) | |
| def compose(models_dir, view, textured=True, table_frame=False): | |
| """trimesh.Scene of the scene's objects at their poses (camera frame of this view, or the table frame).""" | |
| scene = trimesh.Scene(); T_frame = view["cam_wrt_table"] if table_frame else np.eye(4) | |
| for oid, P in zip(view["ids"], view["poses"]): | |
| T = np.eye(4); T[:3] = P; T = T_frame @ T | |
| m = trimesh.load(os.path.join(models_dir, f"{oid:03d}", "textured.obj" if textured else "nontextured.ply"), force="mesh") | |
| m.apply_transform(T); scene.add_geometry(m, node_name=f"obj_{oid:03d}") | |
| return scene | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--scene", required=True); ap.add_argument("--models", required=True); ap.add_argument("--camera", default="realsense") | |
| ap.add_argument("--view", type=int, default=0); ap.add_argument("--out", default="out"); ap.add_argument("--table-frame", action="store_true") | |
| ap.add_argument("--no-texture", action="store_true") | |
| a = ap.parse_args(); os.makedirs(a.out, exist_ok=True) | |
| v = load_view(a.scene, a.camera, a.view) | |
| T_frame = v["cam_wrt_table"] if a.table_frame else np.eye(4) | |
| print(f"{os.path.basename(a.scene)} {a.camera} view {a.view}: {len(v['ids'])} objects; frame = {'table' if a.table_frame else 'camera'}") | |
| for oid, P in zip(v["ids"], v["poses"]): | |
| T = T_frame @ np.vstack([P, [0, 0, 0, 1]]) | |
| print(f" object {oid:03d}: position {np.round(T[:3, 3], 4).tolist()} rotation rows {np.round(T[:3, :3], 3).tolist()}") | |
| scene = compose(a.models, v, textured=not a.no_texture, table_frame=a.table_frame) | |
| glb = os.path.join(a.out, f"scene_{a.view:04d}.glb"); scene.export(glb) | |
| pts, cols = backproject(v["depth"], v["K"], v["rgb"], mask=v["label"] > 0) | |
| pts = trimesh.transform_points(pts, T_frame) | |
| ply = os.path.join(a.out, f"depth_{a.view:04d}.ply"); trimesh.PointCloud(pts, colors=cols).export(ply) | |
| # sanity: depth points on labelled objects should lie on the reconstructed surfaces | |
| from scipy.spatial import cKDTree | |
| surface = scene.dump(concatenate=True).sample(300_000) # dense surface sample of the reconstruction | |
| sample = pts[np.random.default_rng(0).choice(len(pts), min(5000, len(pts)), replace=False)] | |
| d = cKDTree(surface).query(sample)[0] | |
| print(f"depth points on objects: {len(pts)}; distance to reconstructed surfaces: median {1e3 * np.median(d):.1f} mm, 90th pct {1e3 * np.percentile(d, 90):.1f} mm") | |
| print(f"wrote {glb} and {ply}") | |
| if __name__ == "__main__": | |
| main() | |