zhening commited on
Commit
0e12a8e
·
verified ·
1 Parent(s): 361cb67

update preprocess_gt_videos.py

Browse files
Files changed (1) hide show
  1. preprocess_gt_videos.py +141 -0
preprocess_gt_videos.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ eval/preprocess_gt_videos.py
4
+
5
+ Apply the same spatial preprocessing used by SpaceTimePilot to the GT videos
6
+ in camxtime_evaluation_gt, so they match the network output format exactly.
7
+
8
+ Pipeline (mirrors spacetimepilot/dataset/utils.py):
9
+ 1. Load up to 81 frames at stride=1
10
+ 2. crop_and_resize: aspect-ratio preserving scale so image covers 832×480
11
+ 3. CenterCrop to exactly 832×480
12
+ 4. Pad with last frame if shorter than 81 frames
13
+ 5. Write as 30fps H264 MP4
14
+
15
+ For 1080×1080 source: scale to 832×832, then crop 176px top/bottom → 832×480.
16
+
17
+ Usage (run from repo root):
18
+ python eval/preprocess_gt_videos.py \\
19
+ --input camxtime_evaluation_gt \\
20
+ --output camxtime_evaluation_gt_preprocessed
21
+ """
22
+
23
+ import argparse
24
+ import multiprocessing
25
+ import shutil
26
+ from concurrent.futures import ProcessPoolExecutor, as_completed
27
+ from pathlib import Path
28
+
29
+ import imageio.v2 as imageio
30
+ import numpy as np
31
+ from PIL import Image
32
+ from tqdm import tqdm
33
+
34
+ TARGET_W = 832
35
+ TARGET_H = 480
36
+ NUM_FRAMES = 81
37
+ FPS = 30
38
+
39
+
40
+ def crop_and_resize(img: Image.Image) -> Image.Image:
41
+ w, h = img.size
42
+ scale = max(TARGET_W / w, TARGET_H / h)
43
+ return img.resize((round(w * scale), round(h * scale)), Image.BILINEAR)
44
+
45
+
46
+ def center_crop(img: Image.Image) -> Image.Image:
47
+ w, h = img.size
48
+ return img.crop(((w - TARGET_W) // 2, (h - TARGET_H) // 2,
49
+ (w - TARGET_W) // 2 + TARGET_W, (h - TARGET_H) // 2 + TARGET_H))
50
+
51
+
52
+ def preprocess_frame(arr: np.ndarray) -> np.ndarray:
53
+ img = Image.fromarray(arr).convert("RGB")
54
+ return np.array(center_crop(crop_and_resize(img)))
55
+
56
+
57
+ def process_video(src: Path, dst: Path) -> None:
58
+ reader = imageio.get_reader(str(src))
59
+ total = reader.count_frames()
60
+ frames = [preprocess_frame(reader.get_data(i)) for i in range(min(NUM_FRAMES, total))]
61
+ reader.close()
62
+ while len(frames) < NUM_FRAMES:
63
+ frames.append(frames[-1].copy())
64
+ writer = imageio.get_writer(str(dst), fps=FPS, codec="libx264", quality=8)
65
+ for f in frames:
66
+ writer.append_data(f)
67
+ writer.close()
68
+
69
+
70
+ def process_scene(args):
71
+ scene_dir, out_dir = Path(args[0]), Path(args[1])
72
+ out_scene = out_dir / scene_dir.name
73
+ out_scene.mkdir(parents=True, exist_ok=True)
74
+ n_built = n_skipped = 0
75
+ for vid in sorted(scene_dir.glob("*.mp4")):
76
+ out_vid = out_scene / vid.name
77
+ if out_vid.exists():
78
+ n_skipped += 1
79
+ else:
80
+ process_video(vid, out_vid)
81
+ n_built += 1
82
+ for ext in (".json", ".txt"):
83
+ src = vid.with_suffix(ext)
84
+ if src.exists():
85
+ dst = out_scene / src.name
86
+ if not dst.exists():
87
+ shutil.copy2(src, dst)
88
+ cam_json = scene_dir / "camera_data.json"
89
+ if cam_json.exists() and not (out_scene / "camera_data.json").exists():
90
+ shutil.copy2(cam_json, out_scene / "camera_data.json")
91
+ return scene_dir.name, n_built, n_skipped
92
+
93
+
94
+ def main():
95
+ parser = argparse.ArgumentParser(
96
+ description="Preprocess GT videos to 832×480 / 81 frames to match network output."
97
+ )
98
+ parser.add_argument("--input", required=True,
99
+ help="camxtime_evaluation_gt root")
100
+ parser.add_argument("--output", required=True,
101
+ help="Output root (camxtime_evaluation_gt_preprocessed)")
102
+ parser.add_argument("--scenes", nargs="+")
103
+ parser.add_argument("--workers", type=int,
104
+ default=min(32, multiprocessing.cpu_count()))
105
+ args = parser.parse_args()
106
+
107
+ input_dir = Path(args.input)
108
+ output_dir = Path(args.output)
109
+ output_dir.mkdir(parents=True, exist_ok=True)
110
+ scenes = ([input_dir / s for s in args.scenes] if args.scenes
111
+ else sorted(p for p in input_dir.iterdir() if p.is_dir()))
112
+
113
+ print(f"CPUs: {multiprocessing.cpu_count()} | workers: {args.workers} "
114
+ f"| target: {TARGET_W}×{TARGET_H}, {NUM_FRAMES}f @ {FPS}fps "
115
+ f"| scenes: {len(scenes)}\n")
116
+
117
+ tasks = [(s, output_dir) for s in scenes]
118
+ n_done = n_errors = 0
119
+
120
+ with ProcessPoolExecutor(max_workers=args.workers) as pool:
121
+ futures = {pool.submit(process_scene, t): Path(t[0]).name for t in tasks}
122
+ with tqdm(total=len(futures), desc="Overall", unit="scene",
123
+ dynamic_ncols=True) as pbar:
124
+ for fut in as_completed(futures):
125
+ name = futures[fut]
126
+ try:
127
+ _, built, skipped = fut.result()
128
+ n_done += 1
129
+ tqdm.write(f" OK {name:<12s} {built} preprocessed, {skipped} skipped")
130
+ except Exception as exc:
131
+ n_errors += 1
132
+ tqdm.write(f" ERR {name:<12s} {exc}")
133
+ pbar.set_postfix(done=n_done, err=n_errors)
134
+ pbar.update(1)
135
+
136
+ print(f"\nFinished — {n_done} scenes done, {n_errors} errors")
137
+ print(f"Output: {output_dir}")
138
+
139
+
140
+ if __name__ == "__main__":
141
+ main()