yyyyyt commited on
Commit
f9e648a
·
verified ·
1 Parent(s): ecf0118

Delete convert_to_hdf5.py

Browse files
Files changed (1) hide show
  1. convert_to_hdf5.py +0 -165
convert_to_hdf5.py DELETED
@@ -1,165 +0,0 @@
1
- import h5py
2
- import cv2
3
- import numpy as np
4
- import argparse
5
- import csv
6
- import json
7
- from pathlib import Path
8
- import shutil
9
-
10
- def load_robot_data(csv_path):
11
- """
12
- Returns: master_ts, robot_ts, qpos, gripper
13
- """
14
- master_timestamps = []
15
- robot_timestamps = []
16
- qpos = []
17
- gripper = []
18
-
19
- with open(csv_path, 'r') as f:
20
- reader = csv.reader(f)
21
- try:
22
- header = next(reader)
23
-
24
- # Check format
25
- # Format 1: master_timestamp, robot_timestamp, j0..j5, gripper
26
- # Format 2: cam_timestamp, robot_timestamp, j0..j5, gripper (Previous version)
27
- # Format 3: timestamp, j0..j5, gripper (Legacy)
28
-
29
- if header[0] == 'master_timestamp' or header[0] == 'cam_timestamp':
30
- # New formats
31
- for row in reader:
32
- master_timestamps.append(float(row[0]))
33
- robot_timestamps.append(float(row[1]))
34
- qpos.append([float(x) for x in row[2:8]])
35
- gripper.append(float(row[8]))
36
- else:
37
- # Legacy format
38
- for row in reader:
39
- t = float(row[0])
40
- master_timestamps.append(t)
41
- robot_timestamps.append(t)
42
- qpos.append([float(x) for x in row[1:7]])
43
- gripper.append(float(row[7]))
44
-
45
- except StopIteration:
46
- return np.array([]), np.array([]), np.array([]), np.array([])
47
-
48
- return np.array(master_timestamps), np.array(robot_timestamps), np.array(qpos), np.array(gripper)
49
-
50
- def process_episode(episode_path, output_path):
51
- print(f"Processing {episode_path}...")
52
-
53
- csv_path = episode_path / "robot_data.csv"
54
-
55
- if not csv_path.exists():
56
- print(f"Skipping {episode_path}: Missing CSV")
57
- return
58
-
59
- # Load Robot Data
60
- master_ts, robot_ts, qpos, gripper = load_robot_data(csv_path)
61
-
62
- if len(master_ts) == 0:
63
- print(f"Skipping {episode_path}: Empty CSV")
64
- return
65
-
66
- num_frames = len(master_ts)
67
-
68
- # Find all camera directories
69
- cam_dirs = sorted(list(episode_path.glob("cam_*")))
70
-
71
- if not cam_dirs:
72
- print(f"Skipping {episode_path}: No camera directories found")
73
- return
74
-
75
- # Prepare HDF5 file
76
- with h5py.File(output_path, 'w') as root:
77
- root.attrs['sim'] = False
78
-
79
- obs = root.create_group('observations')
80
-
81
- # Robot State
82
- obs.create_dataset('qpos', data=qpos)
83
- obs.create_dataset('qvel', data=np.zeros_like(qpos)) # Placeholder, see below
84
-
85
- # Process Images
86
- min_frames = num_frames
87
-
88
- for cam_dir in cam_dirs:
89
- cam_name = cam_dir.name # e.g. cam_head
90
- image_files = sorted(list(cam_dir.glob("*.jpg")), key=lambda x: int(x.stem))
91
-
92
- # Check count
93
- if len(image_files) != num_frames:
94
- print(f"Warning: {cam_name} frames ({len(image_files)}) != CSV rows ({num_frames}). Truncating.")
95
- min_frames = min(min_frames, len(image_files))
96
-
97
- # Load images
98
- # Note: Loading all to memory might be heavy for many cameras/long episodes
99
- # Consider chunking if needed. For now, simple load.
100
- images = []
101
- for img_path in image_files[:min_frames]:
102
- img = cv2.imread(str(img_path))
103
- images.append(img)
104
-
105
- images = np.array(images)
106
- obs.create_dataset(f'images/{cam_name}', data=images)
107
-
108
- # Truncate robot data if images were shorter
109
- if min_frames < num_frames:
110
- qpos = qpos[:min_frames]
111
- gripper = gripper[:min_frames]
112
- robot_ts = robot_ts[:min_frames]
113
- master_ts = master_ts[:min_frames]
114
-
115
- # Re-save truncated qpos
116
- del obs['qpos']
117
- obs.create_dataset('qpos', data=qpos)
118
-
119
- # Compute qvel
120
- qvel = np.zeros_like(qpos)
121
- if len(qpos) > 1:
122
- dt = np.diff(robot_ts)
123
- dt = np.where(dt == 0, 1e-3, dt)[:, None]
124
- qvel[:-1] = (qpos[1:] - qpos[:-1]) / dt
125
- qvel[-1] = qvel[-2]
126
-
127
- del obs['qvel']
128
- obs.create_dataset('qvel', data=qvel)
129
-
130
- # Action
131
- action = np.zeros_like(qpos)
132
- action[:-1] = qpos[1:]
133
- action[-1] = qpos[-1]
134
-
135
- root.create_dataset('action', data=action)
136
-
137
- # Store timestamps
138
- # obs.create_dataset('timestamp', data=master_ts)
139
-
140
- print(f"Saved to {output_path}")
141
-
142
- def main():
143
- parser = argparse.ArgumentParser(description="Convert raw data to HDF5 for ACT")
144
- parser.add_argument('--task', required=True, help="Task name")
145
- parser.add_argument('--out', default="dataset.hdf5", help="Output HDF5 filename (or dir)")
146
- args = parser.parse_args()
147
-
148
- data_root = Path("data")
149
- task_dir = data_root / args.task
150
-
151
- if not task_dir.exists():
152
- print(f"Task {args.task} not found in {data_root}")
153
- return
154
-
155
- episodes = sorted(list(task_dir.glob("episode_*")))
156
-
157
- output_dir = Path(args.out)
158
- output_dir.mkdir(exist_ok=True, parents=True)
159
-
160
- for ep_dir in episodes:
161
- out_name = f"{ep_dir.name}.hdf5"
162
- process_episode(ep_dir, output_dir / out_name)
163
-
164
- if __name__ == "__main__":
165
- main()