shauryadewan commited on
Commit
97c1448
·
verified ·
1 Parent(s): a983543

Upload hdf5_to_mp4.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. hdf5_to_mp4.py +209 -0
hdf5_to_mp4.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2024-2025, The Isaac Lab Project Developers.
2
+ # All rights reserved.
3
+ #
4
+ # SPDX-License-Identifier: BSD-3-Clause
5
+
6
+ """
7
+ Script to convert HDF5 demonstration files to MP4 videos.
8
+
9
+ This script converts camera frames stored in HDF5 demonstration files to MP4 videos.
10
+ It supports multiple camera modalities including RGB, segmentation, and normal maps.
11
+ The output videos are saved in the specified directory with appropriate naming.
12
+
13
+ required arguments:
14
+ --input_file Path to the input HDF5 file.
15
+ --output_dir Directory to save the output MP4 files.
16
+
17
+ optional arguments:
18
+ --input_keys List of input keys to process from the HDF5 file. (default: ["table_cam", "wrist_cam", "table_cam_segmentation", "table_cam_normals", "table_cam_shaded_segmentation"])
19
+ --video_height Height of the output video in pixels. (default: 704)
20
+ --video_width Width of the output video in pixels. (default: 1280)
21
+ --framerate Frames per second for the output video. (default: 30)
22
+ """
23
+
24
+ # Standard library imports
25
+ import argparse
26
+ import h5py
27
+ import numpy as np
28
+
29
+ # Third-party imports
30
+ import os
31
+
32
+ import cv2
33
+
34
+ # Constants
35
+ DEFAULT_VIDEO_HEIGHT = 704
36
+ DEFAULT_VIDEO_WIDTH = 1280
37
+ DEFAULT_INPUT_KEYS = [
38
+ "table_cam",
39
+ "wrist_cam",
40
+ "table_cam_segmentation",
41
+ "table_cam_normals",
42
+ "table_cam_shaded_segmentation",
43
+ "table_cam_depth",
44
+ ]
45
+ DEFAULT_FRAMERATE = 30
46
+ LIGHT_SOURCE = np.array([0.0, 0.0, 1.0])
47
+ MIN_DEPTH = 0.0
48
+ MAX_DEPTH = 1.5
49
+
50
+
51
+ def parse_args():
52
+ """Parse command line arguments."""
53
+ parser = argparse.ArgumentParser(description="Convert HDF5 demonstration files to MP4 videos.")
54
+ parser.add_argument(
55
+ "--input_file",
56
+ type=str,
57
+ required=True,
58
+ help="Path to the input HDF5 file containing demonstration data.",
59
+ )
60
+ parser.add_argument(
61
+ "--output_dir",
62
+ type=str,
63
+ required=True,
64
+ help="Directory path where the output MP4 files will be saved.",
65
+ )
66
+
67
+ parser.add_argument(
68
+ "--input_keys",
69
+ type=str,
70
+ nargs="+",
71
+ default=DEFAULT_INPUT_KEYS,
72
+ help="List of input keys to process.",
73
+ )
74
+ parser.add_argument(
75
+ "--video_height",
76
+ type=int,
77
+ default=DEFAULT_VIDEO_HEIGHT,
78
+ help="Height of the output video in pixels.",
79
+ )
80
+ parser.add_argument(
81
+ "--video_width",
82
+ type=int,
83
+ default=DEFAULT_VIDEO_WIDTH,
84
+ help="Width of the output video in pixels.",
85
+ )
86
+ parser.add_argument(
87
+ "--framerate",
88
+ type=int,
89
+ default=DEFAULT_FRAMERATE,
90
+ help="Frames per second for the output video.",
91
+ )
92
+
93
+ args = parser.parse_args()
94
+
95
+ return args
96
+
97
+
98
+ def write_demo_to_mp4(
99
+ hdf5_file,
100
+ demo_id,
101
+ frames_path,
102
+ input_key,
103
+ output_dir,
104
+ video_height,
105
+ video_width,
106
+ framerate=DEFAULT_FRAMERATE,
107
+ ):
108
+ """Convert frames from an HDF5 file to an MP4 video.
109
+
110
+ Args:
111
+ hdf5_file (str): Path to the HDF5 file containing the frames.
112
+ demo_id (int): ID of the demonstration to convert.
113
+ frames_path (str): Path to the frames data in the HDF5 file.
114
+ input_key (str): Name of the input key to convert.
115
+ output_dir (str): Directory to save the output MP4 file.
116
+ video_height (int): Height of the output video in pixels.
117
+ video_width (int): Width of the output video in pixels.
118
+ framerate (int, optional): Frames per second for the output video. Defaults to 30.
119
+ """
120
+ with h5py.File(hdf5_file, "r") as f:
121
+ # Get frames based on input key type
122
+ if "shaded_segmentation" in input_key:
123
+ temp_key = input_key.replace("shaded_segmentation", "segmentation")
124
+ frames = f[f"data/demo_{demo_id}/obs/{temp_key}"]
125
+ else:
126
+ frames = f[frames_path + "/" + input_key]
127
+
128
+ # Setup video writer
129
+ output_path = os.path.join(output_dir, f"demo_{demo_id}_{input_key}.mp4")
130
+ fourcc = cv2.VideoWriter_fourcc(*"mp4v")
131
+ if "depth" in input_key:
132
+ video = cv2.VideoWriter(output_path, fourcc, framerate, (video_width, video_height), isColor=False)
133
+ else:
134
+ video = cv2.VideoWriter(output_path, fourcc, framerate, (video_width, video_height))
135
+
136
+ # Process and write frames
137
+ for ix, frame in enumerate(frames):
138
+ # Convert normal maps to uint8 if needed
139
+ if "normals" in input_key:
140
+ frame = (frame * 255.0).astype(np.uint8)
141
+
142
+ # Process shaded segmentation frames
143
+ elif "shaded_segmentation" in input_key:
144
+ seg = frame[..., :-1]
145
+ normals_key = input_key.replace("shaded_segmentation", "normals")
146
+ normals = f[f"data/demo_{demo_id}/obs/{normals_key}"][ix]
147
+ shade = 0.5 + (normals * LIGHT_SOURCE[None, None, :]).sum(axis=-1) * 0.5
148
+ shaded_seg = (shade[..., None] * seg).astype(np.uint8)
149
+ frame = np.concatenate((shaded_seg, frame[..., -1:]), axis=-1)
150
+
151
+ # Convert RGB to BGR
152
+ if "depth" not in input_key:
153
+ frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
154
+ else:
155
+ frame = (frame[..., 0] - MIN_DEPTH) / (MAX_DEPTH - MIN_DEPTH)
156
+ frame = np.where(frame < 0.01, 1.0, frame)
157
+ frame = 1.0 - frame
158
+ frame = (frame * 255.0).astype(np.uint8)
159
+
160
+ # Resize to video resolution
161
+ frame = cv2.resize(frame, (video_width, video_height), interpolation=cv2.INTER_CUBIC)
162
+ video.write(frame)
163
+
164
+ video.release()
165
+
166
+
167
+ def get_num_demos(hdf5_file):
168
+ """Get the number of demonstrations in the HDF5 file.
169
+
170
+ Args:
171
+ hdf5_file (str): Path to the HDF5 file.
172
+
173
+ Returns:
174
+ int: Number of demonstrations found in the file.
175
+ """
176
+ with h5py.File(hdf5_file, "r") as f:
177
+ return len(f["data"].keys())
178
+
179
+
180
+ def main():
181
+ """Main function to convert all demonstrations to MP4 videos."""
182
+ # Parse command line arguments
183
+ args = parse_args()
184
+
185
+ # Create output directory if it doesn't exist
186
+ os.makedirs(args.output_dir, exist_ok=True)
187
+
188
+ # Get number of demonstrations from the file
189
+ num_demos = get_num_demos(args.input_file)
190
+ print(f"Found {num_demos} demonstrations in {args.input_file}")
191
+
192
+ # Convert each demonstration
193
+ for i in range(num_demos):
194
+ frames_path = f"data/demo_{str(i)}/obs"
195
+ for input_key in args.input_keys:
196
+ write_demo_to_mp4(
197
+ args.input_file,
198
+ i,
199
+ frames_path,
200
+ input_key,
201
+ args.output_dir,
202
+ args.video_height,
203
+ args.video_width,
204
+ args.framerate,
205
+ )
206
+
207
+
208
+ if __name__ == "__main__":
209
+ main()