jasonzhango commited on
Commit
5ebe3e9
·
verified ·
1 Parent(s): 4715de3

Upload prepare_scannet_layout.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. prepare_scannet_layout.py +242 -0
prepare_scannet_layout.py ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Prepare SPAR-style layout from an official ScanNet installation (no original files uploaded).
5
+
6
+ Target layout (created locally):
7
+ spar/
8
+ scannet/
9
+ images/
10
+ scene0000_00/
11
+ image_color/ -> link/copy from scans/scene0000_00/color
12
+ image_depth/ -> link/copy from scans/scene0000_00/depth (if --rgbd)
13
+ intrinsic/ -> link/copy from scans/scene0000_00/intrinsic (if --rgbd)
14
+ pose/ -> link/copy from scans/scene0000_00/pose (if --rgbd)
15
+ video_color/ -> built from video_idx.txt as frame{i}_{idx}.jpg (if --use-video-idx)
16
+ video_depth/ -> reserved directory (if --rgbd)
17
+ video_pose/ -> reserved directory (if --rgbd)
18
+ video_idx.txt -> from --video-idx-root/<scene>/video_idx.txt or empty placeholder
19
+
20
+ Notes
21
+ -----
22
+ - When --use-video-idx is enabled, we read each integer index from `video_idx.txt` and
23
+ pick the corresponding source image from `image_color/`, then materialize:
24
+ video_color/frame{i}_{idx}.jpg
25
+ Example: indices [0, 35, 70, 106] → frame0_0.jpg, frame1_35.jpg, ...
26
+ - Source matching is robust to common ScanNet filename styles:
27
+ `174.jpg`, `000174.jpg`, `frame-000174.color.jpg`, etc.
28
+ - By default we create **symlinks**; add `--copy` to duplicate files instead.
29
+
30
+ USAGE (examples)
31
+ ----------------
32
+ # 1) Minimal (RGB only), all scenes, symlinks:
33
+ python tools/prepare_scannet_layout.py \
34
+ --scannet-root /path/to/scannet \
35
+ --out-root spar/scannet/images
36
+
37
+ # 2) RGBD (also link/copy depth/intrinsic/pose):
38
+ python tools/prepare_scannet_layout.py \
39
+ --scannet-root /path/to/scannet \
40
+ --out-root spar/scannet/images \
41
+ --rgbd
42
+
43
+ # 3) Use an existing video_idx.txt to populate video_color/
44
+ # (your idx files live in spar-jsonl/scannet/images/<scene>/video_idx.txt)
45
+ python tools/prepare_scannet_layout.py \
46
+ --scannet-root /path/to/scannet \
47
+ --out-root spar/scannet/images \
48
+ --use-video-idx \
49
+ --video-idx-root spar-jsonl/scannet/images
50
+
51
+ # 4) Only selected scenes (one per line in scenes.txt), copy instead of symlink, dry-run first:
52
+ python tools/prepare_scannet_layout.py \
53
+ --scannet-root /path/to/scannet \
54
+ --out-root spar/scannet/images \
55
+ --scenes-list scenes.txt \
56
+ --copy \
57
+ --dry-run
58
+
59
+ # 5) Customize filename patterns if your ScanNet color/depth names differ:
60
+ python tools/prepare_scannet_layout.py \
61
+ --scannet-root /path/to/scannet \
62
+ --out-root spar/scannet/images \
63
+ --rgbd \
64
+ --use-video-idx --video-idx-root spar-jsonl/scannet/images \
65
+ --color-pattern "*.jpg" \
66
+ --depth-pattern "*.png"
67
+
68
+ Arguments
69
+ ---------
70
+ --scannet-root PATH Path to official ScanNet root (contains scans/sceneXXXX_XX/...).
71
+ --out-root PATH Output root for SPAR-style layout (e.g., spar/scannet/images).
72
+ --rgbd Also prepare depth/intrinsic/pose (+ create video_depth/video_pose dirs).
73
+ --use-video-idx Build video_color/ as frame{i}_{idx}.jpg using video_idx.txt.
74
+ --video-idx-root PATH Root containing <scene>/video_idx.txt (default: use <out-root>/<scene>/video_idx.txt).
75
+ --scenes-list FILE Optional file listing scene IDs to include (one per line).
76
+ --copy Copy files instead of creating symlinks (default is symlink).
77
+ --dry-run Print planned actions without writing anything.
78
+ --color-pattern STR Glob for color images inside color/ (default: *.jpg).
79
+ --depth-pattern STR Glob for depth images inside depth/ (default: *.png).
80
+
81
+ Caveats
82
+ -------
83
+ - This script **does not** upload any ScanNet content; it only organizes your **local** installation.
84
+ - If you previously committed original images to your repo, remove them and clean history (e.g., git lfs/filter-repo).
85
+ - `video_depth/` and `video_pose/` are created as placeholders; extend the script similarly if you later want to
86
+ materialize depth-based frames with the same index list.
87
+ """
88
+ import argparse, os, shutil, sys, re, subprocess
89
+ from pathlib import Path
90
+ from typing import List, Optional
91
+
92
+ def parse_args():
93
+ p = argparse.ArgumentParser(description="Prepare SPAR-style layout from ScanNet")
94
+ p.add_argument("--scannet-root", type=Path, required=True)
95
+ p.add_argument("--out-root", type=Path, required=True)
96
+ p.add_argument("--rgbd", action="store_true")
97
+ p.add_argument("--copy", action="store_true", help="copy instead of symlink")
98
+ p.add_argument("--dry-run", action="store_true")
99
+ p.add_argument("--scenes-list", type=Path, default=None)
100
+ p.add_argument("--color-pattern", default="*.jpg")
101
+ p.add_argument("--depth-pattern", default="*.png")
102
+ p.add_argument("--use-video-idx", action="store_true",
103
+ help="Read video_idx.txt and materialize video_color as frame{i}_{idx}.jpg")
104
+ p.add_argument("--video-idx-root", type=Path, default=None,
105
+ help="Root that contains <scene>/video_idx.txt (e.g. spar-jsonl/scannet/images). "
106
+ "Default: use --out-root/<scene>/video_idx.txt")
107
+ return p.parse_args()
108
+
109
+ def read_scenes_list(path: Optional[Path]) -> List[str]:
110
+ if not path or not path.exists(): return []
111
+ return [ln.strip() for ln in path.read_text(encoding="utf-8").splitlines() if ln.strip()]
112
+
113
+ def ensure_dir(d: Path, dry=False):
114
+ if dry: print(f"[DRY] mkdir -p {d}"); return
115
+ d.mkdir(parents=True, exist_ok=True)
116
+
117
+ def remove_if_exists(p: Path, dry=False):
118
+ if not p.exists() and not p.is_symlink(): return
119
+ if dry: print(f"[DRY] rm -rf {p}"); return
120
+ if p.is_symlink() or p.is_file(): p.unlink()
121
+ else: shutil.rmtree(p)
122
+
123
+ def link_or_copy(src: Path, dst: Path, do_copy: bool, dry=False):
124
+ if not src.exists():
125
+ print(f"[WARN] Missing source: {src}"); return
126
+ if dst.exists() or dst.is_symlink(): remove_if_exists(dst, dry)
127
+ ensure_dir(dst.parent, dry)
128
+ if dry: print(f"[DRY] {'copy' if do_copy else 'symlink'} {src} -> {dst}"); return
129
+ if do_copy:
130
+ if src.is_dir(): shutil.copytree(src, dst, dirs_exist_ok=True)
131
+ else: shutil.copy2(src, dst)
132
+ else:
133
+ dst.symlink_to(src.resolve(), target_is_directory=src.is_dir())
134
+
135
+ _num_name_re = re.compile(r"(\d+)(?:\.\w+)?$")
136
+
137
+ def _candidate_color_files(color_dir: Path, idx: int) -> List[Path]:
138
+ cands = []
139
+ cands.append(color_dir / f"{idx}.jpg")
140
+ cands.append(color_dir / f"{idx:06d}.jpg")
141
+ cands.append(color_dir / f"{idx}.png")
142
+ cands.append(color_dir / f"{idx:06d}.png")
143
+ for p in color_dir.glob("*.jpg"):
144
+ m = _num_name_re.search(p.stem)
145
+ if m and int(m.group(1)) == idx: cands.append(p)
146
+ for p in color_dir.glob("*.png"):
147
+ m = _num_name_re.search(p.stem)
148
+ if m and int(m.group(1)) == idx: cands.append(p)
149
+ seen, uniq = set(), []
150
+ for p in cands:
151
+ if p.exists() and p not in seen:
152
+ uniq.append(p); seen.add(p)
153
+ return uniq
154
+
155
+ def build_video_color_from_idx(color_dir: Path, video_dir: Path,
156
+ idx_file: Path, do_copy: bool, dry=False):
157
+ if not idx_file.exists():
158
+ print(f"[WARN] video_idx.txt not found: {idx_file}"); return
159
+ ensure_dir(video_dir, dry)
160
+ lines = [ln.strip() for ln in idx_file.read_text(encoding="utf-8").splitlines() if ln.strip()]
161
+ kept = 0
162
+ for i, ln in enumerate(lines):
163
+ try:
164
+ idx = int(ln)
165
+ except ValueError:
166
+ print(f"[WARN] bad line in {idx_file}: {ln}"); continue
167
+ cands = _candidate_color_files(color_dir, idx)
168
+ if not cands:
169
+ print(f"[WARN] no source for idx={idx} in {color_dir}")
170
+ continue
171
+ src = cands[0]
172
+ dst = video_dir / f"frame{i}_{idx}{src.suffix.lower()}"
173
+ link_or_copy(src, dst, do_copy, dry)
174
+ kept += 1
175
+ print(f"[INFO] video_color built: {kept} frames from {len(lines)} indices")
176
+
177
+ def main():
178
+ args = parse_args()
179
+ scans_dir = args.scannet_root / "scans"
180
+ if not scans_dir.exists():
181
+ print(f"[ERR] Expecting {scans_dir}"); sys.exit(1)
182
+
183
+ allow = set(read_scenes_list(args.scenes_list))
184
+ if allow: print(f"[INFO] Filtering {len(allow)} scenes")
185
+
186
+ for scene_dir in sorted(scans_dir.glob("scene*_*")):
187
+ scene = scene_dir.name
188
+ if allow and scene not in allow: continue
189
+ print(f"[SCENE] {scene}")
190
+
191
+ out_scene = args.out_root / scene
192
+ color_src = scene_dir / "image" / "color"
193
+ depth_src = scene_dir / "image" / "depth"
194
+ intr_src = scene_dir / "image" / "intrinsic"
195
+ pose_src = scene_dir / "image" / "pose"
196
+
197
+ color_dst = out_scene / "image_color"
198
+ depth_dst = out_scene / "image_depth"
199
+ intr_dst = out_scene / "intrinsic"
200
+ pose_dst = out_scene / "pose"
201
+ vcolor_dir = out_scene / "video_color"
202
+ vdepth_dir = out_scene / "video_depth"
203
+ vpose_dir = out_scene / "video_pose"
204
+ vidx_default = out_scene / "video_idx.txt"
205
+
206
+ ensure_dir(out_scene, args.dry_run)
207
+
208
+ if color_src.exists(): link_or_copy(color_src, color_dst, args.copy, args.dry_run)
209
+ else: print(f"[WARN] Missing color/: {color_src}")
210
+
211
+ if args.rgbd:
212
+ if depth_src.exists(): link_or_copy(depth_src, depth_dst, args.copy, args.dry_run)
213
+ else: print(f"[WARN] Missing depth/: {depth_src}")
214
+ if intr_src.exists(): link_or_copy(intr_src, intr_dst, args.copy, args.dry_run)
215
+ else: print(f"[WARN] Missing intrinsic/: {intr_src}")
216
+ if pose_src.exists(): link_or_copy(pose_src, pose_dst, args.copy, args.dry_run)
217
+ else: print(f"[WARN] Missing pose/: {pose_src}")
218
+
219
+ ensure_dir(vcolor_dir, args.dry_run)
220
+ if args.rgbd:
221
+ ensure_dir(vdepth_dir, args.dry_run)
222
+ ensure_dir(vpose_dir, args.dry_run)
223
+
224
+ idx_file = vidx_default
225
+ if args.video_idx_root is not None:
226
+ idx_candidate = args.video_idx_root / scene / "video_idx.txt"
227
+ if idx_candidate.exists():
228
+ idx_file = idx_candidate
229
+
230
+ if args.use_video_idx:
231
+ build_video_color_from_idx(color_dst, vcolor_dir, idx_file, args.copy, args.dry_run)
232
+ else:
233
+ ensure_dir(vidx_default.parent, args.dry_run)
234
+ if args.dry_run: print(f"[DRY] touch {vidx_default}")
235
+ else:
236
+ if not vidx_default.exists():
237
+ vidx_default.write_text("", encoding="utf-8")
238
+
239
+ print(f"[DONE] Output root: {args.out_root.resolve()}")
240
+
241
+ if __name__ == "__main__":
242
+ main()