File size: 23,434 Bytes
6cf2c86 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 | import pickle
import os
import h5py
import numpy as np
import cv2
import json
import torch
import os
import subprocess
import shutil
def rgbd_to_pointcloud(rgb, depth, intrinsic, extrinsic):
height, width = depth.shape
fx, fy = intrinsic[0,0], intrinsic[1,1]
cx, cy = intrinsic[0,2], intrinsic[1,2]
# Create a mesh grid of pixel coordinates
u = np.arange(width)
v = np.arange(height)
u, v = np.meshgrid(u, v)
# Flatten the arrays
u = u.flatten()
v = v.flatten()
depth = depth.flatten()
# Filter out points with zero depth
valid = depth > 0
u = u[valid]
v = v[valid]
depth = depth[valid]
# Back-project to 3D camera coordinates
x = (u - cx) * depth / fx
y = (v - cy) * depth / fy
z = depth
points_camera = np.vstack((x, y, z)).T # Shape: (N, 3)
# Convert to homogeneous coordinates
points_camera_homogeneous = np.hstack((points_camera, np.ones((points_camera.shape[0], 1)))) # Shape: (N, 4)
# Transform to world coordinates
points_world_homogeneous = points_camera_homogeneous @ np.linalg.inv(extrinsic).T # Shape: (N, 4)
points_world = points_world_homogeneous[:, :3] / points_world_homogeneous[:, 3][:, np.newaxis] # Shape: (N, 3)
colors = rgb[v, u, :] # Shape: (N, 3)
return points_world, colors
def load_cameras_from_hdf5(dataset_path):
print(f"Loading dataset from {dataset_path}...")
if not os.path.isfile(dataset_path):
print(f"Dataset does not exist at \n{dataset_path}\n")
# exit()
raise FileNotFoundError(f"Dataset does not exist at \n{dataset_path}\n")
with h5py.File(dataset_path, "r") as root:
# def print_structure(name, obj):
# print(f"Name: {name}, Type: {'Group' if isinstance(obj, h5py.Group) else 'Dataset'}")
# root.visititems(print_structure)
# Name: observation/surround_camera_0, Type: Group
# Name: observation/surround_camera_0/cam2world_gl, Type: Dataset
# Name: observation/surround_camera_0/depth, Type: Dataset
# Name: observation/surround_camera_0/extrinsic_cv, Type: Dataset
# Name: observation/surround_camera_0/intrinsic_cv, Type: Dataset
# Name: observation/surround_camera_0/rgb, Type: Dataset
cam_dict = dict()
# import time
# time_start = time.time()
for cam_name in root[f"/observation/"].keys():
if "surround_camera_" in cam_name:
cam_dict[cam_name] = dict()
rgb_encoded = root[f"/observation/{cam_name}/rgb"][()]
depth_encoded = root[f"/observation/{cam_name}/depth"][()]
rgb = None
depth = None
for i in range(rgb_encoded.shape[0]):
_rgb_encoded = rgb_encoded[i].rstrip(b"\0")
rgb_decoded = cv2.imdecode(np.frombuffer(buffer=_rgb_encoded, dtype=np.uint8), flags=cv2.IMREAD_COLOR)
# rgb_decoded = cv2.cvtColor(rgb_decoded, cv2.COLOR_BGR2RGB)
rgb_decoded = np.ascontiguousarray(rgb_decoded,dtype=np.float32) / 255.0
_depth_encoded = depth_encoded[i].rstrip(b"\0")
depth_decoded = cv2.imdecode(np.frombuffer(buffer=_depth_encoded, dtype=np.uint8), flags=cv2.IMREAD_UNCHANGED)
depth_decoded = np.ascontiguousarray(depth_decoded,dtype=np.float32) / 1000.0
if rgb is None:
rgb = np.zeros((rgb_encoded.shape[0],) + rgb_decoded.shape, dtype=np.float32)
depth = np.zeros((depth_encoded.shape[0],) + depth_decoded.shape, dtype=np.float32)
rgb[i] = rgb_decoded
depth[i] = depth_decoded
cam_dict[cam_name]["rgb"] = rgb
cam_dict[cam_name]["depth"] = depth
cam_dict[cam_name]["intrinsic_cv"] = np.ascontiguousarray(root[f"/observation/{cam_name}/intrinsic_cv"][0],dtype=np.float64)
cam_dict[cam_name]["extrinsic_cv"] = np.eye(4, dtype=np.float64)
cam_dict[cam_name]["extrinsic_cv"][:3,:] = np.ascontiguousarray(root[f"/observation/{cam_name}/extrinsic_cv"][0],dtype=np.float64)
cam_dict[cam_name]["cam2world_gl"] = np.ascontiguousarray(root[f"/observation/{cam_name}/cam2world_gl"][0],dtype=np.float64)
# time_end = time.time()
# print(f"Loaded {len(cam_dict)} cameras, time cost: {time_end - time_start:.2f}s")
return cam_dict
# if __name__ == "__main__":
# for cam_name in cam_dict:
# print(f"Camera: {cam_name}")
# print(f"{cam_dict[cam_name]['intrinsic_cv']}")
# print(f"{cam_dict[cam_name]['extrinsic_cv']}")
# print(f"{cam_dict[cam_name]['cam2world_gl']}")
# print(f"RGB shape: {cam_dict[cam_name]['rgb'].shape}, Depth shape: {cam_dict[cam_name]['depth'].shape}")
# import open3d as o3d
# # do the pointcloud mapping
# pcds = []
# for cam_name in cam_dict:
# rgb = cam_dict[cam_name]["rgb"]
# depth = cam_dict[cam_name]["depth"]
# intrinsic_cv = cam_dict[cam_name]["intrinsic_cv"]
# extrinsic_cv = cam_dict[cam_name]["extrinsic_cv"]
# cam2world_gl = cam_dict[cam_name]["cam2world_gl"]
# points, colors = rgbd_to_pointcloud(rgb[0], depth[0], intrinsic_cv, extrinsic_cv)
# pcds += [o3d.geometry.PointCloud(o3d.utility.Vector3dVector(points))]
# pcds[-1].colors = o3d.utility.Vector3dVector(colors)
# # break
# # save the pointcloud to a ply file
# pcd = pcds[0]
# for i in range(1, len(pcds)):
# pcd += pcds[i]
# o3d.io.write_point_cloud("test.ply", pcd)
def find_data(base_path, max_episodes_per_task=None):
data_list = []
task_list = os.listdir(base_path)
task_episode_count = {}
for task_path in task_list:
# print(f"Processing task: {task_path}")
# print(os.path.join(base_path, task_path))
task_episode_count.setdefault(task_path, 0)
try:
embodiment_list = os.listdir(os.path.join(base_path, task_path))
for embodiment_path in embodiment_list:
try:
config_list = os.listdir(os.path.join(base_path, task_path, embodiment_path))
for config_path in config_list:
# print(f" Processing config: {config_path}")
scene_info_path = os.path.join(base_path, task_path, embodiment_path, config_path, "scene_info.json")
# print(f" scene_info_path: {scene_info_path}")
if not os.path.exists(scene_info_path):
print(f" scene_info_path {scene_info_path} does not exist, skip.")
continue
with open(scene_info_path, 'r') as f:
scene_info = json.load(f)
# print(scene_info)
for key, value in scene_info.items():
if (
max_episodes_per_task is not None
and task_episode_count[task_path] >= max_episodes_per_task
):
continue
data_dict = dict()
data_dict["data_path"] = os.path.join(base_path, task_path, embodiment_path, config_path, "data")
data_dict["episode_name"] = key.replace("_", "")
data_dict["instructions_path"] = os.path.join(base_path, task_path, embodiment_path, config_path, "instructions",f"{data_dict['episode_name']}.json")
data_dict["metadata_path"] = os.path.join(data_dict["data_path"], f"{data_dict['episode_name']}.json")
data_dict["jointdata_path"] = os.path.join(data_dict["data_path"], f"{data_dict['episode_name']}_joint_data.npz")
data_dict["cache_path"] = os.path.join(base_path, task_path, embodiment_path, config_path, "cache", f"{data_dict['episode_name']}")
if not os.path.exists(data_dict["metadata_path"]):
print(f" metadata_path {data_dict['metadata_path']} does not exist, skip.")
continue
data_list.append(data_dict)
task_episode_count[task_path] += 1
# for key in scene_info:
# if "file_name" in scene_info[key]:
# file_name = scene_info[key]["file_name"]
# text = scene_info[key]["text"]
except:
continue
except:
continue
print(f"Found {len(data_list)} data samples.")
return data_list
def get_valid_candidates(k, N, diff, hard_diff=None):
if hard_diff is not None:
if hard_diff <= 0:
raise ValueError("hard_diff must be a positive integer representing multiples of 30 degrees.")
all_indices = np.arange(N)
first = np.random.choice(all_indices)
selected_list = []
used = set()
for offset in range(k):
idx = (first + offset * hard_diff) % N
if idx in used:
raise ValueError(
f"hard_diff={hard_diff} does not provide {k} unique views for N={N}."
)
selected_list.append(idx)
used.add(idx)
selected_list.sort()
return selected_list
def circular_distance(a, b, N):
return np.minimum(np.abs(a - b), N - np.abs(a - b))
all_indices = np.arange(N)
# print("All indices:", all_indices)
selected_list = []
# random select first index from all indices
first = np.random.choice(all_indices)
selected_list.append(first)
for _ in range(k-1):
available_indices = []
for idx in all_indices:
if idx in selected_list:
continue
distances = [circular_distance(idx, sel, N) for sel in selected_list]
if not all(dist > diff for dist in distances):
available_indices.append(idx)
if len(available_indices) == 0:
raise ValueError("No valid candidates available to select.")
selected_list.append(np.random.choice(available_indices))
selected_list.sort()
far_view_idx = None
for idx in all_indices:
if idx in selected_list:
continue
distances = [circular_distance(idx, sel, N) for sel in selected_list]
# print("Index:", idx, "Distances:", distances)
min_2_distances = sorted(distances)[:2]
min_dist = min_2_distances[0] + min_2_distances[1]
if min_dist > diff:
# available_indices.append(idx)
far_view_idx = idx
break
# print("Selected list before rearranging:", selected_list)
# print("Far view index:", far_view_idx)
if far_view_idx is not None:
start_idx = far_view_idx
while True:
if start_idx in selected_list:
break
start_idx = (start_idx + 1) % N
# print("Adjusted start index:", start_idx)
# rearramge the list to let start_idx be the first
start_pos = selected_list.index(start_idx)
selected_list = selected_list[start_pos:] + selected_list[:start_pos]
return selected_list
# if __name__ == "__main__":
# # task_list = os.listdir(base_path)
# find_data(base_path)
def image_to_float_array(images, scale_factor=None):
if not isinstance(images, np.ndarray):
# images = np.array(images)
images = np.array(images, dtype=np.float32)
r = images[..., 0]
g = images[..., 1]
b = images[..., 2]
# print (r.min(), r.max(), g.min(), g.max(), b.min(), b.max())
# print(image_array.shape)
# RGB image needs to be converted to 24 bit integer.
# float_array = np.sum(image_array * [0, 256, 0], axis=-1)
float_array = r * 65536.0 + g *256.0 + b * 1.0
if scale_factor is None:
scale_factor = 256000.0
scaled_array = float_array / scale_factor
return scaled_array
def get_instructions(instructions_file_path, num=3):
instructions = []
with open(instructions_file_path, 'r') as f:
instructions_dict = json.load(f)
num_instructions = len(instructions_dict["seen"])
# ids = np.random.choice(num_instructions, num, replace=False)
ids = range(num)
# print(ids)
# select the instructions according to the ids
instructions = instructions_dict["seen"]
instructions = [instructions[i] for i in ids]
return instructions
def sample_frame_indices(total_frames: int, target_frames: int = 81) -> list:
# if total_frames <= target_frames:
# raise ValueError("Total frames must be greater than the number of target frames (81).")
# use linspace to generate evenly spaced indices
indices = np.linspace(0, total_frames - 1, target_frames)
# round and convert to integer indices
indices = np.round(indices).astype(int)
indices = np.clip(indices, 0, total_frames - 1)
return indices.tolist()
def backproject_depth_to_cam_xyz(depth_t: torch.Tensor,
K: torch.Tensor) -> torch.Tensor:
"""
depth_t: [B, H, W]
K: [3, 3]
E: [4, 4]
"""
device = depth_t.device
dtype = depth_t.dtype
B, H, W = depth_t.shape
if K.dim() == 2: # [3,3] -> [B,3,3]
K = K.to(device=device, dtype=dtype).unsqueeze(0).expand(B, -1, -1)
else:
K = K.to(device=device, dtype=dtype)
assert K.shape[0] == B, "Batch K expects shape [B,3,3]"
fx = K[:, 0, 0].view(B, 1, 1)
fy = K[:, 1, 1].view(B, 1, 1)
cx = K[:, 0, 2].view(B, 1, 1)
cy = K[:, 1, 2].view(B, 1, 1)
u = torch.arange(W, device=device, dtype=dtype).view(1, 1, W).expand(B, H, W)
v = torch.arange(H, device=device, dtype=dtype).view(1, H, 1).expand(B, H, W)
z = depth_t # [B,H,W]
valid = z > 0
Xc = (u - cx) / fx * z
Yc = (v - cy) / fy * z
Zc = z
Pc = torch.stack([Xc, Yc, Zc], dim=0) #[3, T, H, W]
Pc = torch.where(valid.unsqueeze(0), Pc, torch.ones_like(Pc)*10) # filter out depth error
# ones = torch.ones_like(Zc)
# Pc = torch.stack([Xc, Yc, Zc, ones], dim=1).reshape(B, 4, -1) # [B,3,N]
# c2w = torch.linalg.inv(E)
# Pw = torch.bmm(c2w, Pc)[:, :3]
# Pw = Pw.view(B, 3, H, W) # [B,3,H,W]
# Pw = torch.where(valid.unsqueeze(1), Pw, torch.ones_like(Pw)*10000)
return Pc
def normalize_xyz_to_NDC(xyz: torch.Tensor, ortho_bound, eps: float = 1e-6) -> torch.Tensor:
"""
xyz: [3, T, H, W]
"""
l, r = ortho_bound['l'], ortho_bound['r']
b, t = ortho_bound['b'], ortho_bound['t']
n, f = ortho_bound['n'], ortho_bound['f']
# rx, ry = ortho_bound['rx'], ortho_bound['ry']
rx = max(r - l, eps)
ry = max(t - b, eps)
rz = max(abs(f - n), eps)
x_ndc = (2.0 * xyz[0] - (r + l)) / (rx)
y_ndc = (2.0 * xyz[1] - (t + b)) / (ry)
z_ndc = (2.0 * xyz[2] - (f + n)) / ( (n - f) if (n - f) != 0 else 1e-8 )
return torch.stack([x_ndc, y_ndc, z_ndc], dim=0)
# def inv_ortho_ndc_to_cam(ndc_xyz, l,r,b,t,n,f):
# x = 0.5*(r-l)*ndc_xyz[...,0] + 0.5*(r+l)
# y = 0.5*(t-b)*ndc_xyz[...,1] + 0.5*(t+b)
# z = -0.5*(f-n)*ndc_xyz[...,2] + 0.5*(f+n)
# return torch.stack([x,y,z], dim=-1)
def inv_ortho_ndc_to_cam(ndc_xyz, l,r,b,t,n,f, eps: float = 1e-6):
rx = r - l
ry = t - b
rz = n - f
x = 0.5 * rx * ndc_xyz[...,0] + 0.5 * (r + l)
y = 0.5 * ry * ndc_xyz[...,1] + 0.5 * (t + b)
z = 0.5 * rz * ndc_xyz[...,2] + 0.5 * (f + n)
return torch.stack([x,y,z], dim=-1)
class Camera(object):
def __init__(self, c2w=None, w2c=None):
assert (c2w is not None) or (w2c is not None), "Either c2w or w2c must be provided."
if c2w is None:
c2w = np.linalg.inv(w2c)
elif w2c is None:
w2c = np.linalg.inv(c2w)
self.c2w_mat = c2w
self.w2c_mat = w2c
def images_to_video(imgs: np.ndarray, out_path: str, fps: float = 30.0, is_rgb: bool = True) -> None:
if (not isinstance(imgs, np.ndarray) or imgs.ndim != 4 or imgs.shape[3] not in (3, 4)):
raise ValueError("imgs must be a numpy.ndarray of shape (N, H, W, C), with C equal to 3 or 4.")
os.makedirs(os.path.dirname(out_path), exist_ok=True)
n_frames, H, W, C = imgs.shape
if C == 3:
pixel_format = "rgb24" if is_rgb else "bgr24"
else:
pixel_format = "rgba"
ffmpeg = subprocess.Popen(
[
"ffmpeg",
"-y",
"-loglevel",
"error",
"-f",
"rawvideo",
"-pixel_format",
pixel_format,
"-video_size",
f"{W}x{H}",
"-framerate",
str(fps),
"-i",
"-",
"-pix_fmt",
"yuv420p",
"-vcodec",
"libx264",
"-crf",
"23",
f"{out_path}",
],
stdin=subprocess.PIPE,
)
ffmpeg.stdin.write(imgs.tobytes())
ffmpeg.stdin.close()
if ffmpeg.wait() != 0:
raise IOError(f"Cannot open ffmpeg. Please check the output path and ensure ffmpeg is supported.")
# print(
# f"🎬 Video is saved to `{out_path}`, containing \033[94m{n_frames}\033[0m frames at {W}×{H} resolution and {fps} FPS."
# )
def back_up_codes(src_dir, dst_dir, exclude_dirs=['__pycache__', '.git', 'data', 'logs', '.vscode']):
os.makedirs(dst_dir, exist_ok=True)
if exclude_dirs is None:
exclude_dirs = []
if not os.path.exists(dst_dir):
os.makedirs(dst_dir)
for item in os.listdir(src_dir):
if item in exclude_dirs:
continue
s = os.path.join(src_dir, item)
d = os.path.join(dst_dir, item)
if os.path.isdir(s):
back_up_codes(s, d, exclude_dirs)
else:
if s.endswith('.py') or s.endswith('.json') or s.endswith('.md'):
shutil.copy2(s, d)
def find_rlbench_data(base_path):
data_list = []
task_list = os.listdir(base_path)
scene_data_path = os.path.join(base_path, "scene_data.npz")
if not os.path.exists(scene_data_path):
print(f" rlbench: \t scene_data_path {scene_data_path} does not exist.")
raise FileNotFoundError(f" rlbench: \t scene_data_path {scene_data_path} does not exist.")
episode_num_list = {}
for task_path in task_list:
# print(f"Processing task: {task_path}")
# print(os.path.join(base_path, task_path))
try:
# embodiment_list = os.listdir(os.path.join(base_path, task_path))
variant_list = os.listdir(os.path.join(base_path, task_path))
episode_num_list[task_path] = 0
for variant_path in variant_list:
# for embodiment_path in embodiment_list:
# try:
variation_description_path = os.path.join(base_path, task_path, variant_path, "variation_descriptions.pkl")
# print(f" rlbench: \t processing variation_description_path: {variation_description_path}")
if not os.path.exists(variation_description_path):
print(f" rlbench: \t variation_description_path {variation_description_path} does not exist, skip.")
continue
else:
# print(f" rlbench: \t found variation_description_path: {variation_description_path}")
with open(variation_description_path, 'rb') as f:
variation_descriptions = pickle.load(f)
# print(f" rlbench: \t variation_descriptions for {variant_path}: {variation_descriptions}")
# config_list = os.listdir(os.path.join(base_path, task_path, embodiment_path))
episode_list: list[str] = os.listdir(os.path.join(base_path, task_path, variant_path, 'episodes'))
for episode_path in episode_list:
# print(f" Processing config: {config_path}")
# scene_info_path = os.path.join(base_path, task_path, embodiment_path, config_path, "scene_info.json")
data_path = os.path.join(base_path, task_path, variant_path, 'episodes', episode_path)
low_dim_path = os.path.join(data_path, 'low_dim_obs.npz')
# print(f" rlbench: \t processing low_dim_path: {low_dim_path}")
if not os.path.exists(low_dim_path):
print(f" rlbench: \t low_dim_path {low_dim_path} does not exist, skip.")
continue
# with open(low_dim_path, 'rb') as f:
# print(f" rlbench: \t processing low_dim_path: {low_dim_path}")
# low_dim_obs = pickle.load(f)
# print(f" rlbench: \t low_dim_obs keys: {low_dim_obs.keys()}")
# with open(scene_info_path, 'r') as f:
# scene_info = json.load(f)
# print(scene_info)
# for key, value in scene_info.items():
data_dict = dict()
data_dict["data_path"] = data_path
data_dict["episode_name"] = episode_path
data_dict["variation_name"] = variant_path
data_dict["instructions_path"] = variation_description_path
# data_dict["metadata_path"] = os.path.join(data_dict["data_path"], f"{data_dict['episode_name']}.json")
data_dict["jointdata_path"] = low_dim_path
data_dict["cache_path"] = os.path.join(base_path, task_path, variant_path, "cache", f"{data_dict['episode_name']}")
data_dict["task_name"] = task_path
data_dict["scene_data_path"] = scene_data_path
data_list.append(data_dict)
episode_num_list[task_path] += 1
# for key in scene_info:
# if "file_name" in scene_info[key]:
# file_name = scene_info[key]["file_name"]
# text = scene_info[key]["text"]
# except:
# continue
except:
continue
for task_name, episode_num in episode_num_list.items():
print(f" Task: {task_name}, Episode num: {episode_num}")
print(f"Found {len(data_list)} data samples.")
return data_list
def get_instructions_rlbench(instructions_file_path):
with open(instructions_file_path, 'rb') as f:
variation_descriptions = pickle.load(f)
return variation_descriptions
|