kkkkiiii's picture
Add files using upload-large-folder tool
51bcf93 verified
Raw
History Blame Contribute Delete
13.9 kB
#!/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()