Commit
·
44e46d6
1
Parent(s):
00becf6
Add visualization scripts
Browse files- scripts/dataset.py +92 -0
- scripts/download_objaverse.py +80 -0
- scripts/meshcat_utils.py +366 -0
- scripts/visualize_dataset.py +148 -0
scripts/dataset.py
ADDED
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
|
2 |
+
#
|
3 |
+
# NVIDIA CORPORATION and its licensors retain all intellectual property
|
4 |
+
# and proprietary rights in and to this software, related documentation
|
5 |
+
# and any modifications thereto. Any use, reproduction, disclosure or
|
6 |
+
# distribution of this software and related documentation without an express
|
7 |
+
# license agreement from NVIDIA CORPORATION is strictly prohibited.
|
8 |
+
#
|
9 |
+
'''
|
10 |
+
Dataset class for loading and processing grasp data from a WebDataset.
|
11 |
+
|
12 |
+
Installation:
|
13 |
+
pip install trimesh==4.5.3 objaverse==0.1.7 meshcat==0.0.12 webdataset==0.2.111
|
14 |
+
|
15 |
+
'''
|
16 |
+
import os
|
17 |
+
import json
|
18 |
+
import time
|
19 |
+
import webdataset as wds
|
20 |
+
import glob
|
21 |
+
from pathlib import Path
|
22 |
+
from tqdm import tqdm
|
23 |
+
from typing import Dict, Optional
|
24 |
+
|
25 |
+
def load_uuid_list(uuid_list_path: str):
|
26 |
+
if not os.path.exists(uuid_list_path):
|
27 |
+
raise FileNotFoundError(f"UUID list file not found: {uuid_list_path}")
|
28 |
+
if uuid_list_path.endswith(".json"):
|
29 |
+
with open(uuid_list_path, 'r') as f:
|
30 |
+
uuids = json.load(f)
|
31 |
+
if type(uuids) == list:
|
32 |
+
return uuids
|
33 |
+
elif type(uuids) == dict:
|
34 |
+
return list(uuids.keys())
|
35 |
+
else:
|
36 |
+
raise ValueError(f"UUID list is not a list or dict: {uuids}")
|
37 |
+
elif uuid_list_path.endswith(".txt"):
|
38 |
+
with open(uuid_list_path, 'r') as f:
|
39 |
+
uuids = [line.strip() for line in f.readlines()]
|
40 |
+
else:
|
41 |
+
raise ValueError(f"Unsupported file format: {uuid_list_path}")
|
42 |
+
return uuids
|
43 |
+
|
44 |
+
class GraspWebDatasetReader:
|
45 |
+
"""Class to efficiently read grasps data using a pre-loaded index."""
|
46 |
+
|
47 |
+
def __init__(self, dataset_path: str):
|
48 |
+
"""
|
49 |
+
Initialize the reader with dataset path and load the index.
|
50 |
+
|
51 |
+
Args:
|
52 |
+
dataset_path (str): Path to directory containing WebDataset shards
|
53 |
+
"""
|
54 |
+
self.dataset_path = dataset_path
|
55 |
+
self.shards_dir = self.dataset_path
|
56 |
+
|
57 |
+
# Load the UUID index
|
58 |
+
index_path = os.path.join(self.shards_dir, "uuid_index.json")
|
59 |
+
with open(index_path, 'r') as f:
|
60 |
+
self.uuid_index = json.load(f)
|
61 |
+
|
62 |
+
# Cache for open datasets
|
63 |
+
self.shard_datasets = {}
|
64 |
+
|
65 |
+
def read_grasps_by_uuid(self, object_uuid: str) -> Optional[Dict]:
|
66 |
+
"""
|
67 |
+
Read grasps data for a specific object UUID using the index.
|
68 |
+
|
69 |
+
Args:
|
70 |
+
object_uuid (str): UUID of the object to retrieve
|
71 |
+
|
72 |
+
Returns:
|
73 |
+
Optional[Dict]: Dictionary containing the grasps data if found, None otherwise
|
74 |
+
"""
|
75 |
+
if object_uuid not in self.uuid_index:
|
76 |
+
return None
|
77 |
+
|
78 |
+
shard_idx = self.uuid_index[object_uuid]
|
79 |
+
|
80 |
+
# Get or create dataset for this shard
|
81 |
+
if shard_idx not in self.shard_datasets:
|
82 |
+
shard_path = f"{self.shards_dir}/shard_{shard_idx:03d}.tar"
|
83 |
+
self.shard_datasets[shard_idx] = wds.WebDataset(shard_path)
|
84 |
+
|
85 |
+
dataset = self.shard_datasets[shard_idx]
|
86 |
+
|
87 |
+
# Search for the UUID in the specific shard
|
88 |
+
for sample in dataset:
|
89 |
+
if sample["__key__"] == object_uuid:
|
90 |
+
return json.loads(sample["grasps.json"])
|
91 |
+
|
92 |
+
return None
|
scripts/download_objaverse.py
ADDED
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
|
2 |
+
#
|
3 |
+
# NVIDIA CORPORATION and its licensors retain all intellectual property
|
4 |
+
# and proprietary rights in and to this software, related documentation
|
5 |
+
# and any modifications thereto. Any use, reproduction, disclosure or
|
6 |
+
# distribution of this software and related documentation without an express
|
7 |
+
# license agreement from NVIDIA CORPORATION is strictly prohibited.
|
8 |
+
#
|
9 |
+
'''
|
10 |
+
Download specific Objaverse meshes given their UUIDs.
|
11 |
+
|
12 |
+
Installation:
|
13 |
+
pip install trimesh==4.5.3 objaverse==0.1.7 meshcat==0.0.12 webdataset==0.2.111
|
14 |
+
|
15 |
+
Usage:
|
16 |
+
python download_objaverse.py --uuid_list /path_to_dataset/splits/franka/valid_scenes.json --output_dir /tmp/objs
|
17 |
+
'''
|
18 |
+
import argparse
|
19 |
+
import json
|
20 |
+
import os
|
21 |
+
import shutil
|
22 |
+
from objaverse import load_objects
|
23 |
+
from pathlib import Path
|
24 |
+
from dataset import load_uuid_list
|
25 |
+
|
26 |
+
def download_objaverse_meshes(uuids: list[str], output_dir: str):
|
27 |
+
"""
|
28 |
+
Download specific Objaverse meshes given their UUIDs.
|
29 |
+
|
30 |
+
Args:
|
31 |
+
uuid_list_path (str): Path to JSON file containing list of UUIDs
|
32 |
+
output_dir (str): Directory where meshes will be saved
|
33 |
+
"""
|
34 |
+
# Create output directory if it doesn't exist
|
35 |
+
os.makedirs(output_dir, exist_ok=True)
|
36 |
+
|
37 |
+
print(f"Found {len(uuids)} UUIDs to download")
|
38 |
+
|
39 |
+
# Download objects using Objaverse
|
40 |
+
objects = load_objects(uids=uuids)
|
41 |
+
|
42 |
+
map_uuid_to_path = {}
|
43 |
+
|
44 |
+
# Save each object to the output directory
|
45 |
+
for uuid in uuids:
|
46 |
+
try:
|
47 |
+
# Get the object path from Objaverse
|
48 |
+
obj_path = objects[uuid]
|
49 |
+
|
50 |
+
if obj_path is None:
|
51 |
+
print(f"Failed to download object {uuid}")
|
52 |
+
continue
|
53 |
+
|
54 |
+
# Create destination path
|
55 |
+
dest_path = os.path.join(output_dir, os.path.basename(obj_path))
|
56 |
+
|
57 |
+
shutil.copy2(obj_path, dest_path)
|
58 |
+
|
59 |
+
print(f"Successfully downloaded and saved object {uuid}, saved to {dest_path}")
|
60 |
+
map_uuid_to_path[uuid] = dest_path
|
61 |
+
|
62 |
+
os.remove(obj_path)
|
63 |
+
json.dump(map_uuid_to_path, open(os.path.join(output_dir, "map_uuid_to_path.json"), "w"))
|
64 |
+
|
65 |
+
except Exception as e:
|
66 |
+
print(f"Error processing object {uuid}: {e}")
|
67 |
+
|
68 |
+
print("Download complete!")
|
69 |
+
|
70 |
+
def parse_args():
|
71 |
+
parser = argparse.ArgumentParser()
|
72 |
+
parser.add_argument("--uuid_list", type=str, help="Path to UUID list or Json. This can be the split json file from the GraspGen dataset")
|
73 |
+
parser.add_argument("--output_dir", type=str, help="Path to output directory")
|
74 |
+
return parser.parse_args()
|
75 |
+
|
76 |
+
|
77 |
+
if __name__ == "__main__":
|
78 |
+
args = parse_args()
|
79 |
+
uuid_list = load_uuid_list(args.uuid_list)
|
80 |
+
download_objaverse_meshes(uuid_list, args.output_dir)
|
scripts/meshcat_utils.py
ADDED
@@ -0,0 +1,366 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
|
2 |
+
#
|
3 |
+
# NVIDIA CORPORATION and its licensors retain all intellectual property
|
4 |
+
# and proprietary rights in and to this software, related documentation
|
5 |
+
# and any modifications thereto. Any use, reproduction, disclosure or
|
6 |
+
# distribution of this software and related documentation without an express
|
7 |
+
# license agreement from NVIDIA CORPORATION is strictly prohibited.
|
8 |
+
#
|
9 |
+
'''
|
10 |
+
Utility functions for visualization using meshcat.
|
11 |
+
|
12 |
+
Installation:
|
13 |
+
pip install trimesh==4.5.3 objaverse==0.1.7 meshcat==0.0.12 webdataset==0.2.111
|
14 |
+
|
15 |
+
NOTE: Start meshcat server (in a different terminal) before running this script:
|
16 |
+
meshcat-server
|
17 |
+
'''
|
18 |
+
|
19 |
+
import numpy as np
|
20 |
+
import meshcat
|
21 |
+
import meshcat.geometry as g
|
22 |
+
import meshcat.transformations as mtf
|
23 |
+
import trimesh
|
24 |
+
import trimesh.transformations as tra
|
25 |
+
from typing import List, Optional, Tuple, Union, Any
|
26 |
+
|
27 |
+
control_points_franka = np.array([
|
28 |
+
[ 0.05268743, -0.00005996, 0.05900000],
|
29 |
+
[-0.05268743, 0.00005996, 0.05900000],
|
30 |
+
[ 0.05268743, -0.00005996, 0.10527314],
|
31 |
+
[-0.05268743, 0.00005996, 0.10527314]
|
32 |
+
])
|
33 |
+
|
34 |
+
control_points_robotiq2f140 = np.array([
|
35 |
+
[ 0.06801729, -0, 0.0975],
|
36 |
+
[-0.06801729, 0, 0.0975],
|
37 |
+
[ 0.06801729, -0, 0.1950],
|
38 |
+
[-0.06801729, 0, 0.1950]
|
39 |
+
])
|
40 |
+
|
41 |
+
control_points_suction = np.array([
|
42 |
+
[ 0, 0, -0.10],
|
43 |
+
[ 0, 0, -0.05],
|
44 |
+
[ 0, 0, 0],
|
45 |
+
])
|
46 |
+
|
47 |
+
control_points_data = {
|
48 |
+
"franka": control_points_franka,
|
49 |
+
"robotiq2f140": control_points_robotiq2f140,
|
50 |
+
"suction": control_points_suction,
|
51 |
+
}
|
52 |
+
|
53 |
+
def get_gripper_control_points(gripper_name: str = 'franka') -> np.ndarray:
|
54 |
+
"""
|
55 |
+
Get the control points for a specific gripper.
|
56 |
+
|
57 |
+
Args:
|
58 |
+
gripper_name (str): Name of the gripper ("franka", "robotiq2f140", "suction")
|
59 |
+
|
60 |
+
Returns:
|
61 |
+
np.ndarray: Array of control points for the specified gripper
|
62 |
+
|
63 |
+
Raises:
|
64 |
+
NotImplementedError: If the specified gripper is not implemented
|
65 |
+
"""
|
66 |
+
if gripper_name in control_points_data:
|
67 |
+
return control_points_data[gripper_name]
|
68 |
+
else:
|
69 |
+
raise NotImplementedError(f"Gripper {gripper_name} is not implemented.")
|
70 |
+
return control_points
|
71 |
+
|
72 |
+
def get_gripper_depth(gripper_name: str) -> float:
|
73 |
+
"""
|
74 |
+
Get the depth parameter for a specific gripper type.
|
75 |
+
|
76 |
+
Args:
|
77 |
+
gripper_name (str): Name of the gripper ("franka", "robotiq2f140", "suction")
|
78 |
+
|
79 |
+
Returns:
|
80 |
+
float: Depth parameter for the specified gripper
|
81 |
+
|
82 |
+
Raises:
|
83 |
+
NotImplementedError: If the specified gripper is not implemented
|
84 |
+
"""
|
85 |
+
# TODO: Use register module. Don't have this if-else name lookup
|
86 |
+
pts, d = None, None
|
87 |
+
if gripper_name in ["franka", "robotiq2f140"]:
|
88 |
+
pts = get_gripper_control_points(gripper_name)
|
89 |
+
elif gripper_name == "suction":
|
90 |
+
return 0.069
|
91 |
+
else:
|
92 |
+
raise NotImplementedError(f"Control points for gripper {gripper_name} not implemented!")
|
93 |
+
d = pts[-1][-1] if pts is not None else d
|
94 |
+
return d
|
95 |
+
|
96 |
+
def get_gripper_offset(gripper_name: str) -> np.ndarray:
|
97 |
+
"""
|
98 |
+
Get the offset transform for a specific gripper type.
|
99 |
+
|
100 |
+
Args:
|
101 |
+
gripper_name (str): Name of the gripper
|
102 |
+
|
103 |
+
Returns:
|
104 |
+
np.ndarray: 4x4 homogeneous transformation matrix representing the gripper offset
|
105 |
+
"""
|
106 |
+
return np.eye(4)
|
107 |
+
|
108 |
+
def load_visualize_control_points_suction() -> np.ndarray:
|
109 |
+
"""
|
110 |
+
Load visualization control points specific to the suction gripper.
|
111 |
+
|
112 |
+
Returns:
|
113 |
+
np.ndarray: Array of control points for suction gripper visualization
|
114 |
+
"""
|
115 |
+
h = 0
|
116 |
+
pts = [
|
117 |
+
[0.0, 0],
|
118 |
+
]
|
119 |
+
pts = [generate_circle_points(c, radius=0.005) for c in pts]
|
120 |
+
pts = np.stack(pts)
|
121 |
+
ptsz = h * np.ones([pts.shape[0], pts.shape[1], 1])
|
122 |
+
pts = np.concatenate([pts, ptsz], axis=2)
|
123 |
+
return pts
|
124 |
+
|
125 |
+
def generate_circle_points(center: List[float], radius: float = 0.007, N: int = 30) -> np.ndarray:
|
126 |
+
"""
|
127 |
+
Generate points forming a circle in 2D space.
|
128 |
+
|
129 |
+
Args:
|
130 |
+
center (List[float]): Center coordinates [x, y] of the circle
|
131 |
+
radius (float): Radius of the circle
|
132 |
+
N (int): Number of points to generate around the circle
|
133 |
+
|
134 |
+
Returns:
|
135 |
+
np.ndarray: Array of shape (N, 2) containing the circle points
|
136 |
+
"""
|
137 |
+
angles = np.linspace(0, 2 * np.pi, N, endpoint=False)
|
138 |
+
x_points = center[0] + radius * np.cos(angles)
|
139 |
+
y_points = center[1] + radius * np.sin(angles)
|
140 |
+
points = np.stack((x_points, y_points), axis=1)
|
141 |
+
return points
|
142 |
+
|
143 |
+
|
144 |
+
def get_gripper_visualization_control_points(gripper_name: str = 'franka') -> List[np.ndarray]:
|
145 |
+
"""
|
146 |
+
Get control points for visualizing a specific gripper type.
|
147 |
+
|
148 |
+
Args:
|
149 |
+
gripper_name (str): Name of the gripper ("franka", "robotiq2f140", "suction")
|
150 |
+
|
151 |
+
Returns:
|
152 |
+
List[np.ndarray]: List of control point arrays for gripper visualization
|
153 |
+
"""
|
154 |
+
if gripper_name == "suction":
|
155 |
+
control_points = load_visualize_control_points_suction()
|
156 |
+
offset = get_gripper_offset('suction')
|
157 |
+
ctrl_pts = [tra.transform_points(cpt, offset) for cpt in control_points]
|
158 |
+
d = get_gripper_depth(gripper_name)
|
159 |
+
line_pts = np.array([[0,0,0], [0,0,d]])
|
160 |
+
line_pts = np.expand_dims(line_pts, 0)
|
161 |
+
line_pts = [tra.transform_points(cpt, offset) for cpt in line_pts]
|
162 |
+
line_pts = line_pts[0]
|
163 |
+
ctrl_pts.append(line_pts)
|
164 |
+
return ctrl_pts
|
165 |
+
else:
|
166 |
+
control_points = get_gripper_control_points(gripper_name)
|
167 |
+
mid_point = (control_points[0] + control_points[1]) / 2
|
168 |
+
control_points = [
|
169 |
+
control_points[-2], control_points[0], mid_point,
|
170 |
+
[0, 0, 0], mid_point, control_points[1], control_points[-1]
|
171 |
+
]
|
172 |
+
return [control_points, ]
|
173 |
+
|
174 |
+
def get_color_from_score(labels: Union[float, np.ndarray], use_255_scale: bool = False) -> np.ndarray:
|
175 |
+
"""
|
176 |
+
Convert score labels to RGB colors for visualization.
|
177 |
+
|
178 |
+
Args:
|
179 |
+
labels (Union[float, np.ndarray]): Score values between 0 and 1
|
180 |
+
use_255_scale (bool): If True, output colors in [0-255] range, else [0-1]
|
181 |
+
|
182 |
+
Returns:
|
183 |
+
np.ndarray: RGB colors corresponding to the input scores
|
184 |
+
"""
|
185 |
+
scale = 255.0 if use_255_scale else 1.0
|
186 |
+
if type(labels) in [np.float32, float]:
|
187 |
+
return scale * np.array([1 - labels, labels, 0])
|
188 |
+
else:
|
189 |
+
scale = 255.0 if use_255_scale else 1.0
|
190 |
+
score = scale * np.stack(
|
191 |
+
[np.ones(labels.shape[0]) - labels, labels, np.zeros(labels.shape[0])],
|
192 |
+
axis=1,
|
193 |
+
)
|
194 |
+
return score.astype(np.int)
|
195 |
+
|
196 |
+
def trimesh_to_meshcat_geometry(mesh: trimesh.Trimesh) -> g.TriangularMeshGeometry:
|
197 |
+
"""
|
198 |
+
Convert a trimesh mesh to meshcat geometry format.
|
199 |
+
|
200 |
+
Args:
|
201 |
+
mesh (trimesh.Trimesh): Input mesh in trimesh format
|
202 |
+
|
203 |
+
Returns:
|
204 |
+
g.TriangularMeshGeometry: Mesh in meshcat geometry format
|
205 |
+
"""
|
206 |
+
return meshcat.geometry.TriangularMeshGeometry(mesh.vertices, mesh.faces)
|
207 |
+
|
208 |
+
|
209 |
+
def visualize_mesh(
|
210 |
+
vis: meshcat.Visualizer,
|
211 |
+
name: str,
|
212 |
+
mesh: trimesh.Trimesh,
|
213 |
+
color: Optional[List[int]] = None,
|
214 |
+
transform: Optional[np.ndarray] = None
|
215 |
+
) -> None:
|
216 |
+
"""
|
217 |
+
Visualize a mesh in meshcat with optional color and transform.
|
218 |
+
|
219 |
+
Args:
|
220 |
+
vis (meshcat.Visualizer): Meshcat visualizer instance
|
221 |
+
name (str): Name/path for the mesh in the visualizer scene
|
222 |
+
mesh (trimesh.Trimesh): Mesh to visualize
|
223 |
+
color (Optional[List[int]]): RGB color values [0-255]. Random if None
|
224 |
+
transform (Optional[np.ndarray]): 4x4 homogeneous transform matrix
|
225 |
+
"""
|
226 |
+
if vis is None:
|
227 |
+
return
|
228 |
+
|
229 |
+
if color is None:
|
230 |
+
color = np.random.randint(low=0, high=256, size=3)
|
231 |
+
|
232 |
+
mesh_vis = trimesh_to_meshcat_geometry(mesh)
|
233 |
+
color_hex = rgb2hex(tuple(color))
|
234 |
+
material = meshcat.geometry.MeshPhongMaterial(color=color_hex)
|
235 |
+
vis[name].set_object(mesh_vis, material)
|
236 |
+
|
237 |
+
if transform is not None:
|
238 |
+
vis[name].set_transform(transform)
|
239 |
+
|
240 |
+
|
241 |
+
def rgb2hex(rgb: Tuple[int, int, int]) -> str:
|
242 |
+
"""
|
243 |
+
Convert RGB color values to hexadecimal string.
|
244 |
+
|
245 |
+
Args:
|
246 |
+
rgb (Tuple[int, int, int]): RGB color values (0-255)
|
247 |
+
|
248 |
+
Returns:
|
249 |
+
str: Hexadecimal color string (format: "0xRRGGBB")
|
250 |
+
"""
|
251 |
+
return "0x%02x%02x%02x" % (rgb)
|
252 |
+
|
253 |
+
|
254 |
+
def create_visualizer(clear: bool = True) -> meshcat.Visualizer:
|
255 |
+
"""
|
256 |
+
Create a meshcat visualizer instance.
|
257 |
+
|
258 |
+
Args:
|
259 |
+
clear (bool): If True, clear the visualizer scene upon creation first
|
260 |
+
|
261 |
+
Returns:
|
262 |
+
meshcat.Visualizer: Initialized meshcat visualizer
|
263 |
+
"""
|
264 |
+
print(
|
265 |
+
"Waiting for meshcat server... have you started a server? Run `meshcat-server` to start a server"
|
266 |
+
)
|
267 |
+
vis = meshcat.Visualizer(zmq_url="tcp://127.0.0.1:6000")
|
268 |
+
if clear:
|
269 |
+
vis.delete()
|
270 |
+
return vis
|
271 |
+
|
272 |
+
|
273 |
+
def visualize_pointcloud(
|
274 |
+
vis: meshcat.Visualizer,
|
275 |
+
name: str,
|
276 |
+
pc: np.ndarray,
|
277 |
+
color: Optional[Union[List[int], np.ndarray]] = None,
|
278 |
+
transform: Optional[np.ndarray] = None,
|
279 |
+
**kwargs: Any
|
280 |
+
) -> None:
|
281 |
+
"""
|
282 |
+
Args:
|
283 |
+
vis: meshcat visualizer object
|
284 |
+
name: str
|
285 |
+
pc: Nx3 or HxWx3
|
286 |
+
color: (optional) same shape as pc[0 - 255] scale or just rgb tuple
|
287 |
+
transform: (optional) 4x4 homogeneous transform
|
288 |
+
"""
|
289 |
+
if vis is None:
|
290 |
+
return
|
291 |
+
if pc.ndim == 3:
|
292 |
+
pc = pc.reshape(-1, pc.shape[-1])
|
293 |
+
|
294 |
+
if color is not None:
|
295 |
+
if isinstance(color, list):
|
296 |
+
color = np.array(color)
|
297 |
+
color = np.array(color)
|
298 |
+
# Resize the color np array if needed.
|
299 |
+
if color.ndim == 3:
|
300 |
+
color = color.reshape(-1, color.shape[-1])
|
301 |
+
if color.ndim == 1:
|
302 |
+
color = np.ones_like(pc) * np.array(color)
|
303 |
+
|
304 |
+
# Divide it by 255 to make sure the range is between 0 and 1,
|
305 |
+
color = color.astype(np.float32) / 255
|
306 |
+
else:
|
307 |
+
color = np.ones_like(pc)
|
308 |
+
|
309 |
+
vis[name].set_object(
|
310 |
+
meshcat.geometry.PointCloud(position=pc.T, color=color.T, **kwargs)
|
311 |
+
)
|
312 |
+
|
313 |
+
if transform is not None:
|
314 |
+
vis[name].set_transform(transform)
|
315 |
+
|
316 |
+
|
317 |
+
def load_visualization_gripper_points(gripper_name: str = "franka") -> List[np.ndarray]:
|
318 |
+
"""
|
319 |
+
Load control points for gripper visualization.
|
320 |
+
|
321 |
+
Args:
|
322 |
+
gripper_name (str): Name of the gripper to visualize
|
323 |
+
|
324 |
+
Returns:
|
325 |
+
List[np.ndarray]: List of control point arrays, each of shape [4, N]
|
326 |
+
where N is the number of points for that segment
|
327 |
+
"""
|
328 |
+
ctrl_points = []
|
329 |
+
for ctrl_pts in get_gripper_visualization_control_points(gripper_name):
|
330 |
+
ctrl_pts = np.array(ctrl_pts, dtype=np.float32)
|
331 |
+
ctrl_pts = np.hstack([ctrl_pts, np.ones([len(ctrl_pts),1])])
|
332 |
+
ctrl_pts = ctrl_pts.T
|
333 |
+
ctrl_points.append(ctrl_pts)
|
334 |
+
return ctrl_points
|
335 |
+
|
336 |
+
|
337 |
+
def visualize_grasp(
|
338 |
+
vis: meshcat.Visualizer,
|
339 |
+
name: str,
|
340 |
+
transform: np.ndarray,
|
341 |
+
color: List[int] = [255, 0, 0],
|
342 |
+
gripper_name: str = "franka",
|
343 |
+
**kwargs: Any
|
344 |
+
) -> None:
|
345 |
+
"""
|
346 |
+
Visualize a gripper grasp pose in meshcat.
|
347 |
+
|
348 |
+
Args:
|
349 |
+
vis (meshcat.Visualizer): Meshcat visualizer instance
|
350 |
+
name (str): Name/path for the grasp in the visualizer scene
|
351 |
+
transform (np.ndarray): 4x4 homogeneous transform matrix for the grasp pose
|
352 |
+
color (List[int]): RGB color values [0-255] for the grasp visualization
|
353 |
+
gripper_name (str): Name of the gripper to visualize
|
354 |
+
**kwargs: Additional arguments passed to MeshBasicMaterial
|
355 |
+
"""
|
356 |
+
if vis is None:
|
357 |
+
return
|
358 |
+
grasp_vertices = load_visualization_gripper_points(gripper_name)
|
359 |
+
for i, grasp_vertex in enumerate(grasp_vertices):
|
360 |
+
vis[name + f"/{i}"].set_object(
|
361 |
+
g.Line(
|
362 |
+
g.PointsGeometry(grasp_vertex),
|
363 |
+
g.MeshBasicMaterial(color=rgb2hex(tuple(color)), **kwargs),
|
364 |
+
)
|
365 |
+
)
|
366 |
+
vis[name].set_transform(transform.astype(np.float64))
|
scripts/visualize_dataset.py
ADDED
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
|
2 |
+
#
|
3 |
+
# NVIDIA CORPORATION and its licensors retain all intellectual property
|
4 |
+
# and proprietary rights in and to this software, related documentation
|
5 |
+
# and any modifications thereto. Any use, reproduction, disclosure or
|
6 |
+
# distribution of this software and related documentation without an express
|
7 |
+
# license agreement from NVIDIA CORPORATION is strictly prohibited.
|
8 |
+
#
|
9 |
+
'''
|
10 |
+
Visualize the data with both the object mesh and its corresponding grasps, using meshcat.
|
11 |
+
|
12 |
+
Installation:
|
13 |
+
pip install trimesh==4.5.3 objaverse==0.1.7 meshcat==0.0.12 webdataset==0.2.111
|
14 |
+
|
15 |
+
Usage:
|
16 |
+
|
17 |
+
Before running the script, start the meshcat server in a different terminal:
|
18 |
+
meshcat-server
|
19 |
+
|
20 |
+
To visualize a single object from the dataset:
|
21 |
+
python visualize_dataset.py --dataset_path /path/to/dataset --object_uuid {object_uuid} --object_file /path/to/mesh --gripper_name {choose from: franka, suction, robotiq2f140}
|
22 |
+
|
23 |
+
To visualize many objects (one at a time) from the dataset
|
24 |
+
python visualize_dataset.py --dataset_path /path/to/dataset --uuid_list /path/to/uuid_list.json --gripper_name {choose from: franka, suction, robotiq2f140} --uuid_object_paths_file /path/to/uuid_object_paths_file.json
|
25 |
+
|
26 |
+
NOTE:
|
27 |
+
- The uuid_object_paths_file is a json file, that contains a dictionary with a mapping from the UUID to the absolute path of the mesh file. if you are using the download_objaverse.py script, this file will be auto-generated.
|
28 |
+
- The uuid_list can be the split json file from the GraspGen dataset
|
29 |
+
- The gripper_name has to be one of the following: franka, suction, robotiq2f140
|
30 |
+
'''
|
31 |
+
|
32 |
+
import os
|
33 |
+
import argparse
|
34 |
+
import trimesh
|
35 |
+
import numpy as np
|
36 |
+
import json
|
37 |
+
from meshcat_utils import create_visualizer, visualize_mesh, visualize_grasp
|
38 |
+
from dataset import GraspWebDatasetReader, load_uuid_list
|
39 |
+
|
40 |
+
def visualize_mesh_with_grasps(
|
41 |
+
mesh_path: str,
|
42 |
+
mesh_scale: float,
|
43 |
+
gripper_name: str = "franka",
|
44 |
+
grasps: list[np.ndarray] = None,
|
45 |
+
color: list = [192, 192, 192],
|
46 |
+
transform: np.ndarray = None,
|
47 |
+
max_grasps_to_visualize: int = 20
|
48 |
+
):
|
49 |
+
"""
|
50 |
+
Visualize a single mesh with optional grasps using meshcat.
|
51 |
+
|
52 |
+
Args:
|
53 |
+
mesh_path (str): Path to the mesh file
|
54 |
+
mesh_scale (float): Scale factor for the mesh
|
55 |
+
gripper_name (str): Name of the gripper to visualize ("franka", "suction", etc.)
|
56 |
+
grasps (list[np.ndarray], optional): List of 4x4 grasp transforms
|
57 |
+
color (list, optional): RGB color for the mesh. Defaults to gray if None
|
58 |
+
transform (np.ndarray, optional): 4x4 transform matrix for the mesh. Defaults to identity if None
|
59 |
+
max_grasps_to_visualize (int, optional): Maximum number of grasps to visualize. Defaults to 20
|
60 |
+
"""
|
61 |
+
# Create visualizer
|
62 |
+
vis = create_visualizer()
|
63 |
+
vis.delete()
|
64 |
+
|
65 |
+
# Default transform if none provided
|
66 |
+
if transform is None:
|
67 |
+
transform = np.eye(4)
|
68 |
+
|
69 |
+
# Load and visualize the mesh
|
70 |
+
try:
|
71 |
+
transform = transform.astype(np.float64)
|
72 |
+
mesh = trimesh.load(mesh_path)
|
73 |
+
if type(mesh) == trimesh.Scene:
|
74 |
+
mesh = mesh.dump(concatenate=True)
|
75 |
+
mesh.apply_scale(mesh_scale)
|
76 |
+
|
77 |
+
T_move_mesh_to_origin = np.eye(4)
|
78 |
+
T_move_mesh_to_origin[:3, 3] = -mesh.centroid
|
79 |
+
|
80 |
+
transform = transform @ T_move_mesh_to_origin
|
81 |
+
|
82 |
+
visualize_mesh(vis, 'mesh', mesh, color=color, transform=transform)
|
83 |
+
except Exception as e:
|
84 |
+
print(f"Error loading mesh from {mesh_path}: {e}")
|
85 |
+
|
86 |
+
# Visualize grasps if provided
|
87 |
+
if grasps is not None:
|
88 |
+
for i, grasp in enumerate(np.random.permutation(grasps)[:max_grasps_to_visualize]):
|
89 |
+
visualize_grasp(
|
90 |
+
vis,
|
91 |
+
f"grasps/{i:03d}",
|
92 |
+
transform @ grasp.astype(np.float),
|
93 |
+
[0, 255, 0],
|
94 |
+
gripper_name=gripper_name,
|
95 |
+
linewidth=0.2
|
96 |
+
)
|
97 |
+
|
98 |
+
|
99 |
+
def parse_args():
|
100 |
+
parser = argparse.ArgumentParser()
|
101 |
+
parser.add_argument("--dataset_path", type=str, required=True)
|
102 |
+
parser.add_argument("--object_uuid", type=str, help="The UUID of the object to visualize", default=None)
|
103 |
+
parser.add_argument("--uuid_list", type=str, help="Path to UUID list", default=None)
|
104 |
+
parser.add_argument("--uuid_object_paths_file", type=str, help="Path to JSON file, mapping UUID to absolute path of the mesh file", default=None)
|
105 |
+
parser.add_argument("--object_file", type=str, help="This has to be a .stl or .obj or .glb file", default=None)
|
106 |
+
parser.add_argument("--gripper_name", type=str, required=True, help="Specify the gripper name", choices=["franka", "suction", "robotiq2f140"])
|
107 |
+
parser.add_argument("--max_grasps_to_visualize", type=int, help="The max number of grasps to visualize", default=20)
|
108 |
+
return parser.parse_args()
|
109 |
+
|
110 |
+
if __name__ == "__main__":
|
111 |
+
args = parse_args()
|
112 |
+
assert args.object_uuid is not None or args.uuid_list is not None, "Either object_uuid or uuid_list must be provided"
|
113 |
+
|
114 |
+
if args.object_uuid is not None:
|
115 |
+
webdataset_reader = GraspWebDatasetReader(os.path.join(args.dataset_path, args.gripper_name))
|
116 |
+
uuid_list = [args.object_uuid,]
|
117 |
+
object_paths = [args.object_file,]
|
118 |
+
assert args.object_file is not None, "object_file must be provided if object_uuid is provided"
|
119 |
+
assert os.path.exists(args.object_file), f"Object file {args.object_file} does not exist"
|
120 |
+
else:
|
121 |
+
assert os.path.exists(args.uuid_list), f"UUID list {args.uuid_list} does not exist"
|
122 |
+
uuid_list = load_uuid_list(args.uuid_list)
|
123 |
+
assert args.uuid_object_paths_file is not None, "uuid_object_paths_file must be provided if uuid_list is provided"
|
124 |
+
assert os.path.exists(args.uuid_object_paths_file), f"UUID object paths file {args.uuid_object_paths_file} does not exist"
|
125 |
+
object_paths = json.load(open(args.uuid_object_paths_file))
|
126 |
+
object_paths = [object_paths[uuid] for uuid in uuid_list]
|
127 |
+
webdataset_reader = GraspWebDatasetReader(os.path.join(args.dataset_path, args.gripper_name))
|
128 |
+
|
129 |
+
for uuid, object_path in zip(uuid_list, object_paths):
|
130 |
+
print(f"Visualizing object {uuid}")
|
131 |
+
grasp_data = webdataset_reader.read_grasps_by_uuid(uuid)
|
132 |
+
object_scale = grasp_data['object']['scale']
|
133 |
+
grasps = grasp_data["grasps"]
|
134 |
+
grasp_poses = np.array(grasps["transforms"])
|
135 |
+
grasp_mask = np.array(grasps["object_in_gripper"])
|
136 |
+
positive_grasps = grasp_poses[grasp_mask] # Visualizing only the positive grasps
|
137 |
+
|
138 |
+
if len(positive_grasps) > 0:
|
139 |
+
# Visualize the mesh with the grasps
|
140 |
+
visualize_mesh_with_grasps(
|
141 |
+
mesh_path=object_path,
|
142 |
+
mesh_scale=object_scale,
|
143 |
+
grasps=positive_grasps,
|
144 |
+
gripper_name=args.gripper_name,
|
145 |
+
max_grasps_to_visualize=args.max_grasps_to_visualize,
|
146 |
+
)
|
147 |
+
print("Press Enter to continue...")
|
148 |
+
input()
|