ZoneMaestro_code / tools /utils /visualize_zone_isolation.py
kkkkiiii's picture
Add files using upload-large-folder tool
6de889a verified
#!/usr/bin/env python3
"""
Zone Isolation Visualization - Render each functional zone independently.
This script renders each zone separately with close-up "in your face" camera views
while ensuring all assets in the zone are visible. Renders 8 views per zone:
- 4 diagonal views (diagonal, diagonal2, diagonal3, diagonal4)
- 4 side views (side_front, side_back, side_left, side_right)
Output structure:
output_dir/
zone_<id>/
diagonal.png
diagonal2.png
diagonal3.png
diagonal4.png
side_front.png
side_back.png
side_left.png
side_right.png
zone_info.json
Based on visualize_zones_progressive.py logic.
"""
import os
import json
import argparse
import subprocess
import sys
import shutil
from pathlib import Path
from typing import List, Dict, Any, Optional, Tuple
from copy import deepcopy
import numpy as np
import trimesh
from trimesh.visual.material import PBRMaterial
# Add project root
SCRIPT_DIR = Path(__file__).parent
REPO_ROOT = SCRIPT_DIR.parent.parent
sys.path.insert(0, str(REPO_ROOT))
# Import from visualize_zones
from tools.utils.visualize_zones import (
ZONE_COLORS,
compute_zone_bbox,
compute_all_zone_bboxes,
get_scene_bounds,
)
# All 8 view modes
DIAGONAL_VIEWS = ["diagonal", "diagonal2", "diagonal3", "diagonal4"]
SIDE_VIEWS = ["side_front", "side_back", "side_left", "side_right"]
ALL_VIEWS = DIAGONAL_VIEWS + SIDE_VIEWS
def run_command(cmd, env=None, quiet=False):
"""Run a shell command."""
if not quiet:
print(f" Running: {cmd[:100]}...")
try:
if quiet:
subprocess.check_call(cmd, shell=True, env=env,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
else:
subprocess.check_call(cmd, shell=True, env=env)
return True
except subprocess.CalledProcessError as e:
print(f" Command failed: {e}")
return False
def compose_single_zone_scene(
layout: Dict,
zone_index: int,
output_path: str,
use_retrieval: bool = True,
embedding_manager=None,
asset_finder=None,
) -> str:
"""
Compose a scene with only a single zone's assets.
Args:
layout: Full layout dictionary
zone_index: Index of zone to include (0-based)
output_path: Output GLB path
use_retrieval: Whether to run asset retrieval
embedding_manager: Pre-initialized embedding manager
asset_finder: Pre-initialized asset finder
Returns:
Path to composed GLB
"""
from tools.data_gen.compose_generated import compose_scene
# Create layout with only the selected zone
partial_layout = deepcopy(layout)
all_zones = layout.get('functional_zones', [])
if zone_index >= len(all_zones):
raise ValueError(f"Zone index {zone_index} out of range (total: {len(all_zones)})")
# Keep only the specified zone
partial_layout['functional_zones'] = [all_zones[zone_index]]
# Remove top-level assets to avoid duplication
partial_layout.pop('assets', None)
partial_layout.pop('groups', None)
if use_retrieval:
from tools.data_gen.layout_retrieval import process_layout
# Use provided managers or create new ones
if embedding_manager is None or asset_finder is None:
from tools.asset_description.asset_embedding_manager import AssetEmbeddingManager
from tools.asset_description.asset_finder import AssetFinder
asset_library_dir = os.path.join(REPO_ROOT, "data/asset_library")
embeddings_file = os.path.join(REPO_ROOT, "tools/asset_embeddings.pkl")
embedding_manager = AssetEmbeddingManager(embeddings_file=embeddings_file)
asset_finder = AssetFinder(asset_library_dir)
partial_layout = process_layout(partial_layout, embedding_manager, asset_finder)
# Compose scene - no floor, walls, or ceiling for isolated zone view
compose_scene(
layout=partial_layout,
output_path=output_path,
add_floor=False,
add_walls=False,
add_ceiling=False,
)
return output_path
def compute_zone_camera_params(zone_info: Dict) -> Dict:
"""
Compute camera parameters to get a close-up view of the zone.
Args:
zone_info: Zone info dict with bbox
Returns:
Dict with camera parameters
"""
bbox = zone_info['bbox']
bbox_min = np.array(bbox['min'])
bbox_max = np.array(bbox['max'])
# Compute center and size
center = (bbox_min + bbox_max) / 2.0
size = bbox_max - bbox_min
# Diagonal of the bbox - determines how far camera needs to be
diagonal = np.linalg.norm(size)
# For close-up view, use smaller distance factor
# The camera will be positioned at diagonal_distance * diagonal from center
camera_distance_factor = 0.8 # Close-up but still see everything
return {
'center': center.tolist(),
'size': size.tolist(),
'diagonal': float(diagonal),
'camera_distance_factor': camera_distance_factor,
}
def render_zone_view(
glb_path: str,
output_path: str,
view_mode: str,
zone_camera_params: Dict,
width: int = 1600,
height: int = 1200,
engine: str = "BLENDER_EEVEE",
samples: int = 256,
):
"""
Render a zone from a specific view with close-up camera.
Args:
glb_path: Input GLB path
output_path: Output PNG path
view_mode: Camera view mode
zone_camera_params: Camera parameters computed from zone bbox
width: Image width
height: Image height
engine: Blender render engine
samples: Number of samples
"""
current_env = os.environ.copy()
# Use smaller diagonal distance for close-up view
diagonal_distance = zone_camera_params['camera_distance_factor']
# High quality render args similar to visualize_gt_hq.py
HQ_RENDER_ARGS = (
f"--engine {engine} --samples {samples} "
"--fill-lights "
"--floor-material solid" # Simple floor for zone isolation
)
# Side views get slight elevation angle for better perspective
elevation_arg = ""
if view_mode.startswith("side_"):
elevation_arg = "--side-elevation-angle 25"
cmd = (
f"conda run -n blender python InternScenes/InternScenes_Real2Sim/blender_renderer.py "
f"--input '{glb_path}' "
f"--output '{output_path}' "
f"--width {width} --height {height} "
f"--view-mode {view_mode} "
f"--diagonal-distance {diagonal_distance} "
f"--camera-factor 1.2 " # Slightly wider field of view
f"{elevation_arg} "
f"{HQ_RENDER_ARGS}"
)
return run_command(cmd, env=current_env, quiet=True)
def visualize_zone_isolation(
layout_path: str,
output_dir: str,
use_retrieval: bool = True,
render_diagonal: bool = True,
render_side: bool = True,
width: int = 1600,
height: int = 1200,
engine: str = "BLENDER_EEVEE",
samples: int = 256,
zone_indices: List[int] = None,
):
"""
Main function: render each zone independently with close-up views.
Args:
layout_path: Path to layout.json file
output_dir: Directory to save outputs
use_retrieval: Whether to run asset retrieval
render_diagonal: Whether to render 4 diagonal views
render_side: Whether to render 4 side views
width: Image width
height: Image height
engine: Blender render engine
samples: Number of render samples
zone_indices: Specific zone indices to render (None = all zones)
"""
print(f"\n{'='*60}")
print(f"Zone Isolation Visualization")
print(f"{'='*60}")
print(f"Input: {layout_path}")
print(f"Output: {output_dir}")
print(f"Engine: {engine}, Samples: {samples}")
print(f"Resolution: {width}x{height}")
print(f"{'='*60}\n")
# Load layout
with open(layout_path, 'r') as f:
layout = json.load(f)
# Create output directory
os.makedirs(output_dir, exist_ok=True)
# Get zones info
functional_zones = layout.get('functional_zones', [])
n_zones = len(functional_zones)
if n_zones == 0:
print("Error: No functional zones found in layout!")
return
print(f"Found {n_zones} functional zones")
# Compute zone bboxes
print("\nComputing zone bounding boxes...")
zones_info = compute_all_zone_bboxes(layout)
if len(zones_info) == 0:
print("Error: No valid zones with bbox found!")
return
# Map zone_id to original index
zone_id_to_original_idx = {}
for i, zone in enumerate(functional_zones):
zone_id = zone.get('id', f'zone_{i}')
zone_id_to_original_idx[zone_id] = i
for zone_info in zones_info:
zone_info['original_index'] = zone_id_to_original_idx.get(zone_info['zone_id'], -1)
# Filter to specific zone indices if provided
if zone_indices is not None:
zones_info = [z for z in zones_info if z['original_index'] in zone_indices]
print(f"Filtering to {len(zones_info)} specified zones")
# Print zone info
print("\nZones to render:")
for zone_info in zones_info:
print(f" [{zone_info['original_index']}] {zone_info['zone_id']}: {zone_info['semantic_label']} ({zone_info['asset_count']} assets)")
# Determine views to render
views_to_render = []
if render_diagonal:
views_to_render.extend(DIAGONAL_VIEWS)
if render_side:
views_to_render.extend(SIDE_VIEWS)
if not views_to_render:
print("Error: No views to render! Enable at least --diagonal or --side")
return
print(f"\nViews to render per zone: {views_to_render}")
# Create temp directory for intermediate GLBs
temp_dir = os.path.join(output_dir, "_temp")
os.makedirs(temp_dir, exist_ok=True)
# Initialize embedding manager and asset finder once
embedding_manager = None
asset_finder = None
if use_retrieval:
print("\nInitializing asset retrieval system...")
from tools.asset_description.asset_embedding_manager import AssetEmbeddingManager
from tools.asset_description.asset_finder import AssetFinder
asset_library_dir = os.path.join(REPO_ROOT, "data/asset_library")
embeddings_file = os.path.join(REPO_ROOT, "tools/asset_embeddings.pkl")
embedding_manager = AssetEmbeddingManager(embeddings_file=embeddings_file)
asset_finder = AssetFinder(asset_library_dir)
print(" Asset retrieval system initialized.")
# Process each zone
for zone_info in zones_info:
zone_id = zone_info['zone_id']
zone_idx = zone_info['original_index']
semantic_label = zone_info['semantic_label']
print(f"\n{'='*50}")
print(f"Processing Zone: {zone_id} ({semantic_label})")
print(f"{'='*50}")
# Create zone output directory
zone_output_dir = os.path.join(output_dir, f"zone_{zone_id}")
os.makedirs(zone_output_dir, exist_ok=True)
# Compose scene with only this zone's assets
zone_glb_path = os.path.join(temp_dir, f"zone_{zone_id}_scene.glb")
print(f" Composing zone scene...")
try:
compose_single_zone_scene(
layout=layout,
zone_index=zone_idx,
output_path=zone_glb_path,
use_retrieval=use_retrieval,
embedding_manager=embedding_manager,
asset_finder=asset_finder,
)
except Exception as e:
print(f" Error composing zone: {e}")
continue
# Compute camera params for close-up view
camera_params = compute_zone_camera_params(zone_info)
print(f" Zone bbox diagonal: {camera_params['diagonal']:.2f}m")
# Render all views
for view in views_to_render:
output_img = os.path.join(zone_output_dir, f"{view}.png")
print(f" Rendering {view}...")
success = render_zone_view(
glb_path=zone_glb_path,
output_path=output_img,
view_mode=view,
zone_camera_params=camera_params,
width=width,
height=height,
engine=engine,
samples=samples,
)
if success and os.path.exists(output_img):
print(f" ✓ Saved: {output_img}")
else:
print(f" ✗ Failed to render {view}")
# Save zone info
zone_info_path = os.path.join(zone_output_dir, "zone_info.json")
zone_info_to_save = {
'zone_id': zone_id,
'semantic_label': semantic_label,
'asset_count': zone_info['asset_count'],
'bbox': zone_info['bbox'],
'camera_params': camera_params,
}
with open(zone_info_path, 'w') as f:
json.dump(zone_info_to_save, f, indent=2)
# Clean up temp directory
# shutil.rmtree(temp_dir) # Uncomment to auto-clean
print(f"\n{'='*60}")
print(f"Done! Outputs saved to: {output_dir}")
print(f"{'='*60}")
# Summary
print("\n=== Output Summary ===")
for zone_info in zones_info:
zone_id = zone_info['zone_id']
zone_dir = os.path.join(output_dir, f"zone_{zone_id}")
if os.path.exists(zone_dir):
files = [f for f in os.listdir(zone_dir) if f.endswith('.png')]
print(f" zone_{zone_id}/: {len(files)} images")
def main():
parser = argparse.ArgumentParser(
description="Render each functional zone independently with close-up views",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Basic usage - render all zones with all 8 views
python visualize_zone_isolation.py --input layout.json --output zone_output
# Render only diagonal views
python visualize_zone_isolation.py --input layout.json --output zone_output --no-side
# Render only side views
python visualize_zone_isolation.py --input layout.json --output zone_output --no-diagonal
# Render specific zones only (by index)
python visualize_zone_isolation.py --input layout.json --output zone_output --zones 0 2 3
# Higher quality with CYCLES
python visualize_zone_isolation.py --input layout.json --output zone_output --engine CYCLES --samples 512
# Higher resolution
python visualize_zone_isolation.py --input layout.json --output zone_output --width 2400 --height 1800
Views rendered per zone:
Diagonal: diagonal, diagonal2, diagonal3, diagonal4
Side: side_front, side_back, side_left, side_right
"""
)
parser.add_argument("--input", default="case_hq/H-shaped_01_001536_1766364802273481/layout_retrieved/layout_retrieved.json", help="Path to layout JSON file")
parser.add_argument("--output", default="zone_isolation_output1536", help="Output directory")
parser.add_argument("--no-retrieval", action="store_true", help="Skip asset retrieval (use existing model_uid)")
parser.add_argument("--no-diagonal", action="store_true", help="Skip diagonal views")
parser.add_argument("--no-side", action="store_true", help="Skip side views")
parser.add_argument("--zones", type=int, nargs="+", help="Specific zone indices to render")
parser.add_argument("--width", type=int, default=1600, help="Image width (default: 1600)")
parser.add_argument("--height", type=int, default=1200, help="Image height (default: 1200)")
parser.add_argument("--engine", default="BLENDER_EEVEE", choices=["BLENDER_EEVEE", "CYCLES"],
help="Blender render engine (default: BLENDER_EEVEE)")
parser.add_argument("--samples", type=int, default=256, help="Render samples (default: 256)")
args = parser.parse_args()
visualize_zone_isolation(
layout_path=args.input,
output_dir=args.output,
use_retrieval=not args.no_retrieval,
render_diagonal=not args.no_diagonal,
render_side=not args.no_side,
width=args.width,
height=args.height,
engine=args.engine,
samples=args.samples,
zone_indices=args.zones,
)
if __name__ == "__main__":
main()