Tachintech commited on
Commit
72ebc5e
·
verified ·
1 Parent(s): 65a8e22

Simplify example script comments

Browse files
Files changed (1) hide show
  1. example_usage.py +42 -77
example_usage.py CHANGED
@@ -1,11 +1,11 @@
1
  # -*- coding: utf-8 -*-
2
  """
3
- Fixed_Viewpoint_Tactile_Dataset 使用示例(可直接运行)
4
 
5
- 环境要求: Python >= 3.10, 已安装 lerobot
6
- conda activate zyhand # 你机器上有 lerobot 0.4.3 的环境
7
- python example_usage.py # 从 HF 自动下载
8
- python example_usage.py --root E:/tachintech/dataset/lerobot_tactile_hand_20fps # 用本地, 不下载
9
  """
10
  import argparse
11
  import numpy as np
@@ -15,96 +15,61 @@ REPO = "Tachintech/Fixed_Viewpoint_Tactile_Dataset"
15
 
16
  def main():
17
  ap = argparse.ArgumentParser()
18
- ap.add_argument("--root", default=None, help="本地数据集路径(给了就不从HF下载)")
19
- ap.add_argument("--save-img", default="sample_color.png", help="保存一帧RGB的路径")
20
  args = ap.parse_args()
21
 
22
- # ── 1) 加载数据集 ────────────────────────────────────────────────
23
  from lerobot.datasets.lerobot_dataset import LeRobotDataset
24
- print("加载数据集中 ...")
25
  ds = LeRobotDataset(REPO, root=args.root)
26
- print(f" 总帧数 : {ds.num_frames}")
27
- print(f" episodes : {ds.num_episodes}")
28
- print(f" fps : {ds.fps}")
29
 
30
- # ── 2) 列出所有键(字段) ──────────────────────────────────────────
31
- print("\n===== 数据集所有键 (来自 meta/info.json) =====")
32
- feats = ds.meta.info["features"]
33
- for name, spec in feats.items():
34
- print(f" {name:35s} dtype={spec['dtype']:8s} shape={spec['shape']}")
35
 
36
- # 触觉每路的 2D 形状
37
  shapes = ds.meta.info.get("tactile_2d_shapes", {})
38
- print("\n触觉传感器 2D 形状 (tactile_2d_shapes):")
39
- for k, v in shapes.items():
40
- print(f" {k:12s} -> {v[0]} x {v[1]}")
41
 
42
- # ── 3) 取一帧, 看实际内容 ────────────────────────────────────────
43
- print("\n===== 取第 0 帧, 各键的形状 =====")
44
- s = ds[0]
45
  for k in sorted(s.keys()):
46
  v = s[k]
47
- shp = tuple(v.shape) if hasattr(v, "shape") else f"{type(v).__name__}={v}"
48
- print(f" {k:35s} {shp}")
49
-
50
- # ── 4) 动捕: 还原成 20 个点 ──────────────────────────────────────
51
- pos = s["observation_motion_positions"].numpy() # [60]
52
- quat = s["observation_motion_quaternions"].numpy() # [80]
53
- pos20 = pos.reshape(20, 3) # 20 个点 x (x,y,z)
54
- quat20 = quat.reshape(20, 4) # 20 个点 x (w,x,y,z)
55
- print("\n===== 动捕 =====")
56
- print(f" 20 个标记点位置 reshape -> {pos20.shape}, 第0点 xyz = {np.round(pos20[0],4)}")
57
- print(f" 20 个标记点姿态 reshape -> {quat20.shape}, 第0点 quat= {np.round(quat20[0],4)}")
58
-
59
- # ── 5) 触觉: 还原成 2D 阵列 ──────────────────────────────────────
60
- print("\n===== 触觉 (还原成 2D) =====")
61
- for i in [0, 19]:
62
- key = f"tactile_{i}"
63
  flat = s[f"tactile_tactile_{i}"].numpy()
64
- grid = flat.reshape(shapes[key])
65
- print(f" tactile_tactile_{i}: {flat.shape} -> 2D {grid.shape}, 和={grid.sum():.3f}")
66
-
67
- # ── 6) action 是什么 ─────────────────────────────────────────────
68
- act = s["action"].numpy() # [140]
69
- obs_concat = np.concatenate([pos, quat]) # 60+80=140
70
- print("\n===== action =====")
71
- print(f" action shape = {act.shape}")
72
- print(f" action 是否 == (positions ⊕ quaternions): "
73
- f"{'是(完全相等)' if np.allclose(act, obs_concat) else '否'}")
74
- print(" 即 action = 当前帧 20 个动捕点的 (位置60 + 四元数80)")
75
-
76
- # ── 7) 视频帧 (已自动从 mp4 解码) ───────────────────────────────
77
- color = s["observation.images.color"] # [3,480,848] float[0,1]
78
- depth = s["observation.images.depth"]
79
- print("\n===== 视频 =====")
80
- print(f" color: {tuple(color.shape)} dtype={color.dtype} 值域[{color.min():.2f},{color.max():.2f}]")
81
- print(f" depth: {tuple(depth.shape)}")
82
  try:
83
  from PIL import Image
84
  img = (color.permute(1, 2, 0).numpy() * 255).astype(np.uint8)
85
  Image.fromarray(img).save(args.save_img)
86
- print(f" 已保存一帧 RGB -> {args.save_img}")
87
  except Exception as e:
88
- print(f" (保存图片跳过: {e})")
89
-
90
- # ── 8) 按 episode 取 + DataLoader 批训练 ────────────────────────
91
- print("\n===== 遍历 / 训练 =====")
92
- # episode 边界
93
- try:
94
- froms = ds.meta.episodes["dataset_from_index"]
95
- tos = ds.meta.episodes["dataset_to_index"]
96
- print(f" episode 0: 帧 [{froms[0]}, {tos[0]}) 共 {tos[0]-froms[0]} 帧")
97
- except Exception:
98
- print(" (episode 边界 API 视版本而定, 可从 meta/episodes parquet 读 dataset_from/to_index)")
99
 
 
100
  from torch.utils.data import DataLoader
101
- dl = DataLoader(ds, batch_size=8, shuffle=True, num_workers=0)
102
- batch = next(iter(dl))
103
- print(f" 一个 batch: action={tuple(batch['action'].shape)} "
104
- f"color={tuple(batch['observation.images.color'].shape)} "
105
- f"tactile_0={tuple(batch['tactile_tactile_0'].shape)}")
106
-
107
- print("\n===== 完成: 数据集可正常加载和使用 =====")
108
 
109
 
110
  if __name__ == "__main__":
 
1
  # -*- coding: utf-8 -*-
2
  """
3
+ Fixed_Viewpoint_Tactile_Dataset 加载示例
4
 
5
+ python example_usage.py # HuggingFace 下载
6
+ python example_usage.py --root <本地数据集路径> # 用本地副本,不下载
7
+
8
+ 需要 Python >= 3.10 且已安装 lerobot。
9
  """
10
  import argparse
11
  import numpy as np
 
15
 
16
  def main():
17
  ap = argparse.ArgumentParser()
18
+ ap.add_argument("--root", default=None, help="本地数据集路径给了就不从 HF 下载")
19
+ ap.add_argument("--save-img", default="sample_color.png")
20
  args = ap.parse_args()
21
 
 
22
  from lerobot.datasets.lerobot_dataset import LeRobotDataset
 
23
  ds = LeRobotDataset(REPO, root=args.root)
24
+ print(f"frames={ds.num_frames} episodes={ds.num_episodes} fps={ds.fps}")
 
 
25
 
26
+ # 字段列表
27
+ print("\n[features]")
28
+ for name, spec in ds.meta.info["features"].items():
29
+ print(f" {name:35s} {spec['dtype']:8s} {spec['shape']}")
 
30
 
 
31
  shapes = ds.meta.info.get("tactile_2d_shapes", {})
 
 
 
32
 
33
+ # 取一帧
34
+ s = ds[100]
35
+ print("\n[frame 100]")
36
  for k in sorted(s.keys()):
37
  v = s[k]
38
+ print(f" {k:35s} {tuple(v.shape) if hasattr(v, 'shape') else v}")
39
+
40
+ # 动捕:20 个标记点,各 3 位置 + 4 四元数
41
+ pos20 = s["observation_motion_positions"].numpy().reshape(20, 3)
42
+ quat20 = s["observation_motion_quaternions"].numpy().reshape(20, 4)
43
+ print(f"\nmotion: pos {pos20.shape}, quat {quat20.shape}")
44
+
45
+ # 触觉:展平向量按 tactile_2d_shapes 还原成 2D
46
+ for i in (0, 19):
 
 
 
 
 
 
 
47
  flat = s[f"tactile_tactile_{i}"].numpy()
48
+ grid = flat.reshape(shapes[f"tactile_{i}"])
49
+ print(f"tactile_{i}: {flat.shape} -> {grid.shape}")
50
+
51
+ # action 等于当前帧动捕的 位置 + 四元数 拼接
52
+ act = s["action"].numpy()
53
+ obs = np.concatenate([s["observation_motion_positions"].numpy(),
54
+ s["observation_motion_quaternions"].numpy()])
55
+ print(f"action == motion(pos+quat): {np.allclose(act, obs)}")
56
+
57
+ # 视频已从 mp4 解码为 [3,H,W] 张量,值域 [0,1]
58
+ color = s["observation.images.color"]
59
+ print(f"color {tuple(color.shape)}, depth {tuple(s['observation.images.depth'].shape)}")
 
 
 
 
 
 
60
  try:
61
  from PIL import Image
62
  img = (color.permute(1, 2, 0).numpy() * 255).astype(np.uint8)
63
  Image.fromarray(img).save(args.save_img)
64
+ print(f"saved {args.save_img}")
65
  except Exception as e:
66
+ print(f"skip save image: {e}")
 
 
 
 
 
 
 
 
 
 
67
 
68
+ # 批训练
69
  from torch.utils.data import DataLoader
70
+ batch = next(iter(DataLoader(ds, batch_size=8, shuffle=True, num_workers=0)))
71
+ print(f"\nbatch: action {tuple(batch['action'].shape)}, "
72
+ f"color {tuple(batch['observation.images.color'].shape)}")
 
 
 
 
73
 
74
 
75
  if __name__ == "__main__":