jasonzhango commited on
Commit
98f59d5
·
verified ·
1 Parent(s): 21ab52b

Upload prepare_structured3d_layout.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. prepare_structured3d_layout.py +243 -0
prepare_structured3d_layout.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Prepare SPAR-style layout from an official Structured3D installation (RGB only).
5
+
6
+ Source (official-like):
7
+ Structured3D/
8
+ scene_02199/
9
+ 2D_rendering/
10
+ 3972/
11
+ perspective/
12
+ full/
13
+ 0/
14
+ rgb_rawlight.png
15
+ 1/
16
+ rgb_rawlight.png
17
+ ...
18
+
19
+ Target (created locally; nothing uploaded):
20
+ structured3d/
21
+ images/<scene_id>/
22
+ image_color/
23
+ <view_id>_<cam_id>.jpg # e.g., 3972_0.jpg
24
+
25
+ Notes
26
+ -----
27
+ - Only image_color is generated (no video dirs).
28
+ - By default, we CONVERT source PNG → JPG with a configurable quality.
29
+ - If you want to keep source suffix (e.g., .png), pass --force-ext ".png".
30
+
31
+ Usage (examples)
32
+ ----------------
33
+ # Convert all scenes, default: rgb_rawlight.png → JPG quality=95
34
+ python tools/prepare_structured3d_layout.py \
35
+ --structured3d-root /path/to/Structured3D \
36
+ --out-root structured3d/images
37
+
38
+ # Only selected scenes, keep PNG suffix, dry-run first:
39
+ python tools/prepare_structured3d_layout.py \
40
+ --structured3d-root /path/to/Structured3D \
41
+ --out-root structured3d/images \
42
+ --scenes-list scenes_structured3d.txt \
43
+ --force-ext ".png" \
44
+ --dry-run
45
+
46
+ # If your file name is different (e.g., rgb_nolight.png), or try fallbacks:
47
+ python tools/prepare_structured3d_layout.py \
48
+ --structured3d-root /path/to/Structured3D \
49
+ --out-root structured3d/images \
50
+ --rgb-name rgb_nolight.png \
51
+ --fallback-rgb rgb_rawlight.png rgb_shading.png
52
+ """
53
+
54
+ import argparse
55
+ import os
56
+ import re
57
+ import sys
58
+ import shutil
59
+ from pathlib import Path
60
+ from typing import List, Optional, Tuple
61
+
62
+ try:
63
+ from PIL import Image
64
+ except Exception:
65
+ Image = None # 若未安装 Pillow,且要求转 JPG,会提示
66
+
67
+ def parse_args():
68
+ p = argparse.ArgumentParser(description="Prepare SPAR-style layout from Structured3D (RGB only)")
69
+ p.add_argument("--structured3d-root", type=Path, required=True,
70
+ help="Path to Structured3D root (contains scene_XXXX/2D_rendering/...).")
71
+ p.add_argument("--out-root", type=Path, required=True,
72
+ help="Output root, e.g., structured3d/images")
73
+ p.add_argument("--scenes-list", type=Path, default=None,
74
+ help="Optional file listing scene IDs to include (one per line, e.g., scene_02199).")
75
+
76
+ # File picking
77
+ p.add_argument("--rgb-name", type=str, default="rgb_rawlight.png",
78
+ help="Preferred RGB filename under .../perspective/full/<cam>/ (default: rgb_rawlight.png)")
79
+ p.add_argument("--fallback-rgb", type=str, nargs="*", default=["rgb_nolight.png", "rgb_shading.png"],
80
+ help="Fallback filenames to try if --rgb-name not found.")
81
+
82
+ # Output naming & format
83
+ p.add_argument("--force-ext", type=str, default=".jpg",
84
+ help="Output extension (default: .jpg). Use '.png' to keep PNG, or '' to preserve source suffix.")
85
+ p.add_argument("--jpg-quality", type=int, default=95,
86
+ help="JPEG quality if converting to JPEG (default: 95).")
87
+
88
+ # Safety & speed
89
+ p.add_argument("--dry-run", action="store_true",
90
+ help="Print actions without writing anything.")
91
+ p.add_argument("--copy", action="store_true",
92
+ help="Copy bytes instead of converting when suffix matches or --force-ext='' and src suffix equals dst suffix.")
93
+
94
+ return p.parse_args()
95
+
96
+ def read_scenes_list(path: Optional[Path]) -> List[str]:
97
+ if not path or not path.exists():
98
+ return []
99
+ return [ln.strip() for ln in path.read_text(encoding="utf-8").splitlines() if ln.strip()]
100
+
101
+ def ensure_dir(d: Path, dry: bool):
102
+ if dry:
103
+ print(f"[DRY] mkdir -p {d}")
104
+ else:
105
+ d.mkdir(parents=True, exist_ok=True)
106
+
107
+ def save_image_convert(src: Path, dst: Path, force_ext: str, jpg_quality: int, dry: bool, copy_bytes: bool):
108
+ """
109
+ Save/convert image:
110
+ - If force_ext is '', preserve source suffix.
111
+ - If force_ext is '.jpg' or '.png', force the target suffix/format.
112
+ - If copy_bytes is True and suffixes match, do a byte copy.
113
+ - Otherwise, convert with Pillow (if available).
114
+ """
115
+ # Decide dst suffix
116
+ if force_ext:
117
+ dst = dst.with_suffix(force_ext)
118
+ else:
119
+ dst = dst.with_suffix(src.suffix.lower())
120
+
121
+ if dry:
122
+ print(f"[DRY] write {dst} (from {src})")
123
+ return
124
+
125
+ if copy_bytes and dst.suffix.lower() == src.suffix.lower():
126
+ # Direct byte copy
127
+ dst.parent.mkdir(parents=True, exist_ok=True)
128
+ shutil.copy2(src, dst)
129
+ return
130
+
131
+ # Convert via Pillow if needed
132
+ if Image is None:
133
+ raise RuntimeError("Pillow is not installed, cannot convert images. Install 'Pillow' or use --copy with matching suffix.")
134
+
135
+ img = Image.open(src)
136
+ # Ensure RGB for JPEG
137
+ if dst.suffix.lower() in [".jpg", ".jpeg"] and img.mode not in ("RGB", "L"):
138
+ img = img.convert("RGB")
139
+ dst.parent.mkdir(parents=True, exist_ok=True)
140
+ if dst.suffix.lower() in [".jpg", ".jpeg"]:
141
+ img.save(dst, format="JPEG", quality=jpg_quality, optimize=True)
142
+ elif dst.suffix.lower() == ".png":
143
+ img.save(dst, format="PNG")
144
+ else:
145
+ # Other formats if Pillow supports
146
+ img.save(dst)
147
+
148
+ def find_rgb_file(cam_dir: Path, prefer: str, fallbacks: List[str]) -> Optional[Path]:
149
+ """Pick rgb file under a camera directory by preferred filename then fallbacks."""
150
+ cand = cam_dir / prefer
151
+ if cand.exists():
152
+ return cand
153
+ for fb in fallbacks:
154
+ c = cam_dir / fb
155
+ if c.exists():
156
+ return c
157
+ # As a last resort: any png with 'rgb' in name
158
+ for f in cam_dir.glob("*.png"):
159
+ if "rgb" in f.name:
160
+ return f
161
+ return None
162
+
163
+ def list_scenes(structured3d_root: Path) -> List[Path]:
164
+ # scene directories typically named 'scene_XXXXX'
165
+ return sorted([p for p in structured3d_root.iterdir() if p.is_dir() and p.name.startswith("scene_")],
166
+ key=lambda p: p.name)
167
+
168
+ def process_scene(scene_dir: Path, out_root: Path,
169
+ prefer_name: str, fallback_names: List[str],
170
+ force_ext: str, jpg_quality: int, dry: bool, copy_bytes: bool) -> int:
171
+ """
172
+ Returns number of images written for this scene.
173
+ """
174
+ scene_id = scene_dir.name
175
+ twoD = scene_dir / "2D_rendering"
176
+ if not twoD.exists():
177
+ print(f"[WARN] Skip {scene_id}: 2D_rendering not found")
178
+ return 0
179
+
180
+ # Layout: 2D_rendering/<view_id>/perspective/full/<cam_id>/<rgb_file>
181
+ count = 0
182
+ for view_dir in sorted([p for p in twoD.iterdir() if p.is_dir() and p.name.isdigit()],
183
+ key=lambda p: int(p.name)):
184
+ view_id = view_dir.name
185
+ persp = view_dir / "perspective" / "full"
186
+ if not persp.exists():
187
+ # Some scenes may not have 'perspective/full'
188
+ # Try a broader search if needed (not typical)
189
+ print(f"[WARN] {scene_id}: perspective/full not found in view {view_id}")
190
+ continue
191
+
192
+ # iterate cameras under 'full'
193
+ cam_dirs = sorted([p for p in persp.iterdir() if p.is_dir()],
194
+ key=lambda p: p.name)
195
+ for cam_dir in cam_dirs:
196
+ cam_id = cam_dir.name # e.g., "0", "1"
197
+ src = find_rgb_file(cam_dir, prefer_name, fallback_names)
198
+ if src is None:
199
+ print(f"[WARN] {scene_id}: missing RGB under {cam_dir}")
200
+ continue
201
+
202
+ out_scene = out_root / scene_id / "image_color"
203
+ ensure_dir(out_scene, dry)
204
+ dst_name = f"{view_id}_{cam_id}"
205
+ dst = out_scene / dst_name # suffix assigned in save_image_convert
206
+ try:
207
+ save_image_convert(src, dst, force_ext, jpg_quality, dry, copy_bytes)
208
+ count += 1
209
+ except Exception as e:
210
+ print(f"[WARN] {scene_id}: convert failed for {src} → {dst}: {e}")
211
+
212
+ if count == 0:
213
+ print(f"[WARN] {scene_id}: no images written")
214
+ else:
215
+ print(f"[INFO] {scene_id}: images written: {count}")
216
+ return count
217
+
218
+ def main():
219
+ args = parse_args()
220
+
221
+ root = args.structured3d_root
222
+ if not root.exists():
223
+ print(f"[ERR] Structured3D root not found: {root}")
224
+ sys.exit(1)
225
+
226
+ allow = set(read_scenes_list(args.scenes_list))
227
+ if allow:
228
+ print(f"[INFO] Filtering {len(allow)} scenes")
229
+
230
+ total = 0
231
+ for scene_dir in list_scenes(root):
232
+ if allow and scene_dir.name not in allow:
233
+ continue
234
+ total += process_scene(scene_dir, args.out_root,
235
+ args.rgb_name, args.fallback_rgb,
236
+ args.force_ext, args.jpg_quality,
237
+ args.dry_run, args.copy)
238
+
239
+ print(f"[DONE] Scenes processed: {total}")
240
+ print(f"[INFO] Output root: {args.out_root.resolve()}")
241
+
242
+ if __name__ == "__main__":
243
+ main()