rollingoat commited on
Commit
d18f707
·
verified ·
1 Parent(s): 5c44e75

Upload visualize_synced_data.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. visualize_synced_data.py +142 -0
visualize_synced_data.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Visualize a synced HDF5 dataset (output of sync_image_low_dim.py) as per-demo MP4s.
2
+
3
+ For each demo, renders selected image observations side-by-side and overlays
4
+ selected low-dim observations as text on every frame.
5
+
6
+ Example:
7
+ python visualize_synced_data.py synced.h5 --out-dir ./vis --fps 10 \
8
+ --image-keys agentview_image oak_image \
9
+ --overlay-keys robot0_eef_pos robot0_gripper_qpos
10
+ """
11
+
12
+ import argparse
13
+ import os
14
+
15
+ import cv2
16
+ import h5py
17
+ import numpy as np
18
+
19
+
20
+ def format_value(v) -> str:
21
+ arr = np.asarray(v).reshape(-1)
22
+ if arr.size == 1:
23
+ return f"{float(arr[0]):.3f}"
24
+ return "[" + ", ".join(f"{float(x):.3f}" for x in arr) + "]"
25
+
26
+
27
+ def visualize_demo(
28
+ demo_grp: h5py.Group,
29
+ demo_name: str,
30
+ out_dir: str,
31
+ image_keys: list,
32
+ fps: int,
33
+ overlay_keys: list,
34
+ target_size=(480, 680),
35
+ ) -> None:
36
+ print(f"Visualizing {demo_name} ({image_keys})...")
37
+ obs = demo_grp["obs"]
38
+ present_keys = [k for k in image_keys if k in obs]
39
+ if not present_keys:
40
+ print(f" Skipping {demo_name}: none of {image_keys} in obs.")
41
+ return
42
+ image_stacks = [obs[k][:] for k in present_keys]
43
+ n_frames = min(len(s) for s in image_stacks)
44
+ if n_frames == 0:
45
+ print(f" Skipping {demo_name}: no frames.")
46
+ return
47
+
48
+ overlay_data = []
49
+ for key in overlay_keys:
50
+ if key not in obs:
51
+ print(f" Note: overlay key '{key}' not in obs, skipping.")
52
+ continue
53
+ overlay_data.append((key, obs[key][:]))
54
+
55
+ target_h, per_w = target_size
56
+ total_w = per_w * len(present_keys)
57
+ total_h = target_h
58
+
59
+ video_path = os.path.join(out_dir, f"{demo_name}.mp4")
60
+ fourcc = cv2.VideoWriter_fourcc(*"mp4v")
61
+ writer = cv2.VideoWriter(video_path, fourcc, fps, (total_w, total_h))
62
+
63
+ for i in range(n_frames):
64
+ panels = []
65
+ for key, stack in zip(present_keys, image_stacks):
66
+ frame = stack[i]
67
+ if frame.ndim == 2:
68
+ frame = cv2.cvtColor(frame, cv2.COLOR_GRAY2BGR)
69
+ else:
70
+ frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
71
+ frame = cv2.resize(frame, (per_w, target_h))
72
+ cv2.putText(frame, key, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
73
+ panels.append(frame)
74
+ row = np.hstack(panels)
75
+
76
+ cv2.putText(row, f"Frame: {i}/{n_frames}", (10, target_h - 20),
77
+ cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2)
78
+
79
+ # Overlay low-dim values as text (top-right, stacked)
80
+ y = 30
81
+ for key, data in overlay_data:
82
+ val = data[i] if i < len(data) else data[-1]
83
+ text = f"{key}: {format_value(val)}"
84
+ (tw, th), _ = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, 0.6, 2)
85
+ x = total_w - tw - 10
86
+ cv2.putText(row, text, (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.6,
87
+ (0, 200, 255), 2)
88
+ y += th + 10
89
+
90
+ writer.write(row)
91
+
92
+ writer.release()
93
+ print(f" Saved {video_path}")
94
+
95
+
96
+ def _sort_key(name: str):
97
+ parts = name.split("_")
98
+ for p in reversed(parts):
99
+ if p.isdigit():
100
+ return (0, int(p))
101
+ return (1, name)
102
+
103
+
104
+ def main() -> None:
105
+ parser = argparse.ArgumentParser(description="Visualize synced HDF5 dataset as videos.")
106
+ parser.add_argument("file", help="Path to synced HDF5 file")
107
+ parser.add_argument("--out-dir", default="./vis", help="Output directory for videos")
108
+ parser.add_argument("--fps", type=int, default=30)
109
+ parser.add_argument("--image-keys", nargs="+", default=["agentview_image"],
110
+ help="Image observation keys to render side-by-side")
111
+ parser.add_argument("--overlay-keys", nargs="*", default=[],
112
+ help="Low-dim obs keys to overlay as text on each frame")
113
+ parser.add_argument("--target-size", type=int, nargs=2, default=[240, 680],
114
+ metavar=("H", "W"))
115
+ args = parser.parse_args()
116
+
117
+ if not os.path.exists(args.file):
118
+ print(f"File not found: {args.file}")
119
+ return
120
+ os.makedirs(args.out_dir, exist_ok=True)
121
+
122
+ with h5py.File(args.file, "r") as f:
123
+ if "data" not in f:
124
+ print("Invalid file: no top-level 'data' group.")
125
+ return
126
+ demos = sorted(f["data"].keys(), key=_sort_key)
127
+ print(f"Found {len(demos)} demos.")
128
+ for demo in demos:
129
+ visualize_demo(
130
+ f["data"][demo],
131
+ demo,
132
+ args.out_dir,
133
+ args.image_keys,
134
+ args.fps,
135
+ args.overlay_keys,
136
+ tuple(args.target_size),
137
+ )
138
+ print("Done.")
139
+
140
+
141
+ if __name__ == "__main__":
142
+ main()