# -*- coding: utf-8 -*- """ Fixed_Viewpoint_Tactile_Dataset 使用示例(可直接运行) 环境要求: Python >= 3.10, 已安装 lerobot conda activate zyhand # 你机器上有 lerobot 0.4.3 的环境 python example_usage.py # 从 HF 自动下载 python example_usage.py --root E:/tachintech/dataset/lerobot_tactile_hand_20fps # 用本地, 不下载 """ import argparse import numpy as np REPO = "Tachintech/Fixed_Viewpoint_Tactile_Dataset" def main(): ap = argparse.ArgumentParser() ap.add_argument("--root", default=None, help="本地数据集路径(给了就不从HF下载)") ap.add_argument("--save-img", default="sample_color.png", help="保存一帧RGB的路径") args = ap.parse_args() # ── 1) 加载数据集 ──────────────────────────────────────────────── from lerobot.datasets.lerobot_dataset import LeRobotDataset print("加载数据集中 ...") ds = LeRobotDataset(REPO, root=args.root) print(f" 总帧数 : {ds.num_frames}") print(f" episodes : {ds.num_episodes}") print(f" fps : {ds.fps}") # ── 2) 列出所有键(字段) ────────────────────────────────────────── print("\n===== 数据集所有键 (来自 meta/info.json) =====") feats = ds.meta.info["features"] for name, spec in feats.items(): print(f" {name:35s} dtype={spec['dtype']:8s} shape={spec['shape']}") # 触觉每路的 2D 形状 shapes = ds.meta.info.get("tactile_2d_shapes", {}) print("\n触觉传感器 2D 形状 (tactile_2d_shapes):") for k, v in shapes.items(): print(f" {k:12s} -> {v[0]} x {v[1]}") # ── 3) 取一帧, 看实际内容 ──────────────────────────────────────── print("\n===== 取第 0 帧, 各键的形状 =====") s = ds[0] for k in sorted(s.keys()): v = s[k] shp = tuple(v.shape) if hasattr(v, "shape") else f"{type(v).__name__}={v}" print(f" {k:35s} {shp}") # ── 4) 动捕: 还原成 20 个点 ────────────────────────────────────── pos = s["observation_motion_positions"].numpy() # [60] quat = s["observation_motion_quaternions"].numpy() # [80] pos20 = pos.reshape(20, 3) # 20 个点 x (x,y,z) quat20 = quat.reshape(20, 4) # 20 个点 x (w,x,y,z) print("\n===== 动捕 =====") print(f" 20 个标记点位置 reshape -> {pos20.shape}, 第0点 xyz = {np.round(pos20[0],4)}") print(f" 20 个标记点姿态 reshape -> {quat20.shape}, 第0点 quat= {np.round(quat20[0],4)}") # ── 5) 触觉: 还原成 2D 阵列 ────────────────────────────────────── print("\n===== 触觉 (还原成 2D) =====") for i in [0, 19]: key = f"tactile_{i}" flat = s[f"tactile_tactile_{i}"].numpy() grid = flat.reshape(shapes[key]) print(f" tactile_tactile_{i}: {flat.shape} -> 2D {grid.shape}, 和={grid.sum():.3f}") # ── 6) action 是什么 ───────────────────────────────────────────── act = s["action"].numpy() # [140] obs_concat = np.concatenate([pos, quat]) # 60+80=140 print("\n===== action =====") print(f" action shape = {act.shape}") print(f" action 是否 == (positions ⊕ quaternions): " f"{'是(完全相等)' if np.allclose(act, obs_concat) else '否'}") print(" 即 action = 当前帧 20 个动捕点的 (位置60 + 四元数80)") # ── 7) 视频帧 (已自动从 mp4 解码) ─────────────────────────────── color = s["observation.images.color"] # [3,480,848] float[0,1] depth = s["observation.images.depth"] print("\n===== 视频 =====") print(f" color: {tuple(color.shape)} dtype={color.dtype} 值域[{color.min():.2f},{color.max():.2f}]") print(f" depth: {tuple(depth.shape)}") try: from PIL import Image img = (color.permute(1, 2, 0).numpy() * 255).astype(np.uint8) Image.fromarray(img).save(args.save_img) print(f" 已保存一帧 RGB -> {args.save_img}") except Exception as e: print(f" (保存图片跳过: {e})") # ── 8) 按 episode 取 + DataLoader 批训练 ──────────────────────── print("\n===== 遍历 / 训练 =====") # episode 边界 try: froms = ds.meta.episodes["dataset_from_index"] tos = ds.meta.episodes["dataset_to_index"] print(f" episode 0: 帧 [{froms[0]}, {tos[0]}) 共 {tos[0]-froms[0]} 帧") except Exception: print(" (episode 边界 API 视版本而定, 可从 meta/episodes parquet 读 dataset_from/to_index)") from torch.utils.data import DataLoader dl = DataLoader(ds, batch_size=8, shuffle=True, num_workers=0) batch = next(iter(dl)) print(f" 一个 batch: action={tuple(batch['action'].shape)} " f"color={tuple(batch['observation.images.color'].shape)} " f"tactile_0={tuple(batch['tactile_tactile_0'].shape)}") print("\n===== 完成: 数据集可正常加载和使用 =====") if __name__ == "__main__": main()