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