File size: 13,948 Bytes
51bcf93 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 | #!/usr/bin/env python3
"""Batch render scenes from different datasets: generate GLB files and render top/diagonal views.
Supports: scannet, arkitscenes, matterport3d, 3rscan
Usage:
# Step 1: Generate all GLB files (use internscenes environment)
conda activate internscenes
python batch_render_scenes.py --dataset arkitscenes --mode compose --workers 4
# Step 2: Render all views (use blender environment)
conda activate blender
python batch_render_scenes.py --dataset arkitscenes --mode render --workers 8
# Process all datasets
python batch_render_scenes.py --dataset all --mode render --workers 8
"""
from __future__ import annotations
import argparse
import os
import subprocess
import sys
from pathlib import Path
from concurrent.futures import ProcessPoolExecutor, as_completed
from multiprocessing import cpu_count
try:
from tqdm import tqdm
except ImportError:
def tqdm(iterable, desc=None, total=None, **kwargs):
if desc:
print(f"{desc}...")
for i, item in enumerate(iterable):
yield item
tqdm.write = print
# Paths
LAYOUT_INFO_DIR = "/home/v-meiszhang/backup/datas/InternScenes/Layout_info"
ASSET_LIBRARY_DIR = "/home/v-meiszhang/backup/datas/InternScenes/asset_library"
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
BLENDER_RENDERER = os.path.join(SCRIPT_DIR, "blender_renderer.py")
# Set environment variables for compose_scenes.py
os.environ['PTH_ASSET_LIBRARY'] = ASSET_LIBRARY_DIR
os.environ['STRUCTURE_MESH_DIRS'] = LAYOUT_INFO_DIR
# Supported datasets
DATASETS = ["scannet", "arkitscenes", "matterport3d", "3rscan"]
def get_dataset_dir(dataset: str) -> str:
"""Get the directory for a dataset."""
return os.path.join(LAYOUT_INFO_DIR, dataset)
def get_all_scenes(dataset: str) -> list[tuple[str, str]]:
"""Get all scene names and their full paths for a dataset.
Returns list of (scene_name, scene_dir) tuples.
For arkitscenes, handles the Training/Validation subdirectory structure.
"""
dataset_dir = get_dataset_dir(dataset)
scenes = []
if not os.path.isdir(dataset_dir):
print(f"Warning: Dataset directory not found: {dataset_dir}")
return scenes
if dataset == "arkitscenes":
# arkitscenes has Training/Validation subdirectories
for split in ["Training", "Validation"]:
split_dir = os.path.join(dataset_dir, split)
if os.path.isdir(split_dir):
for scene_name in sorted(os.listdir(split_dir)):
scene_path = os.path.join(split_dir, scene_name)
layout_json = os.path.join(scene_path, "layout.json")
if os.path.isdir(scene_path) and os.path.exists(layout_json):
full_scene_name = f"{dataset}/{split}/{scene_name}"
scenes.append((full_scene_name, scene_path))
elif dataset == "matterport3d":
# matterport3d has building/region structure
for building in sorted(os.listdir(dataset_dir)):
building_dir = os.path.join(dataset_dir, building)
if os.path.isdir(building_dir):
for region in sorted(os.listdir(building_dir)):
region_path = os.path.join(building_dir, region)
layout_json = os.path.join(region_path, "layout.json")
if os.path.isdir(region_path) and os.path.exists(layout_json):
full_scene_name = f"{dataset}/{building}/{region}"
scenes.append((full_scene_name, region_path))
else:
# scannet, 3rscan have flat structure
for scene_name in sorted(os.listdir(dataset_dir)):
scene_path = os.path.join(dataset_dir, scene_name)
layout_json = os.path.join(scene_path, "layout.json")
if os.path.isdir(scene_path) and os.path.exists(layout_json):
full_scene_name = f"{dataset}/{scene_name}"
scenes.append((full_scene_name, scene_path))
return scenes
def compose_one_scene(args: tuple[str, str, bool]) -> tuple[str, bool, str]:
"""Compose GLB for a single scene. Returns (scene_name, success, message)."""
full_scene_name, scene_dir, skip_existing = args
# Check if GLB already exists and skip if requested
glb_path = os.path.join(scene_dir, "glb_scene.glb")
if skip_existing and os.path.exists(glb_path) and os.path.getsize(glb_path) > 0:
return full_scene_name, True, "SKIPPED (already exists)"
try:
# Import here to avoid issues when running in blender environment
from compose_scenes import SceneComposer
composer = SceneComposer()
# Override both scene_files_dir and scene_info_dir to use Layout_info directory
composer.scene_files_dir = LAYOUT_INFO_DIR
composer.scene_info_dir = LAYOUT_INFO_DIR
composer.compose_one_scene(
full_scene_name,
use_texture=True,
add_floor=True,
add_wall=False,
add_ceiling=False
)
return full_scene_name, True, "OK"
except Exception as e:
return full_scene_name, False, str(e)
def compose_all_scenes(scenes: list[tuple[str, str]], max_workers: int = 4, skip_existing: bool = False) -> None:
"""Compose GLB files for all scenes using multiprocessing."""
print(f"Composing {len(scenes)} scenes with {max_workers} workers...")
if skip_existing:
print(" (skipping scenes with existing GLB files)")
success_count = 0
skip_count = 0
fail_count = 0
# Add skip_existing flag to each scene tuple
scenes_with_flag = [(name, path, skip_existing) for name, path in scenes]
with ProcessPoolExecutor(max_workers=max_workers) as executor:
futures = {executor.submit(compose_one_scene, scene): scene[0] for scene in scenes_with_flag}
with tqdm(total=len(futures), desc="Composing GLB") as pbar:
for future in as_completed(futures):
scene_name, success, msg = future.result()
if success:
if "SKIPPED" in msg:
skip_count += 1
else:
success_count += 1
else:
fail_count += 1
tqdm.write(f" Failed: {scene_name} - {msg}")
pbar.update(1)
print(f"\nCompose complete: {success_count} success, {skip_count} skipped, {fail_count} failed")
def render_one_scene(args: tuple[str, str, bool]) -> tuple[str, bool, str]:
"""Render top and diagonal views for a single scene."""
full_scene_name, scene_dir, skip_existing = args
try:
glb_path = os.path.join(scene_dir, "glb_scene.glb")
# Output paths (same directory as layout.json)
topdown_output = os.path.join(scene_dir, "render_topdown.png")
diagonal_output = os.path.join(scene_dir, "render_diagonal.png")
# Skip if both renders already exist
if skip_existing:
topdown_exists = os.path.exists(topdown_output) and os.path.getsize(topdown_output) > 0
diagonal_exists = os.path.exists(diagonal_output) and os.path.getsize(diagonal_output) > 0
if topdown_exists and diagonal_exists:
return full_scene_name, True, "SKIPPED"
# Common render arguments - use conda run -n blender to ensure bpy is available
base_args = [
"conda", "run", "-n", "blender", "python", BLENDER_RENDERER,
"--input", glb_path,
"--scene-y-up",
"--engine", "BLENDER_EEVEE",
"--samples", "128",
"--auto-crop",
"--crop-padding", "20",
]
# Render top-down view
topdown_args = base_args + [
"--output", topdown_output,
"--view-mode", "topdown",
"--topdown-height", "1.5",
"--topdown-scale", "1.2",
]
result = subprocess.run(topdown_args, capture_output=True, text=True, timeout=120)
if result.returncode != 0:
return full_scene_name, False, f"Topdown render failed: {result.stderr[:200]}"
# Render diagonal view
diagonal_args = base_args + [
"--output", diagonal_output,
"--view-mode", "diagonal",
"--diagonal-distance", "1.2",
"--diagonal-height-offset", "0.1",
]
result = subprocess.run(diagonal_args, capture_output=True, text=True, timeout=120)
if result.returncode != 0:
return full_scene_name, False, f"Diagonal render failed: {result.stderr[:200]}"
return full_scene_name, True, "OK"
except subprocess.TimeoutExpired:
return full_scene_name, False, "Timeout"
except Exception as e:
return full_scene_name, False, str(e)
def render_all_scenes(scenes: list[tuple[str, str]], max_workers: int = 4, skip_existing: bool = False) -> None:
"""Render all scenes that have GLB files using multiprocessing."""
print(f"Checking {len(scenes)} scenes for rendering...")
# Find scenes with existing valid GLB files (non-empty)
scenes_to_render = []
skipped_empty = 0
skipped_missing = 0
skipped_existing = 0
for full_scene_name, scene_dir in scenes:
glb_path = os.path.join(scene_dir, "glb_scene.glb")
if os.path.exists(glb_path):
if os.path.getsize(glb_path) > 0:
# Check if renders already exist when skip_existing is enabled
if skip_existing:
topdown_output = os.path.join(scene_dir, "render_topdown.png")
diagonal_output = os.path.join(scene_dir, "render_diagonal.png")
if os.path.exists(topdown_output) and os.path.exists(diagonal_output):
skipped_existing += 1
continue
scenes_to_render.append((full_scene_name, scene_dir))
else:
skipped_empty += 1
else:
skipped_missing += 1
print(f"Found {len(scenes_to_render)} scenes to render")
if skipped_existing > 0:
print(f" Skipped {skipped_existing} already rendered scenes")
if skipped_empty > 0:
print(f" Skipped {skipped_empty} empty/corrupted GLB files")
if skipped_missing > 0:
print(f" Skipped {skipped_missing} missing GLB files")
print(f"Using {max_workers} workers")
if not scenes_to_render:
print("No scenes to render!")
return
success_count = 0
fail_count = 0
with ProcessPoolExecutor(max_workers=max_workers) as executor:
futures = {
executor.submit(render_one_scene, (scene[0], scene[1], skip_existing)): scene[0]
for scene in scenes_to_render
}
with tqdm(total=len(futures), desc="Rendering") as pbar:
for future in as_completed(futures):
scene_name, success, msg = future.result()
if success:
success_count += 1
else:
fail_count += 1
tqdm.write(f" Failed: {scene_name} - {msg}")
pbar.update(1)
print(f"\nRender complete: {success_count} success, {fail_count} failed")
def main():
parser = argparse.ArgumentParser(description="Batch process scenes from different datasets")
parser.add_argument(
"--dataset",
choices=DATASETS + ["all"],
default="matterport3d",
help="Dataset to process (default: scannet)"
)
parser.add_argument(
"--mode",
choices=["compose", "render", "all"],
default="all",
help="compose: generate GLB files, render: render views, all: both"
)
parser.add_argument(
"--workers",
type=int,
default=20,
help=f"Number of parallel workers (default: {max(1, cpu_count() // 2)})"
)
parser.add_argument(
"--limit",
type=int,
default=None,
help="Limit number of scenes to process (for testing)"
)
parser.add_argument(
"--start",
type=int,
default=0,
help="Start index for scenes (for resuming)"
)
parser.add_argument(
"--skip-existing",
action="store_true",
default=False,
help="Skip scenes that already have GLB/render files (for resuming)"
)
args = parser.parse_args()
# Get datasets to process
if args.dataset == "all":
datasets_to_process = DATASETS
else:
datasets_to_process = [args.dataset]
for dataset in datasets_to_process:
print(f"\n{'='*60}")
print(f"Processing dataset: {dataset}")
print(f"{'='*60}")
# Get all scenes
all_scenes = get_all_scenes(dataset)
print(f"Found {len(all_scenes)} scenes in {dataset}")
if not all_scenes:
print(f"No scenes found for {dataset}, skipping...")
continue
# Apply limits
scenes = all_scenes[args.start:]
if args.limit:
scenes = scenes[:args.limit]
if args.start > 0 or args.limit:
print(f"Processing scenes {args.start} to {args.start + len(scenes)}")
if args.mode in ["compose", "all"]:
print("\n=== Step 1: Composing GLB files ===")
compose_all_scenes(scenes, max_workers=args.workers, skip_existing=args.skip_existing)
if args.mode in ["render", "all"]:
print("\n=== Step 2: Rendering views ===")
render_all_scenes(scenes, max_workers=args.workers, skip_existing=args.skip_existing)
print("\nAll done!")
if __name__ == "__main__":
main()
|