Datasets:

Modalities:
Image
Text
Formats:
parquet
ArXiv:
License:
MTJester commited on
Commit
58d236b
·
verified ·
1 Parent(s): 537ec9a

Upload example_usage.py

Browse files
Files changed (1) hide show
  1. example_usage.py +262 -0
example_usage.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ CHIP Dataset Usage Example
3
+
4
+ This script demonstrates how to load and visualize data from the CHIP dataset,
5
+ including RGB images, depth maps, camera parameters, and 3D object models.
6
+
7
+ Requirements:
8
+ pip install datasets huggingface_hub numpy opencv-python open3d torch
9
+ """
10
+
11
+ import json
12
+ import os
13
+ import gc
14
+ from typing import Tuple, Optional
15
+
16
+ import numpy as np
17
+ import cv2
18
+ import open3d as o3d
19
+ import torch
20
+ from datasets import load_dataset, get_dataset_infos
21
+ from huggingface_hub import snapshot_download
22
+
23
+
24
+ def lift_point_cloud(
25
+ depth: torch.Tensor,
26
+ camera_intrinsics: torch.Tensor,
27
+ xy_indices: Optional[Tuple[torch.Tensor, torch.Tensor]] = None
28
+ ) -> torch.Tensor:
29
+ """
30
+ Lift a depth image to a 3D point cloud using camera intrinsics.
31
+
32
+ Args:
33
+ depth: Depth image tensor of shape (H, W, C) where C >= 1.
34
+ If C > 1, channels 1+ are treated as features (e.g., RGB).
35
+ camera_intrinsics: Flattened camera intrinsic matrix [fx, 0, cx, 0, fy, cy, 0, 0, 1].
36
+ xy_indices: Optional tuple of (x_coords, y_coords) to lift only specific pixels.
37
+
38
+ Returns:
39
+ Point cloud tensor of shape (N, 3+F) where F is the number of feature channels.
40
+ First 3 columns are XYZ coordinates, remaining columns are features.
41
+ """
42
+ H, W, num_channels = depth.shape
43
+ depth_values = depth[:, :, 0]
44
+
45
+ if xy_indices is not None:
46
+ x_coords, y_coords = xy_indices
47
+ x_coords = x_coords.to(depth_values.device).float()
48
+ y_coords = y_coords.to(depth_values.device).float()
49
+ z_coords = depth_values[y_coords.long(), x_coords.long()]
50
+ else:
51
+ # Create pixel coordinate grids
52
+ x_grid, y_grid = np.meshgrid(
53
+ np.arange(W, dtype=np.float32),
54
+ np.arange(H, dtype=np.float32),
55
+ indexing='xy'
56
+ )
57
+ x_coords = torch.from_numpy(x_grid).flatten().to(depth_values.device)
58
+ y_coords = torch.from_numpy(y_grid).flatten().to(depth_values.device)
59
+ z_coords = depth_values.flatten()
60
+
61
+ # Extract camera intrinsics
62
+ fx, fy = camera_intrinsics[0], camera_intrinsics[4]
63
+ cx, cy = camera_intrinsics[2], camera_intrinsics[5]
64
+
65
+ # Back-project to 3D coordinates
66
+ x_3d = (x_coords - cx) * z_coords / fx
67
+ y_3d = (y_coords - cy) * z_coords / fy
68
+ points_3d = torch.stack([x_3d, y_3d, z_coords], dim=1)
69
+
70
+ # Add additional features (e.g., RGB) if present
71
+ if num_channels > 1:
72
+ features = depth[y_coords.long(), x_coords.long(), 1:]
73
+ if xy_indices is None:
74
+ features = features.reshape(H * W, num_channels - 1)
75
+ points_3d = torch.cat([points_3d, features], dim=1)
76
+
77
+ return points_3d
78
+
79
+
80
+ def back_project_rgbd(
81
+ rgb: np.ndarray,
82
+ depth: np.ndarray,
83
+ camera_intrinsics: np.ndarray
84
+ ) -> torch.Tensor:
85
+ """
86
+ Back-project RGB-D image to a colored point cloud.
87
+
88
+ Args:
89
+ rgb: RGB image array of shape (H, W, 3).
90
+ depth: Depth map array of shape (H, W) with values in meters.
91
+ camera_intrinsics: Flattened 3x3 camera intrinsic matrix.
92
+
93
+ Returns:
94
+ Point cloud tensor of shape (N, 6) with XYZ and RGB columns.
95
+ """
96
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
97
+
98
+ # Get valid depth pixel coordinates
99
+ valid_rows, valid_cols = np.where(depth > 0)
100
+ xy_indices = torch.tensor(
101
+ np.stack([valid_cols, valid_rows]),
102
+ dtype=torch.long,
103
+ device=device
104
+ )
105
+
106
+ # Concatenate depth and RGB channels
107
+ depth_rgb = torch.cat([
108
+ torch.from_numpy(depth).unsqueeze(-1),
109
+ torch.from_numpy(rgb)
110
+ ], dim=2).to(device)
111
+
112
+ # Lift to 3D point cloud
113
+ camera_tensor = torch.from_numpy(camera_intrinsics).to(device)
114
+ point_cloud = lift_point_cloud(depth_rgb, camera_tensor, tuple(xy_indices))
115
+
116
+ return point_cloud
117
+
118
+
119
+ def visualize_chip_sample(
120
+ repo_id: str = "FBK-TeV/CHIP",
121
+ target_dir: str = "./chip_data",
122
+ num_samples: int = 1,
123
+ show_2d: bool = False
124
+ ) -> None:
125
+ """
126
+ Load and visualize samples from the CHIP dataset.
127
+
128
+ Args:
129
+ repo_id: Hugging Face dataset repository ID.
130
+ target_dir: Local directory to store downloaded model files.
131
+ num_samples: Number of samples to visualize.
132
+ show_2d: If True, display RGB and depth images in OpenCV windows.
133
+ If False, only show 3D point cloud visualization.
134
+ """
135
+ # Display dataset information
136
+ info = get_dataset_infos(repo_id)
137
+ print(f"Dataset info: {info}\n")
138
+
139
+ # Download 3D object models
140
+ print("Downloading 3D models...")
141
+ local_path = snapshot_download(
142
+ repo_id=repo_id,
143
+ repo_type="dataset",
144
+ local_dir=target_dir,
145
+ allow_patterns=["models/*"]
146
+ )
147
+ print(f"Models downloaded to: {local_path}\n")
148
+
149
+ # Stream dataset samples
150
+ dataset = load_dataset(repo_id, streaming=True)
151
+
152
+ for idx, example in enumerate(dataset['test'].take(num_samples)):
153
+ print(f"Processing sample {idx + 1}/{num_samples}...")
154
+
155
+ # ========== Load RGB Image ==========
156
+ rgb_image = np.array(example['image'])
157
+ rgb_bgr = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2BGR)
158
+
159
+ # ========== Load Depth Map ==========
160
+ depth_map = np.array(example['depth'], dtype=np.uint16).astype(np.float32)
161
+
162
+ # Visualize depth for display
163
+ depth_vis = cv2.normalize(depth_map, None, 0, 255, cv2.NORM_MINMAX)
164
+ depth_vis = depth_vis.astype(np.uint8)
165
+
166
+ # ========== Parse Camera Parameters ==========
167
+ camera_params = json.loads(example['camera_params'])
168
+ intrinsics_matrix = np.array(camera_params['cam_K']).reshape(3, 3)
169
+ depth_scale = camera_params['depth_scale']
170
+
171
+ print(f"Camera intrinsics:\n{intrinsics_matrix}")
172
+ print(f"Depth scale: {depth_scale}")
173
+
174
+ # ========== Parse Object Labels ==========
175
+ labels = json.loads(example['labels'])
176
+ label = labels[0] # Process first object
177
+
178
+ rotation_matrix = np.array(label['cam_R_m2c_flat']).reshape(3, 3)
179
+ translation_vector = np.array(label['cam_t_m2c'])
180
+ bbox = [
181
+ label['bbox_x'],
182
+ label['bbox_y'],
183
+ label['bbox_width'],
184
+ label['bbox_height']
185
+ ]
186
+
187
+ print(f"\nObject ID: {label['obj_id']}")
188
+ print(f"Rotation matrix:\n{rotation_matrix}")
189
+ print(f"Translation vector: {translation_vector}")
190
+ print(f"Bounding box (x, y, w, h): {bbox}\n")
191
+
192
+ # ========== Visualize 2D ==========
193
+ if show_2d:
194
+ x, y, w, h = bbox
195
+ rgb_with_bbox = rgb_bgr.copy()
196
+ cv2.rectangle(rgb_with_bbox, (x, y), (x + w, y + h), (0, 255, 0), 2)
197
+
198
+ cv2.imshow("RGB Image", rgb_with_bbox)
199
+ cv2.imshow("Depth Map", depth_vis)
200
+ print("Displaying 2D images (press any key to continue to 3D)...")
201
+ cv2.waitKey(0)
202
+
203
+ # ========== Create 3D Point Cloud ==========
204
+ depth_metric = depth_map * depth_scale
205
+ point_cloud = back_project_rgbd(rgb_image, depth_metric, intrinsics_matrix.flatten())
206
+
207
+ # Convert to Open3D format
208
+ pcd_o3d = o3d.geometry.PointCloud()
209
+ pcd_o3d.points = o3d.utility.Vector3dVector(point_cloud[:, :3].cpu().numpy())
210
+ if point_cloud.shape[1] > 3:
211
+ pcd_o3d.colors = o3d.utility.Vector3dVector(
212
+ point_cloud[:, 3:].cpu().numpy() / 255.0
213
+ )
214
+
215
+ # ========== Load and Transform 3D Model ==========
216
+ model_path = os.path.join(target_dir, "models", f"obj_{label['obj_id']:06d}.ply")
217
+ model_mesh = o3d.io.read_triangle_mesh(model_path)
218
+ model_mesh.paint_uniform_color([1.0, 0.0, 0.0]) # Red
219
+
220
+ # Apply pose transformation
221
+ pose_matrix = np.eye(4)
222
+ pose_matrix[:3, :3] = rotation_matrix
223
+ pose_matrix[:3, 3] = translation_vector
224
+ model_mesh.transform(pose_matrix)
225
+
226
+ # ========== Visualize 3D ==========
227
+ print("Displaying 3D visualization (close window to continue)...")
228
+ o3d.visualization.draw_geometries(
229
+ [pcd_o3d, model_mesh],
230
+ window_name=f"CHIP Sample {idx + 1}: Scene + Model (Red)"
231
+ )
232
+
233
+ if show_2d:
234
+ cv2.destroyAllWindows()
235
+ else:
236
+ # Small delay to prevent visualization from closing too quickly
237
+ cv2.waitKey(100)
238
+
239
+ # Cleanup
240
+ del dataset
241
+ gc.collect()
242
+ print("\nVisualization complete!")
243
+
244
+
245
+ if __name__ == "__main__":
246
+ # Example usage
247
+
248
+ # Option 1: Show both 2D images and 3D point cloud
249
+ visualize_chip_sample(
250
+ repo_id="FBK-TeV/CHIP",
251
+ target_dir="./chip_data",
252
+ num_samples=1,
253
+ show_2d=True # Display RGB and depth images
254
+ )
255
+
256
+ # Option 2: Show only 3D point cloud visualization
257
+ # visualize_chip_sample(
258
+ # repo_id="FBK-TeV/CHIP",
259
+ # target_dir="./chip_data",
260
+ # num_samples=1,
261
+ # show_2d=False # Skip 2D visualization
262
+ # )