zhening commited on
Commit
361cb67
·
verified ·
1 Parent(s): 283fe3d

update process_full_grid_to_gt.py

Browse files
Files changed (1) hide show
  1. process_full_grid_to_gt.py +336 -0
process_full_grid_to_gt.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ eval/process_full_grid_to_gt.py
4
+
5
+ Converts camxtime_evaluation_full_grid → camxtime_evaluation_gt.
6
+ Generates GT videos for the 5 moving-camera patterns only (81 frames each).
7
+
8
+ Input scene structure:
9
+ {input}/scene_X/
10
+ camera_000.mp4 ... camera_080.mp4 120-frame videos
11
+ (video frame 0 = trajectory key '2')
12
+ camera_000.json ... camera_080.json per-camera trajectory JSONs
13
+
14
+ Output scene structure:
15
+ {output}/scene_X/
16
+ moving_forward.mp4 + .json + .txt
17
+ moving_backward.mp4 + .json + .txt
18
+ moving_zigzag.mp4 + .json + .txt
19
+ moving_bullettime.mp4 + .json + .txt
20
+ moving_slowmo.mp4 + .json + .txt
21
+ camera_data.json (copied from src_cam/scene_X/camera_data.json)
22
+
23
+ Usage (run from repo root):
24
+ python eval/process_full_grid_to_gt.py \\
25
+ --input camxtime_evaluation_full_grid \\
26
+ --output camxtime_evaluation_gt \\
27
+ --src_cam evaluation_dataset/src_cam
28
+ """
29
+
30
+ import os
31
+ import json
32
+ import argparse
33
+ import subprocess
34
+ import shutil
35
+ import tempfile
36
+ import multiprocessing
37
+ from pathlib import Path
38
+ from datetime import datetime
39
+ from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor, as_completed
40
+
41
+ from tqdm import tqdm
42
+
43
+ # ── Constants ──────────────────────────────────────────────────────────────────
44
+ N_CAMS = 81
45
+ BULLET_FRAME = 40
46
+ TRAJ_KEY_OFFSET = 2 # video frame index 0 → trajectory JSON key '2'
47
+
48
+
49
+ # ── Pattern definitions (moving-cam only) ─────────────────────────────────────
50
+ def build_moving_patterns():
51
+ zigzag = list(range(41)) + list(range(39, -1, -1))
52
+ slowmo = [j // 2 for j in range(81)]
53
+ return {
54
+ "moving_forward": [(i, i) for i in range(N_CAMS)],
55
+ "moving_backward": [(i, N_CAMS-1-i) for i in range(N_CAMS)],
56
+ "moving_zigzag": [(i, zigzag[i]) for i in range(N_CAMS)],
57
+ "moving_bullettime": [(i, BULLET_FRAME) for i in range(N_CAMS)],
58
+ "moving_slowmo": [(i, slowmo[i]) for i in range(N_CAMS)],
59
+ }
60
+
61
+
62
+ # ── Load per-camera trajectories & intrinsics ─────────────────────────────────
63
+ def load_camera_trajectories(scene_dir: Path, n_cams: int = N_CAMS):
64
+ """Load camera poses for cameras 0..n_cams-1.
65
+
66
+ Prefers the compressed camera_data.json produced by compress_full_grid_cameras.py
67
+ (~0.3 MB vs ~7.7 MB of individual JSONs). Falls back to per-camera JSONs if absent.
68
+ """
69
+ compressed = scene_dir / "camera_data.json"
70
+ if compressed.exists():
71
+ with open(compressed) as f:
72
+ d = json.load(f)
73
+ K = d["intrinsics"]["K"]
74
+ intrinsics = {"K": K, "fx": K[0][0], "fy": K[1][1], "cx": K[0][2], "cy": K[1][2]}
75
+ # All frames of a camera share the same pose; replicate across all motion indices.
76
+ trajectories = {
77
+ cam_idx: {frame: d["cameras"][str(cam_idx)]["c2w"] for frame in range(N_CAMS)}
78
+ for cam_idx in range(n_cams)
79
+ }
80
+ return trajectories, intrinsics
81
+
82
+ # Fallback: read individual per-camera JSONs
83
+ trajectories = {}
84
+ intrinsics = None
85
+ for cam_idx in range(n_cams):
86
+ json_path = scene_dir / f"camera_{cam_idx:03d}.json"
87
+ if not json_path.exists():
88
+ raise FileNotFoundError(
89
+ f"Missing: {json_path}\n"
90
+ f" Run eval/compress_full_grid_cameras.py first, or keep per-camera JSONs."
91
+ )
92
+ with open(json_path) as f:
93
+ d = json.load(f)
94
+ if intrinsics is None:
95
+ K = d["intrinsics"]["K"]
96
+ intrinsics = {"K": K, "fx": K[0][0], "fy": K[1][1], "cx": K[0][2], "cy": K[1][2]}
97
+ traj = {}
98
+ for key, val in d["trajectory"].items():
99
+ traj[int(key) - TRAJ_KEY_OFFSET] = val["c2w"]
100
+ trajectories[cam_idx] = traj
101
+ return trajectories, intrinsics
102
+
103
+
104
+ # ── Frame extraction ───────────────────────────────────────────────────────────
105
+ def _extract_one_camera(args):
106
+ vid_path, out_cam_dir, max_frame = args
107
+ Path(out_cam_dir).mkdir(parents=True, exist_ok=True)
108
+ cmd = [
109
+ "ffmpeg", "-y", "-i", str(vid_path),
110
+ "-frames:v", str(max_frame + 1),
111
+ "-start_number", "0", "-q:v", "2",
112
+ str(Path(out_cam_dir) / "frame_%04d.jpg"),
113
+ ]
114
+ result = subprocess.run(cmd, capture_output=True)
115
+ if result.returncode != 0:
116
+ raise RuntimeError(
117
+ f"ffmpeg extraction failed for {Path(vid_path).name}:\n"
118
+ f"{result.stderr.decode()[-400:]}"
119
+ )
120
+
121
+
122
+ def extract_scene_frames(scene_dir, temp_dir, n_cams=N_CAMS,
123
+ max_frame=N_CAMS-1, n_threads=8):
124
+ tasks = [
125
+ (scene_dir / f"camera_{i:03d}.mp4", temp_dir / f"camera_{i:03d}", max_frame)
126
+ for i in range(n_cams)
127
+ ]
128
+ corrupt = set()
129
+ futures_map = {}
130
+ with ThreadPoolExecutor(max_workers=n_threads) as pool:
131
+ futures_map = {pool.submit(_extract_one_camera, t): i
132
+ for i, t in enumerate(tasks)}
133
+ for fut in as_completed(futures_map):
134
+ cam_idx = futures_map[fut]
135
+ try:
136
+ fut.result()
137
+ except RuntimeError as e:
138
+ corrupt.add(cam_idx)
139
+ print(f" WARNING: camera_{cam_idx:03d}.mp4 is corrupt — will substitute from neighbor")
140
+
141
+ # Substitute corrupt cameras with frames from nearest valid neighbor
142
+ if corrupt:
143
+ for cam_idx in sorted(corrupt):
144
+ # find nearest valid camera (search outward from cam_idx)
145
+ neighbor = None
146
+ for delta in range(1, n_cams):
147
+ for sign in (1, -1):
148
+ cand = cam_idx + sign * delta
149
+ if 0 <= cand < n_cams and cand not in corrupt:
150
+ neighbor = cand
151
+ break
152
+ if neighbor is not None:
153
+ break
154
+ if neighbor is None:
155
+ raise RuntimeError(f"No valid neighbor found for camera_{cam_idx:03d}")
156
+ src_dir = temp_dir / f"camera_{neighbor:03d}"
157
+ dst_dir = temp_dir / f"camera_{cam_idx:03d}"
158
+ dst_dir.mkdir(parents=True, exist_ok=True)
159
+ for frame_file in src_dir.iterdir():
160
+ dst = dst_dir / frame_file.name
161
+ if not dst.exists():
162
+ shutil.copy2(frame_file, dst)
163
+ print(f" INFO: camera_{cam_idx:03d} substituted from camera_{neighbor:03d}")
164
+
165
+
166
+ # ── Video assembly ─────────────────────────────────────────────────────────────
167
+ def build_video(frame_paths, output_path, fps=30):
168
+ list_file = str(output_path) + ".concat.txt"
169
+ with open(list_file, "w") as f:
170
+ for fp in frame_paths:
171
+ f.write(f"file '{fp}'\nduration {1.0/fps}\n")
172
+ if frame_paths:
173
+ f.write(f"file '{frame_paths[-1]}'\n")
174
+ cmd = [
175
+ "ffmpeg", "-y", "-f", "concat", "-safe", "0", "-i", list_file,
176
+ "-c:v", "libx264", "-pix_fmt", "yuv420p", "-r", str(fps), str(output_path),
177
+ ]
178
+ result = subprocess.run(cmd, capture_output=True)
179
+ os.unlink(list_file)
180
+ if result.returncode != 0:
181
+ raise RuntimeError(f"ffmpeg assembly failed:\n{result.stderr.decode()[-400:]}")
182
+
183
+
184
+ # ── Trajectory output ──────────────────────────────────────────────────────────
185
+ def _invert_rigid(c2w):
186
+ R = [[c2w[r][c] for c in range(3)] for r in range(3)]
187
+ t = [c2w[r][3] for r in range(3)]
188
+ Rt = [[R[c][r] for c in range(3)] for r in range(3)]
189
+ nt = [-sum(Rt[r][c] * t[c] for c in range(3)) for r in range(3)]
190
+ return [[Rt[0][0], Rt[0][1], Rt[0][2], nt[0]],
191
+ [Rt[1][0], Rt[1][1], Rt[1][2], nt[1]],
192
+ [Rt[2][0], Rt[2][1], Rt[2][2], nt[2]],
193
+ [0.0, 0.0, 0.0, 1.0]]
194
+
195
+
196
+ def save_trajectory(traj_seq, intrinsics, scene_name, pattern_name,
197
+ out_json, out_txt, video_rel):
198
+ traj_dict = {
199
+ str(i): {"c2w": c2w, "w2c": _invert_rigid(c2w),
200
+ "source_cam_idx": cam, "source_motion_frame": mot}
201
+ for i, (c2w, cam, mot) in enumerate(traj_seq)
202
+ }
203
+ with open(out_json, "w") as f:
204
+ json.dump({"video_path": video_rel, "timestamp": datetime.now().isoformat()[:19],
205
+ "pattern": pattern_name, "intrinsics": intrinsics,
206
+ "trajectory": traj_dict,
207
+ "extras": {"scene_name": scene_name, "pattern": pattern_name,
208
+ "frame_count": len(traj_seq)}}, f, indent=2)
209
+ K = intrinsics["K"]
210
+ lines = [
211
+ "# Camera metadata",
212
+ f"video_path: {video_rel}", f"pattern: {pattern_name}",
213
+ f"scene_name: {scene_name}",
214
+ f"fx: {intrinsics['fx']}", f"fy: {intrinsics['fy']}",
215
+ f"cx: {intrinsics['cx']}", f"cy: {intrinsics['cy']}",
216
+ f"frame_count: {len(traj_seq)}", "",
217
+ "[K]",
218
+ f"{K[0][0]:.6f} {K[0][1]:.6f} {K[0][2]:.6f}",
219
+ f"{K[1][0]:.6f} {K[1][1]:.6f} {K[1][2]:.6f}",
220
+ f"{K[2][0]:.6f} {K[2][1]:.6f} {K[2][2]:.6f}", "",
221
+ "[CAMERA_TRAJECTORY]",
222
+ "# output_frame cam=source_cam_idx motion=motion_frame pos(x y z) rot(row0 row1 row2)",
223
+ ]
224
+ for i, (c2w, cam, mot) in enumerate(traj_seq):
225
+ px, py, pz = c2w[0][3], c2w[1][3], c2w[2][3]
226
+ r = [c2w[0][0], c2w[0][1], c2w[0][2],
227
+ c2w[1][0], c2w[1][1], c2w[1][2],
228
+ c2w[2][0], c2w[2][1], c2w[2][2]]
229
+ lines.append(f"{i} cam={cam} motion={mot} "
230
+ f"{px:.6f} {py:.6f} {pz:.6f} {' '.join(f'{v:.6f}' for v in r)}")
231
+ Path(out_txt).write_text("\n".join(lines))
232
+
233
+
234
+ # ── Per-scene worker ───────────────────────────────────────────────────────────
235
+ def process_scene(args):
236
+ import time
237
+ scene_dir, out_dir, src_cam_dir, fps, n_threads = args
238
+ scene_dir, out_dir, src_cam_dir = Path(scene_dir), Path(out_dir), Path(src_cam_dir)
239
+ scene_name = scene_dir.name
240
+ out_scene = out_dir / scene_name
241
+ out_scene.mkdir(parents=True, exist_ok=True)
242
+ t_start = time.time()
243
+
244
+ trajectories, intrinsics = load_camera_trajectories(scene_dir)
245
+
246
+ src_cam_json = src_cam_dir / scene_name / "camera_data.json"
247
+ if src_cam_json.exists():
248
+ shutil.copy2(src_cam_json, out_scene / "camera_data.json")
249
+
250
+ patterns = build_moving_patterns()
251
+ if all((out_scene / f"{n}.mp4").exists() and (out_scene / f"{n}.json").exists()
252
+ for n in patterns):
253
+ return scene_name, "skipped", 0.0, 0, len(patterns)
254
+
255
+ n_done = n_skip = 0
256
+ with tempfile.TemporaryDirectory() as tmp:
257
+ tmp_path = Path(tmp)
258
+ extract_scene_frames(scene_dir, tmp_path, N_CAMS, N_CAMS - 1, n_threads)
259
+ for pattern_name, frame_seq in patterns.items():
260
+ out_vid = out_scene / f"{pattern_name}.mp4"
261
+ out_json = out_scene / f"{pattern_name}.json"
262
+ out_txt = out_scene / f"{pattern_name}.txt"
263
+ if out_vid.exists() and out_json.exists():
264
+ n_skip += 1
265
+ continue
266
+ frame_paths, traj_seq = [], []
267
+ for cam_idx, motion_idx in frame_seq:
268
+ fp = tmp_path / f"camera_{cam_idx:03d}" / f"frame_{motion_idx:04d}.jpg"
269
+ if not fp.exists():
270
+ raise FileNotFoundError(f"Missing frame: {fp}")
271
+ frame_paths.append(str(fp))
272
+ traj_seq.append((trajectories[cam_idx][motion_idx], cam_idx, motion_idx))
273
+ build_video(frame_paths, out_vid, fps)
274
+ save_trajectory(traj_seq, intrinsics, scene_name, pattern_name,
275
+ out_json, out_txt, out_vid.name)
276
+ n_done += 1
277
+
278
+ return scene_name, "done", time.time() - t_start, n_done, n_skip
279
+
280
+
281
+ # ── CLI ────────────────────────────────────────────────────────────────────────
282
+ def main():
283
+ parser = argparse.ArgumentParser(
284
+ description="Generate moving-camera GT videos from camxtime_evaluation_full_grid."
285
+ )
286
+ parser.add_argument("--input", required=True)
287
+ parser.add_argument("--output", required=True)
288
+ parser.add_argument("--src_cam", required=True,
289
+ help="evaluation_dataset/src_cam folder")
290
+ parser.add_argument("--fps", type=int, default=30)
291
+ parser.add_argument("--scenes", nargs="+")
292
+ parser.add_argument("--workers", type=int,
293
+ default=max(1, multiprocessing.cpu_count() // 8))
294
+ parser.add_argument("--threads", type=int, default=8,
295
+ help="ffmpeg threads per scene for frame extraction")
296
+ args = parser.parse_args()
297
+
298
+ input_dir = Path(args.input)
299
+ output_dir = Path(args.output)
300
+ output_dir.mkdir(parents=True, exist_ok=True)
301
+ scenes = ([input_dir / s for s in args.scenes] if args.scenes
302
+ else sorted(p for p in input_dir.iterdir() if p.is_dir()))
303
+
304
+ print(f"CPUs: {multiprocessing.cpu_count()} | workers: {args.workers} "
305
+ f"| threads/scene: {args.threads} | scenes: {len(scenes)}\n")
306
+
307
+ tasks = [(s, output_dir, Path(args.src_cam), args.fps, args.threads) for s in scenes]
308
+ n_done = n_skipped = n_errors = 0
309
+
310
+ with ProcessPoolExecutor(max_workers=args.workers) as pool:
311
+ futures = {pool.submit(process_scene, t): Path(t[0]).name for t in tasks}
312
+ with tqdm(total=len(futures), desc="Overall", unit="scene",
313
+ dynamic_ncols=True) as pbar:
314
+ for fut in as_completed(futures):
315
+ name = futures[fut]
316
+ try:
317
+ _, status, elapsed, pdone, pskip = fut.result()
318
+ if status == "skipped":
319
+ n_skipped += 1
320
+ tqdm.write(f" SKIP {name:<12s} (all patterns exist)")
321
+ else:
322
+ n_done += 1
323
+ tqdm.write(f" OK {name:<12s} {elapsed:5.1f}s "
324
+ f"patterns: {pdone} built, {pskip} skipped")
325
+ except Exception as exc:
326
+ n_errors += 1
327
+ tqdm.write(f" ERR {name:<12s} {exc}")
328
+ pbar.set_postfix(done=n_done, skip=n_skipped, err=n_errors)
329
+ pbar.update(1)
330
+
331
+ print(f"\nFinished — {n_done} built, {n_skipped} skipped, {n_errors} errors")
332
+ print(f"Output: {output_dir}")
333
+
334
+
335
+ if __name__ == "__main__":
336
+ main()