# import pickle # import zarr # import numpy as np # import os # from tqdm import tqdm # def detect_episode_boundaries(data): # """精确检测episode边界""" # boundaries = [i for i, d in enumerate(data) if d.get('dones', False)] # if not boundaries or boundaries[-1] != len(data)-1: # boundaries.append(len(data)-1) # return boundaries # def convert_pkl_to_zarr(pkl_path, zarr_path): # # 加载数据 # with open(pkl_path, 'rb') as f: # data = pickle.load(f) # # 检测真实episode边界 # episode_ends = detect_episode_boundaries(data) # episode_ends = [x + 1 for x in episode_ends] # print(f"检测到 {len(episode_ends)} 个episode,边界索引: {episode_ends}") # # 初始化zarr存储 # if os.path.exists(zarr_path): # import shutil # shutil.rmtree(zarr_path) # root = zarr.open_group(zarr_path, mode='w') # data_group = root.create_group('data') # meta_group = root.create_group('meta') # # 数据容器 # all_actions = [] # all_states = [] # all_side_image = [] # side_classifier # all_wrist_image = [] # # 处理每个step(只保留next_observations的第二个视角) # for step in tqdm(data, desc="Processing steps"): # obs = step['observations'] # all_side_image.append(obs['side_policy_256'][0]) # (256,256,3) # # all_wrist_image.append(obs['wrist_224'][0]) # (128,128,3) # all_states.append(obs['state'][0]) # (19,) # all_actions.append(step['actions']) # # 转换为numpy数组 # actions = np.array(all_actions, dtype=np.float64) # states = np.array(all_states, dtype=np.float32) # side_images = np.array(all_side_image, dtype=np.uint8) # (N,128,128,3) # wrist_images = np.array(all_wrist_image, dtype=np.uint8) # # 存储数据(使用高效压缩) # compressor = zarr.Blosc(cname='zstd', clevel=3, shuffle=1) # data_group.array('action', actions, chunks=(100,7), compressor=compressor) # data_group.array('state', states, chunks=(100,19), compressor=compressor) # data_group.array('side_image', side_images, chunks=(100,256,256,3), compressor=compressor) # # data_group.array('wrist_image', wrist_images, chunks=(100,224,224,3), compressor=compressor) # meta_group.array('episode_ends', np.array(episode_ends, dtype=np.int64)) # # 验证输出 # print("\n转换结果验证:") # print(f"- action: {actions.shape} {actions.dtype}") # print(f"- state: {states.shape} {states.dtype}") # print(f"- img: {side_images.shape} {side_images.dtype}") # print(f"- img: {wrist_images.shape} {wrist_images.dtype}") # print(f"- episode_ends: {len(episode_ends)} points") # if __name__ == '__main__': # convert_pkl_to_zarr( # pkl_path='/opt/ts/cfmp/data/lk_data/apple/is_random_False_apple_50_demos_2025-08-11_09-06-10.pkl', # zarr_path='data/lk_data_zarr/apple/apple_50_demos_2025-08-11_09-06-10.zarr' # ) import pickle import zarr import numpy as np import os from tqdm import tqdm def detect_episode_boundaries(data): """精确检测episode边界""" boundaries = [i for i, d in enumerate(data) if d.get('dones', False)] if not boundaries or boundaries[-1] != len(data)-1: boundaries.append(len(data)-1) return boundaries # def process_actions(actions, episode_ends): # """ # 处理actions: # - 保留第0,1,2和第6维,删除中间3,4,5维 # - 对最后一维的0值,用最近一次出现的1或-1替换(每个episode开头连续0保持不变) # """ # # 保留前三维 + 最后一维 (0,1,2,6),丢弃中间3-5维 # actions_new = np.concatenate([actions[:, :3], actions[:, 6:7]], axis=1) # shape (N,4) # last_dim = actions_new[:, -1] # start_idx = 0 # for end_idx in episode_ends: # episode_segment = last_dim[start_idx:end_idx] # nonzero_idx = np.where(episode_segment != 0)[0] # if len(nonzero_idx) == 0: # # 整个episode全0,保持不变 # start_idx = end_idx # continue # last_val = 0 # for i in range(len(episode_segment)): # if episode_segment[i] != 0: # last_val = episode_segment[i] # else: # if i > 0: # episode_segment[i] = last_val # last_dim[start_idx:end_idx] = episode_segment # start_idx = end_idx # actions_new[:, -1] = last_dim # return actions_new # def process_actions(actions, episode_ends, threshold=0.8): # """ # 处理 actions: # 1. 保留第0,1,2和第6维,删除中间3,4,5维 # 2. 对最后一维离散化:>threshold设为1,<-threshold设为-1,其余设为0 # 3. 对最后一维的0值,用最近一次出现的1或-1替换(每个episode开头连续0保持不变) # """ # # 保留前三维 + 最后一维 (0,1,2,6) # actions_new = np.concatenate([actions[:, :3], actions[:, 6:7]], axis=1) # shape (N,4) # last_dim = actions_new[:, -1] # # Step 1: 按阈值离散化 # last_dim[last_dim > threshold] = 1 # last_dim[last_dim < -threshold] = -1 # mask_mid = (last_dim <= threshold) & (last_dim >= -threshold) # last_dim[mask_mid] = 0 # # Step 2: 按 episode 填充 0 # start_idx = 0 # for end_idx in episode_ends: # episode_segment = last_dim[start_idx:end_idx] # # 找到所有非零位置 # nonzero_idx = np.where(episode_segment != 0)[0] # if len(nonzero_idx) == 0: # # 整个 episode 全 0,直接跳过 # start_idx = end_idx # continue # last_val = 0 # for i in range(len(episode_segment)): # if episode_segment[i] != 0: # last_val = episode_segment[i] # else: # # if i > 0: # 开头的连续 0 不填充 # episode_segment[i] = last_val # last_dim[start_idx:end_idx] = episode_segment # start_idx = end_idx # actions_new[:, -1] = last_dim # return actions_new def process_actions(actions, episode_ends, threshold=0.8): # 保留前三维 + 最后一维 (0,1,2,6) actions_new = np.concatenate([actions[:, :3], actions[:, 6:7]], axis=1) # shape (N,4) last_dim = actions_new[:, -1] # Step 1: 按阈值离散化 last_dim[last_dim > threshold] = 1 last_dim[last_dim < -threshold] = -1 mask_mid = (last_dim <= threshold) & (last_dim >= -threshold) last_dim[mask_mid] = 0 # Step 2: 按 episode 填充 0 start_idx = 0 for end_idx in episode_ends: episode_segment = last_dim[start_idx:end_idx] # 如果全 0,就直接全部改成 1 if np.all(episode_segment == 0): episode_segment[:] = 1 last_dim[start_idx:end_idx] = episode_segment start_idx = end_idx continue # 开头连续 0 全部改成 1 first_nonzero_idx = np.argmax(episode_segment != 0) if np.any(episode_segment != 0) else len(episode_segment) episode_segment[:first_nonzero_idx] = 1 # 再做正常的填充 last_val = episode_segment[0] for i in range(1, len(episode_segment)): if episode_segment[i] != 0: last_val = episode_segment[i] else: episode_segment[i] = last_val last_dim[start_idx:end_idx] = episode_segment start_idx = end_idx actions_new[:, -1] = last_dim return actions_new def convert_pkl_to_zarr(pkl_path, zarr_path): # 加载数据 with open(pkl_path, 'rb') as f: data = pickle.load(f) # 检测真实episode边界 episode_ends = detect_episode_boundaries(data) episode_ends = [x + 1 for x in episode_ends] print(f"检测到 {len(episode_ends)} 个episode,边界索引: {episode_ends}") # 初始化zarr存储 if os.path.exists(zarr_path): import shutil shutil.rmtree(zarr_path) root = zarr.open_group(zarr_path, mode='w') data_group = root.create_group('data') meta_group = root.create_group('meta') all_actions = [] all_states = [] all_side_image = [] # side_classifier all_wrist_image = [] # 处理每个step(只保留next_observations的第二个视角) for step in tqdm(data, desc="Processing steps"): obs = step['observations'] all_side_image.append(obs['side_policy_256'][0]) # (256,256,3) # all_wrist_image.append(obs['wrist_224'][0]) # (128,128,3) all_states.append(obs['state'][0]) # (19,) all_actions.append(step['actions']) # 转换为numpy数组 actions = np.array(all_actions, dtype=np.float64) states = np.array(all_states, dtype=np.float32) side_images = np.array(all_side_image, dtype=np.uint8) # (N,256,256,3) wrist_images = np.array(all_wrist_image, dtype=np.uint8) # 处理actions actions_processed = process_actions(actions, episode_ends) # 存储数据(使用高效压缩) compressor = zarr.Blosc(cname='zstd', clevel=3, shuffle=1) data_group.array('action', actions_processed, chunks=(100,4), compressor=compressor) data_group.array('state', states, chunks=(100,19), compressor=compressor) data_group.array('side_image', side_images, chunks=(100,256,256,3), compressor=compressor) # data_group.array('wrist_image', wrist_images, chunks=(100,224,224,3), compressor=compressor) meta_group.array('episode_ends', np.array(episode_ends, dtype=np.int64)) # 验证输出 print("\n转换结果验证:") print(f"- action: {actions_processed.shape} {actions_processed.dtype}") print(f"- state: {states.shape} {states.dtype}") print(f"- side_image: {side_images.shape} {side_images.dtype}") print(f"- wrist_image: {wrist_images.shape} {wrist_images.dtype}") print(f"- episode_ends: {len(episode_ends)} points") if __name__ == '__main__': convert_pkl_to_zarr( pkl_path='/opt/ts/cfmp/data/lk_data/apple/is_random_False_pick_apple_50_demos_2025-08-14_09-55-57.pkl', zarr_path='data/lk_data-1/apple/apple_50_demos_2025-08-14_09-55-57.zarr' )