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

Upload prepare_scannetpp_layout.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. prepare_scannetpp_layout.py +204 -0
prepare_scannetpp_layout.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Prepare SPAR-style layout from an official ScanNet++ installation (RGB only).
5
+ - Build image_color/ as 0.jpg, 1.jpg, ...
6
+ - READ an existing video_idx.txt and materialize video_color/frame{i}_{idx}.jpg
7
+ by locating source frames in iphone/rgb/frame_{idx:06d}.jpg.
8
+
9
+ Source (official):
10
+ scannetpp/
11
+ scans/<scene_id>/iphone/rgb/frame_000000.jpg
12
+
13
+ Target (created locally; nothing uploaded):
14
+ scannetpp/
15
+ images/<scene_id>/
16
+ image_color/ 0.jpg, 1.jpg, 2.jpg, ...
17
+ video_color/ frame0_0.jpg, frame1_35.jpg, ...
18
+ video_idx.txt (must already exist; read-only)
19
+
20
+ Examples
21
+ --------
22
+ # Basic usage (read video_idx.txt from <out-root>/<scene>/video_idx.txt):
23
+ python tools/prepare_scannetpp_layout.py \
24
+ --scannetpp-root /path/to/scannetpp \
25
+ --out-root scannetpp/images \
26
+ --use-video-idx
27
+
28
+ # If your idx files live under a different root (e.g., scannetpp/images/<scene>/video_idx.txt):
29
+ python tools/prepare_scannetpp_layout.py \
30
+ --scannetpp-root /path/to/scannetpp \
31
+ --out-root scannetpp/images \
32
+ --use-video-idx \
33
+ --video-idx-root scannetpp/images
34
+
35
+ # Process only selected scenes (one per line), dry-run first:
36
+ python tools/prepare_scannetpp_layout.py \
37
+ --scannetpp-root /path/to/scannetpp \
38
+ --out-root scannetpp/images \
39
+ --scenes-list scenes_scannetpp.txt \
40
+ --use-video-idx \
41
+ --dry-run
42
+ """
43
+
44
+ import argparse, os, re, shutil, sys
45
+ from pathlib import Path
46
+ from typing import List, Optional, Tuple
47
+
48
+ def parse_args():
49
+ p = argparse.ArgumentParser(description="Prepare SPAR-style layout from ScanNet++ (RGB only)")
50
+ p.add_argument("--scannetpp-root", type=Path, required=True,
51
+ help="Path to official ScanNet++ root (must contain 'scans/<scene_id>/iphone/rgb').")
52
+ p.add_argument("--out-root", type=Path, required=True,
53
+ help="Output root, e.g., scannetpp/images")
54
+ p.add_argument("--rgb-subdir", type=str, default="iphone/rgb",
55
+ help="Relative path under each scene to RGB frames (default: iphone/rgb).")
56
+ p.add_argument("--rgb-pattern", type=str, default="frame_*.jpg",
57
+ help="Glob pattern for RGB frames (default: frame_*.jpg).")
58
+ p.add_argument("--force-ext", type=str, default=".jpg",
59
+ help="Extension for output files (default: .jpg). Use '' to preserve source suffix.")
60
+ p.add_argument("--copy", action="store_true",
61
+ help="Copy files instead of symlink (default: symlink).")
62
+ p.add_argument("--dry-run", action="store_true",
63
+ help="Print actions without writing anything.")
64
+ p.add_argument("--scenes-list", type=Path, default=None,
65
+ help="Optional text file listing scene IDs to include (one per line).")
66
+
67
+ # 读取现有 video_idx.txt 并据此生成 video_color/
68
+ p.add_argument("--use-video-idx", action="store_true",
69
+ help="Read existing <scene>/video_idx.txt and build video_color/frame{i}_{idx}.jpg")
70
+ p.add_argument("--video-idx-root", type=Path, default=None,
71
+ help="Root containing <scene>/video_idx.txt (default: use --out-root/<scene>/video_idx.txt)")
72
+
73
+ return p.parse_args()
74
+
75
+ def read_scenes_list(path: Optional[Path]) -> List[str]:
76
+ if not path or not path.exists(): return []
77
+ return [ln.strip() for ln in path.read_text(encoding="utf-8").splitlines() if ln.strip()]
78
+
79
+ def ensure_dir(d: Path, dry: bool):
80
+ if dry: print(f"[DRY] mkdir -p {d}")
81
+ else: d.mkdir(parents=True, exist_ok=True)
82
+
83
+ def remove_if_exists(p: Path, dry: bool):
84
+ if not p.exists() and not p.is_symlink(): return
85
+ if dry: print(f"[DRY] rm -rf {p}"); return
86
+ if p.is_symlink() or p.is_file(): p.unlink()
87
+ else: shutil.rmtree(p)
88
+
89
+ def link_or_copy(src: Path, dst: Path, do_copy: bool, dry: bool):
90
+ if not src.exists():
91
+ print(f"[WARN] Missing source: {src}"); return
92
+ if dst.exists() or dst.is_symlink():
93
+ remove_if_exists(dst, dry)
94
+ ensure_dir(dst.parent, dry)
95
+ if dry:
96
+ print(f"[DRY] {'copy' if do_copy else 'symlink'} {src} -> {dst}")
97
+ return
98
+ if do_copy: shutil.copy2(src, dst)
99
+ else: dst.symlink_to(src.resolve())
100
+
101
+ _num_re = re.compile(r"(\d+)")
102
+
103
+ def extract_frame_index(name: str) -> Optional[int]:
104
+ m = _num_re.search(name)
105
+ if not m: return None
106
+ try: return int(m.group(1))
107
+ except ValueError: return None
108
+
109
+ def sorted_rgb_frames(rgb_dir: Path, pattern: str) -> List[Tuple[Path, int]]:
110
+ files = list(rgb_dir.glob(pattern))
111
+ items = []
112
+ for f in files:
113
+ idx = extract_frame_index(f.name) or extract_frame_index(f.stem)
114
+ if idx is None: continue
115
+ items.append((f, idx))
116
+ items.sort(key=lambda x: x[1]) # sort by original index
117
+ return items
118
+
119
+ def find_rgb_by_index(rgb_dir: Path, idx: int) -> Optional[Path]:
120
+ # 尝试常见扩展名
121
+ for ext in (".jpg", ".jpeg", ".png"):
122
+ cand = rgb_dir / f"frame_{idx:06d}{ext}"
123
+ if cand.exists(): return cand
124
+ # ��底:遍历一遍(慢,但稳)
125
+ for f in rgb_dir.iterdir():
126
+ if not f.is_file(): continue
127
+ i = extract_frame_index(f.name) or extract_frame_index(f.stem)
128
+ if i == idx: return f
129
+ return None
130
+
131
+ def main():
132
+ args = parse_args()
133
+
134
+ scans_dir = args.scannetpp_root / "scans"
135
+ if not scans_dir.exists():
136
+ print(f"[ERR] Expecting {scans_dir}")
137
+ sys.exit(1)
138
+
139
+ allow = set(read_scenes_list(args.scenes_list))
140
+ if allow: print(f"[INFO] Filtering {len(allow)} scenes")
141
+
142
+ n_scenes = 0
143
+ for scene_dir in sorted((p for p in scans_dir.iterdir() if p.is_dir()),
144
+ key=lambda p: p.name):
145
+ scene = scene_dir.name # e.g., "0a5c013435"
146
+ if allow and scene not in allow:
147
+ continue
148
+
149
+ rgb_dir = scene_dir / args.rgb_subdir
150
+ if not rgb_dir.exists():
151
+ print(f"[WARN] Skip {scene}: RGB dir not found: {rgb_dir}")
152
+ continue
153
+
154
+ frames = sorted_rgb_frames(rgb_dir, args.rgb_pattern)
155
+ if not frames:
156
+ print(f"[WARN] Skip {scene}: no frames matching {args.rgb_pattern} in {rgb_dir}")
157
+ continue
158
+
159
+ print(f"[SCENE] {scene} (frames: {len(frames)})")
160
+
161
+ # 1) image_color/: 0.jpg, 1.jpg, ...
162
+ out_scene = args.out_root / scene / "image_color"
163
+ ensure_dir(out_scene, args.dry_run)
164
+ for i, (src, orig_idx) in enumerate(frames):
165
+ dst = out_scene / (f"{i}{args.force_ext}" if args.force_ext else f"{i}{src.suffix.lower()}")
166
+ link_or_copy(src, dst, args.copy, args.dry_run)
167
+
168
+ # 2) video_color/: read video_idx.txt → frame{i}_{idx}.jpg
169
+ if args.use_video_idx:
170
+ idx_file = (args.out_root / scene / "video_idx.txt")
171
+ if args.video_idx_root is not None:
172
+ cand = args.video_idx_root / scene / "video_idx.txt"
173
+ if cand.exists(): idx_file = cand
174
+
175
+ if not idx_file.exists():
176
+ print(f"[WARN] {scene}: video_idx.txt not found at {idx_file}; skip video_color")
177
+ else:
178
+ vcolor_dir = args.out_root / scene / "video_color"
179
+ ensure_dir(vcolor_dir, args.dry_run)
180
+ lines = [ln.strip() for ln in idx_file.read_text(encoding="utf-8").splitlines() if ln.strip()]
181
+ kept = 0
182
+ for i, ln in enumerate(lines):
183
+ try:
184
+ idx = int(ln)
185
+ except ValueError:
186
+ print(f"[WARN] {scene}: bad index '{ln}' in {idx_file}"); continue
187
+ src = find_rgb_by_index(rgb_dir, idx)
188
+ if src is None:
189
+ print(f"[WARN] {scene}: source not found for idx={idx}")
190
+ continue
191
+ # frame{i}_{idx}.<ext>
192
+ ext = (args.force_ext if args.force_ext else src.suffix.lower()) or ".jpg"
193
+ dst = vcolor_dir / f"frame{i}_{idx}{ext}"
194
+ link_or_copy(src, dst, args.copy, args.dry_run)
195
+ kept += 1
196
+ print(f"[INFO] {scene}: video_color built: {kept}/{len(lines)}")
197
+
198
+ n_scenes += 1
199
+
200
+ print(f"[DONE] Scenes processed: {n_scenes}")
201
+ print(f"[INFO] Output root: {args.out_root.resolve()}")
202
+
203
+ if __name__ == "__main__":
204
+ main()