ZoneMaestro_code / tools /utils /visualize_zones.py
kkkkiiii's picture
Add files using upload-large-folder tool
afb311a verified
"""
Visualize functional zones in a 3D indoor scene layout.
Each zone is rendered with a colored bounding box encompassing all its assets.
"""
import os
import json
import argparse
import subprocess
import sys
import tempfile
import shutil
from pathlib import Path
from typing import List, Dict, Any, Optional, Tuple
# Add project root
SCRIPT_DIR = Path(__file__).parent
REPO_ROOT = SCRIPT_DIR.parent.parent
sys.path.insert(0, str(REPO_ROOT))
# Predefined colors for zones (distinguishable colors)
ZONE_COLORS = [
(1.0, 0.2, 0.2), # Red
(0.2, 0.8, 0.2), # Green
(0.2, 0.4, 1.0), # Blue
(1.0, 0.8, 0.0), # Yellow
(1.0, 0.4, 0.8), # Pink
(0.0, 0.9, 0.9), # Cyan
(0.9, 0.5, 0.0), # Orange
(0.6, 0.2, 0.8), # Purple
(0.5, 0.9, 0.5), # Light Green
(0.9, 0.3, 0.5), # Coral
(0.3, 0.7, 0.9), # Sky Blue
(0.8, 0.8, 0.3), # Olive
]
def get_asset_position_size(asset: Dict) -> Tuple[Optional[List[float]], Optional[List[float]]]:
"""
Extract position and size from asset, handling different data formats.
Supports:
- asset['transform']['pos'] / asset['transform']['size']
- asset['position'] / asset['size']
- asset['pos'] / asset['size']
"""
pos = None
size = None
# Try transform format first (unified-layout-aligned format)
if 'transform' in asset:
transform = asset['transform']
pos = transform.get('pos') or transform.get('position')
size = transform.get('size')
# Fallback to direct fields
if pos is None:
pos = asset.get('pos') or asset.get('position')
if size is None:
size = asset.get('size')
return pos, size
def get_scene_bounds(layout: Dict) -> Optional[Dict[str, List[float]]]:
"""
Get scene boundary from layout's architecture.boundary_polygon.
Returns:
Dict with 'min' and 'max' corners, or None if not available.
"""
architecture = layout.get('architecture', {})
boundary_polygon = architecture.get('boundary_polygon', [])
if not boundary_polygon:
return None
import numpy as np
boundary = np.array(boundary_polygon)
if len(boundary) == 0:
return None
return {
'min': boundary.min(axis=0).tolist(),
'max': boundary.max(axis=0).tolist(),
}
def clamp_bbox_to_bounds(bbox: Dict, bounds: Dict) -> Dict:
"""
Clamp a bounding box to stay within scene bounds.
Args:
bbox: Zone bounding box with 'min' and 'max'
bounds: Scene bounds with 'min' and 'max'
Returns:
Clamped bbox dict
"""
clamped_min = [
max(bbox['min'][0], bounds['min'][0]),
max(bbox['min'][1], bounds['min'][1]),
max(bbox['min'][2], bounds['min'][2]),
]
clamped_max = [
min(bbox['max'][0], bounds['max'][0]),
min(bbox['max'][1], bounds['max'][1]),
min(bbox['max'][2], bounds['max'][2]),
]
# Ensure min <= max (in case zone is completely outside)
for i in range(3):
if clamped_min[i] > clamped_max[i]:
# Zone is outside bounds on this axis, use boundary edge
mid = (bounds['min'][i] + bounds['max'][i]) / 2
clamped_min[i] = mid
clamped_max[i] = mid
return {
'min': clamped_min,
'max': clamped_max,
'center': [(clamped_min[i] + clamped_max[i]) / 2 for i in range(3)],
'size': [clamped_max[i] - clamped_min[i] for i in range(3)],
}
def compute_zone_bbox(zone: Dict) -> Optional[Dict[str, List[float]]]:
"""
Compute the bounding box for a functional zone based on its assets.
Important: This applies the same transform logic as compose_generated.py:
- Floor alignment: if pos[2] ≈ 0, adjust to size[2]/2 (lift object to sit on floor)
Returns:
Dict with 'min' and 'max' corners, or None if no valid assets.
"""
assets = zone.get('assets', [])
if not assets:
return None
min_x, max_x = float('inf'), float('-inf')
min_y, max_y = float('inf'), float('-inf')
min_z, max_z = float('inf'), float('-inf')
valid_count = 0
for asset in assets:
pos, size = get_asset_position_size(asset)
if pos is None or size is None:
continue
# Skip zero-size assets
if all(s == 0 for s in size):
continue
valid_count += 1
# Convert to numpy for easier manipulation
pos = list(pos) # Make a copy
size = list(size)
# Apply floor alignment (same as compose_generated.py)
# If pos[2] ≈ 0 (object on floor), lift it by half its height
if abs(pos[2]) < 1e-3:
pos[2] = size[2] / 2.0
# Compute asset bounds (position is center)
half_size = [s / 2 for s in size]
asset_min_x = pos[0] - half_size[0]
asset_max_x = pos[0] + half_size[0]
asset_min_y = pos[1] - half_size[1]
asset_max_y = pos[1] + half_size[1]
asset_min_z = pos[2] - half_size[2]
asset_max_z = pos[2] + half_size[2]
min_x = min(min_x, asset_min_x)
max_x = max(max_x, asset_max_x)
min_y = min(min_y, asset_min_y)
max_y = max(max_y, asset_max_y)
min_z = min(min_z, asset_min_z)
max_z = max(max_z, asset_max_z)
if valid_count == 0:
return None
return {
'min': [min_x, min_y, min_z],
'max': [max_x, max_y, max_z],
'center': [(min_x + max_x) / 2, (min_y + max_y) / 2, (min_z + max_z) / 2],
'size': [max_x - min_x, max_y - min_y, max_z - min_z],
}
def compute_all_zone_bboxes(layout: Dict) -> List[Dict]:
"""
Compute bounding boxes for all functional zones in a layout.
Zone bboxes are clamped to the scene boundary.
Returns:
List of zone info dicts with bbox data.
"""
zones_info = []
# Get scene boundary from architecture
scene_bounds = get_scene_bounds(layout)
if scene_bounds:
print(f" Scene boundary: X=[{scene_bounds['min'][0]:.2f}, {scene_bounds['max'][0]:.2f}], "
f"Y=[{scene_bounds['min'][1]:.2f}, {scene_bounds['max'][1]:.2f}], "
f"Z=[{scene_bounds['min'][2]:.2f}, {scene_bounds['max'][2]:.2f}]")
functional_zones = layout.get('functional_zones', [])
for i, zone in enumerate(functional_zones):
zone_id = zone.get('id', f'zone_{i}')
semantic_label = zone.get('semantic_label', 'Unknown')
bbox = compute_zone_bbox(zone)
if bbox is None:
print(f" Warning: Zone '{zone_id}' ({semantic_label}) has no valid assets with position/size")
continue
# Clamp bbox to scene boundary
if scene_bounds:
bbox = clamp_bbox_to_bounds(bbox, scene_bounds)
zones_info.append({
'zone_id': zone_id,
'semantic_label': semantic_label,
'bbox': bbox,
'color': ZONE_COLORS[i % len(ZONE_COLORS)],
'asset_count': len(zone.get('assets', [])),
})
return zones_info
def create_zone_bbox_glb(zones_info: List[Dict], output_path: str, scene_bounds: Optional[Dict] = None,
face_alpha: float = 0.25, edge_alpha: float = 0.8, edge_radius: float = 0.015,
render_faces: bool = True, render_edges: bool = True):
"""
Create a GLB file containing bounding boxes for all zones with transparent faces and edges.
This creates solid box faces with high transparency (like the reference image shows),
plus optional wireframe edges for better visibility.
Important: This applies the same global rotation as compose_generated.py:
- Global rotation: -π/2 around X axis
- This transforms: original Y -> -Z, original Z -> Y
Args:
zones_info: List of zone info dicts with bbox and color
output_path: Output GLB path
scene_bounds: Optional scene bounds to clamp bbox after padding
face_alpha: Alpha value for box faces (0.0-1.0, default 0.25 for high transparency)
edge_alpha: Alpha value for wireframe edges (0.0-1.0, default 0.8)
edge_radius: Radius of edge cylinders (default 0.015m = 1.5cm)
render_faces: Whether to render transparent box faces (default True)
render_edges: Whether to render wireframe edges (default True)
"""
import numpy as np
import trimesh
from trimesh.visual.material import PBRMaterial
# Global rotation matrix (same as compose_generated.py)
# Rotates -π/2 around X axis: Y -> -Z, Z -> Y
global_rot = trimesh.transformations.rotation_matrix(-np.pi / 2, [1, 0, 0])
scene = trimesh.Scene()
for zone in zones_info:
bbox = zone['bbox']
color = zone['color']
zone_id = zone['zone_id']
# Create box
min_pt = np.array(bbox['min'])
max_pt = np.array(bbox['max'])
# Add small padding (5cm)
padding = 0.05
min_pt -= padding
max_pt += padding
# Clamp to scene bounds if provided (ensure padding doesn't exceed room boundary)
if scene_bounds is not None:
min_pt = np.maximum(min_pt, scene_bounds['min'])
max_pt = np.minimum(max_pt, scene_bounds['max'])
# Box dimensions
box_size = max_pt - min_pt
box_center = (min_pt + max_pt) / 2
# ============ RENDER TRANSPARENT FACES ============
if render_faces:
# Create a box mesh for the faces
box_mesh = trimesh.creation.box(extents=box_size)
box_mesh.apply_translation(box_center)
# Apply global rotation
box_mesh.apply_transform(global_rot)
# Create transparent PBR material for faces
face_rgba = [int(c * 255) for c in color] + [int(face_alpha * 255)]
face_material = PBRMaterial(
baseColorFactor=face_rgba,
metallicFactor=0.0,
roughnessFactor=0.8,
alphaMode='BLEND', # Enable alpha blending for transparency
)
box_mesh.visual = trimesh.visual.TextureVisuals(material=face_material)
scene.add_geometry(box_mesh, node_name=f"{zone_id}_faces")
# ============ RENDER WIREFRAME EDGES ============
if render_edges:
# Define 8 corner vertices
vertices = np.array([
[min_pt[0], min_pt[1], min_pt[2]], # 0: bottom-front-left
[max_pt[0], min_pt[1], min_pt[2]], # 1: bottom-front-right
[max_pt[0], max_pt[1], min_pt[2]], # 2: bottom-back-right
[min_pt[0], max_pt[1], min_pt[2]], # 3: bottom-back-left
[min_pt[0], min_pt[1], max_pt[2]], # 4: top-front-left
[max_pt[0], min_pt[1], max_pt[2]], # 5: top-front-right
[max_pt[0], max_pt[1], max_pt[2]], # 6: top-back-right
[min_pt[0], max_pt[1], max_pt[2]], # 7: top-back-left
])
# Define 12 edges (pairs of vertex indices)
edges = [
# Bottom face
[0, 1], [1, 2], [2, 3], [3, 0],
# Top face
[4, 5], [5, 6], [6, 7], [7, 4],
# Vertical edges
[0, 4], [1, 5], [2, 6], [3, 7],
]
# Create PBR material for edges (slightly more opaque)
edge_rgba = [int(c * 255) for c in color] + [int(edge_alpha * 255)]
edge_material = PBRMaterial(
baseColorFactor=edge_rgba,
metallicFactor=0.0,
roughnessFactor=0.5,
)
# Create cylinders for each edge
for i, edge in enumerate(edges):
start = vertices[edge[0]]
end = vertices[edge[1]]
segment = end - start
length = np.linalg.norm(segment)
if length < 0.001:
continue
# Create cylinder along Z axis
cylinder = trimesh.creation.cylinder(
radius=edge_radius,
height=length,
sections=8
)
# Compute rotation to align cylinder with edge
direction = segment / length
z_axis = np.array([0, 0, 1])
if np.allclose(direction, z_axis):
rotation = np.eye(4)
elif np.allclose(direction, -z_axis):
rotation = trimesh.transformations.rotation_matrix(np.pi, [1, 0, 0])
else:
axis = np.cross(z_axis, direction)
axis = axis / np.linalg.norm(axis)
angle = np.arccos(np.clip(np.dot(z_axis, direction), -1, 1))
rotation = trimesh.transformations.rotation_matrix(angle, axis)
# Move to edge midpoint
midpoint = (start + end) / 2
translation = trimesh.transformations.translation_matrix(midpoint)
cylinder.apply_transform(rotation)
cylinder.apply_transform(translation)
# Apply global rotation
cylinder.apply_transform(global_rot)
# Apply PBR material
cylinder.visual = trimesh.visual.TextureVisuals(material=edge_material)
scene.add_geometry(cylinder, node_name=f"{zone_id}_edge_{i}")
scene.export(output_path)
print(f" Created zone bbox GLB: {output_path}")
def _add_zone_label(scene, zone: Dict, global_rot):
"""
Add a 3D label marker for a zone at the top-center of its bounding box.
Uses a colored sphere/cylinder combination to indicate the zone.
Args:
scene: trimesh.Scene to add geometry to
zone: Zone info dict with bbox, color, semantic_label
global_rot: Global rotation matrix to apply
"""
import numpy as np
import trimesh
from trimesh.visual.material import PBRMaterial
bbox = zone['bbox']
color = zone['color']
zone_id = zone['zone_id']
semantic_label = zone.get('semantic_label', 'Unknown')
# Position: center of bbox in X/Y, top in Z (with some offset above)
label_pos = np.array([
bbox['center'][0],
bbox['center'][1],
bbox['max'][2] + 0.3 # 30cm above the top of the zone
])
# Create a marker: sphere with a vertical pole
rgba = [int(c * 255) for c in color] + [255]
material = PBRMaterial(
baseColorFactor=rgba,
metallicFactor=0.0,
roughnessFactor=0.5,
)
# Sphere marker at the top
sphere_radius = 0.12 # 12cm radius
sphere = trimesh.creation.icosphere(radius=sphere_radius, subdivisions=2)
sphere.apply_translation(label_pos)
sphere.apply_transform(global_rot)
sphere.visual = trimesh.visual.TextureVisuals(material=material)
scene.add_geometry(sphere, node_name=f"{zone_id}_label_sphere")
# Vertical pole from zone top to the sphere
pole_start = np.array([bbox['center'][0], bbox['center'][1], bbox['max'][2]])
pole_end = label_pos - np.array([0, 0, sphere_radius])
pole_height = np.linalg.norm(pole_end - pole_start)
if pole_height > 0.01:
pole = trimesh.creation.cylinder(radius=0.02, height=pole_height, sections=8)
pole_center = (pole_start + pole_end) / 2
pole.apply_translation(pole_center)
pole.apply_transform(global_rot)
pole.visual = trimesh.visual.TextureVisuals(material=material)
scene.add_geometry(pole, node_name=f"{zone_id}_label_pole")
# Add a small horizontal bar indicating direction (optional visual cue)
bar_length = 0.2
bar = trimesh.creation.cylinder(radius=0.015, height=bar_length, sections=6)
# Rotate to horizontal (along X axis)
bar.apply_transform(trimesh.transformations.rotation_matrix(np.pi/2, [0, 1, 0]))
bar.apply_translation(label_pos + np.array([bar_length/2 + sphere_radius, 0, 0]))
bar.apply_transform(global_rot)
bar.visual = trimesh.visual.TextureVisuals(material=material)
scene.add_geometry(bar, node_name=f"{zone_id}_label_bar")
def _deprecated_add_coordinate_axes(scene, zones_info: List[Dict]):
"""
[DEPRECATED] Add coordinate axis markers on the floor plane (Z=0) for verification.
This function is kept for reference but is no longer used.
"""
import numpy as np
import trimesh
from trimesh.visual.material import PBRMaterial
# Global rotation matrix (same as compose_generated.py)
global_rot = trimesh.transformations.rotation_matrix(-np.pi / 2, [1, 0, 0])
# Find extent of all zones
all_min = np.array([float('inf'), float('inf'), float('inf')])
all_max = np.array([float('-inf'), float('-inf'), float('-inf')])
for zone in zones_info:
bbox = zone['bbox']
all_min = np.minimum(all_min, bbox['min'])
all_max = np.maximum(all_max, bbox['max'])
# Extend slightly beyond
margin = 1.0
x_min, x_max = int(all_min[0] - margin), int(all_max[0] + margin)
y_min, y_max = int(all_min[1] - margin), int(all_max[1] + margin)
z_floor = 0.0
# Axis colors
x_color = [255, 0, 0, 255] # Red for X
y_color = [0, 255, 0, 255] # Green for Y
tick_color = [100, 100, 100, 255] # Gray for tick marks
x_material = PBRMaterial(baseColorFactor=x_color, metallicFactor=0.0, roughnessFactor=0.5)
y_material = PBRMaterial(baseColorFactor=y_color, metallicFactor=0.0, roughnessFactor=0.5)
tick_material = PBRMaterial(baseColorFactor=tick_color, metallicFactor=0.0, roughnessFactor=0.5)
axis_radius = 0.03
tick_radius = 0.02
tick_height = 0.3
# X axis (red) - horizontal line along X
x_length = x_max - x_min
x_axis = trimesh.creation.cylinder(radius=axis_radius, height=x_length, sections=8)
# Rotate to align with X axis (default is Z)
x_axis.apply_transform(trimesh.transformations.rotation_matrix(np.pi/2, [0, 1, 0]))
x_axis.apply_translation([(x_min + x_max) / 2, 0, z_floor])
x_axis.apply_transform(global_rot) # Apply global rotation
x_axis.visual = trimesh.visual.TextureVisuals(material=x_material)
scene.add_geometry(x_axis, node_name="axis_x")
# Y axis (green) - horizontal line along Y
y_length = y_max - y_min
y_axis = trimesh.creation.cylinder(radius=axis_radius, height=y_length, sections=8)
# Rotate to align with Y axis
y_axis.apply_transform(trimesh.transformations.rotation_matrix(np.pi/2, [1, 0, 0]))
y_axis.apply_translation([0, (y_min + y_max) / 2, z_floor])
y_axis.apply_transform(global_rot) # Apply global rotation
y_axis.visual = trimesh.visual.TextureVisuals(material=y_material)
scene.add_geometry(y_axis, node_name="axis_y")
# Add tick marks along X axis
for x in range(x_min, x_max + 1):
tick = trimesh.creation.cylinder(radius=tick_radius, height=tick_height, sections=6)
tick.apply_translation([x, 0, z_floor + tick_height/2])
tick.apply_transform(global_rot) # Apply global rotation
tick.visual = trimesh.visual.TextureVisuals(material=tick_material)
scene.add_geometry(tick, node_name=f"tick_x_{x}")
# Add label sphere at integer coordinates (larger at origin)
sphere_radius = 0.08 if x == 0 else 0.05
sphere = trimesh.creation.icosphere(radius=sphere_radius, subdivisions=2)
sphere.apply_translation([x, 0, z_floor + tick_height + 0.1])
sphere.apply_transform(global_rot) # Apply global rotation
sphere.visual = trimesh.visual.TextureVisuals(material=x_material)
scene.add_geometry(sphere, node_name=f"label_x_{x}")
# Add tick marks along Y axis
for y in range(y_min, y_max + 1):
tick = trimesh.creation.cylinder(radius=tick_radius, height=tick_height, sections=6)
tick.apply_translation([0, y, z_floor + tick_height/2])
tick.apply_transform(global_rot) # Apply global rotation
tick.visual = trimesh.visual.TextureVisuals(material=tick_material)
scene.add_geometry(tick, node_name=f"tick_y_{y}")
# Add label sphere
sphere_radius = 0.08 if y == 0 else 0.05
sphere = trimesh.creation.icosphere(radius=sphere_radius, subdivisions=2)
sphere.apply_translation([0, y, z_floor + tick_height + 0.1])
sphere.apply_transform(global_rot) # Apply global rotation
sphere.visual = trimesh.visual.TextureVisuals(material=y_material)
scene.add_geometry(sphere, node_name=f"label_y_{y}")
# Add origin marker (larger sphere)
origin_material = PBRMaterial(baseColorFactor=[255, 255, 255, 255], metallicFactor=0.0, roughnessFactor=0.3)
origin = trimesh.creation.icosphere(radius=0.12, subdivisions=3)
origin.apply_translation([0, 0, z_floor])
origin.visual = trimesh.visual.TextureVisuals(material=origin_material)
scene.add_geometry(origin, node_name="origin")
print(f" Added coordinate axes: X=[{x_min}, {x_max}], Y=[{y_min}, {y_max}]")
def run_command(cmd, env=None, quiet=False):
"""Run a shell command."""
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 project_3d_to_2d_diagonal(point_3d, scene_center, scene_radius, img_width, img_height,
camera_factor=0.8, diagonal_distance=1.2, diagonal_height_offset=0.1, view_mode="diagonal"):
"""
Project a 3D point to 2D image coordinates for diagonal view.
Mimics the camera setup in blender_renderer.py.
Args:
point_3d: (x, y, z) in world coordinates
scene_center: (cx, cy, cz) scene center
scene_radius: scene bounding radius
img_width, img_height: image dimensions
camera_factor: camera distance factor (default: 0.8, from blender_renderer.py)
diagonal_distance: distance multiplier (default: 1.2, from blender_renderer.py)
diagonal_height_offset: vertical camera offset (default: 0.1, from blender_renderer.py)
view_mode: "diagonal" or "diagonal2"
Returns:
(x_2d, y_2d) in image coordinates, or None if behind camera
"""
import math
import numpy as np
# IMPORTANT: Apply the same global rotation as compose_generated.py and create_zone_bbox_glb
# Global rotation: -π/2 around X axis
# Rotation matrix Rx(-π/2) = [[1, 0, 0], [0, 0, 1], [0, -1, 0]]
# So (x, y, z) -> (x, z, -y)
point_world_original = np.array(point_3d)
point_world = np.array([
point_world_original[0], # X stays X
point_world_original[2], # new Y = original Z
-point_world_original[1] # new Z = -original Y
])
# Also transform scene center
scene_center_original = np.array(scene_center)
scene_center_transformed = np.array([
scene_center_original[0],
scene_center_original[2],
-scene_center_original[1]
])
# Camera direction (same as blender_renderer.py)
if view_mode == "diagonal":
cam_dir = np.array([1.0, 1.0, 1.0])
else: # diagonal2
cam_dir = np.array([-1.0, -1.0, 1.0])
cam_dir = cam_dir / np.linalg.norm(cam_dir)
# Camera position (matching blender_renderer.py line 295)
distance = scene_radius * max(1.0, diagonal_distance * camera_factor * 1.5)
eye = scene_center_transformed + cam_dir * distance
# Look target with height offset (matching blender_renderer.py line 298-305)
look_target = scene_center_transformed.copy()
z_offset = scene_radius * diagonal_height_offset
eye[2] -= z_offset
look_target[2] -= z_offset
# Look direction (from camera to look target)
look_dir = look_target - eye
look_dir = look_dir / np.linalg.norm(look_dir)
# Build camera coordinate system
world_up = np.array([0.0, 0.0, 1.0])
right = np.cross(look_dir, world_up)
if np.linalg.norm(right) < 1e-6:
right = np.array([1.0, 0.0, 0.0])
right = right / np.linalg.norm(right)
up = np.cross(right, look_dir)
up = up / np.linalg.norm(up)
# Transform point to camera space (use transformed point)
point_cam = point_world - eye
# Project to camera coordinates
x_cam = np.dot(point_cam, right)
y_cam = np.dot(point_cam, up)
z_cam = np.dot(point_cam, look_dir)
# Check if behind camera
if z_cam <= 0.1:
return None
# Perspective projection (FOV based on lens=35mm)
# For 35mm lens, approximate FOV ~54 degrees
fov = math.radians(54.0)
f = img_height / (2.0 * math.tan(fov / 2.0))
x_2d = (x_cam / z_cam) * f + img_width / 2.0
y_2d = img_height / 2.0 - (y_cam / z_cam) * f # Flip Y for image coordinates
return (x_2d, y_2d)
def add_zone_labels_to_image(image_path: str, zones_info: List[Dict], scene_bounds: Dict,
output_path: str = None, view_mode: str = "diagonal"):
"""
Add zone labels as text overlays on a rendered image, positioned above each zone's bbox.
Args:
image_path: Path to input image
zones_info: List of zone info dicts with zone_id, semantic_label, color, bbox
scene_bounds: Dict with 'center' and 'radius' for camera projection
output_path: Path to save annotated image (default: overwrite input)
view_mode: Camera view mode (diagonal, diagonal2, etc.)
"""
try:
from PIL import Image, ImageDraw, ImageFont
except ImportError:
print(" Warning: PIL not available, skipping label annotation")
return False
if zones_info is None or len(zones_info) == 0:
return False
if output_path is None:
output_path = image_path
# Open image
img = Image.open(image_path)
draw = ImageDraw.Draw(img)
img_width, img_height = img.size
# Load Times New Roman font
try:
font_size = 28
# Try common paths for Times New Roman
font_paths = [
"/usr/share/fonts/truetype/msttcorefonts/Times_New_Roman.ttf",
"/usr/share/fonts/truetype/liberation/LiberationSerif-Bold.ttf", # Free alternative
"/System/Library/Fonts/Times New Roman.ttf", # macOS
"C:/Windows/Fonts/times.ttf", # Windows
]
font = None
for path in font_paths:
try:
font = ImageFont.truetype(path, font_size)
break
except:
continue
if font is None:
# Fallback to DejaVu Serif
font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSerif-Bold.ttf", font_size)
except:
font = ImageFont.load_default()
# Get scene center and radius for projection
scene_center = scene_bounds['center']
scene_radius = scene_bounds['radius']
# For each zone, calculate bbox top center and project to 2D
for zone in zones_info:
semantic_label = zone['semantic_label']
color = zone['color']
bbox = zone['bbox']
# Calculate bbox top center (x_center, y_center, z_max)
x_center = (bbox['min'][0] + bbox['max'][0]) / 2.0
y_center = (bbox['min'][1] + bbox['max'][1]) / 2.0
z_top = bbox['max'][2] # Top of the bbox
# Project to 2D
point_3d = (x_center, y_center, z_top)
projected = project_3d_to_2d_diagonal(
point_3d, scene_center, scene_radius,
img_width, img_height, view_mode=view_mode
)
if projected is None:
continue # Skip if behind camera
x_2d, y_2d = projected
# Convert color to RGB (0-255)
rgb_color = tuple(int(c * 255) for c in color)
# Create label text
label_text = f"{semantic_label}"
# Get text bounding box
bbox_text = draw.textbbox((0, 0), label_text, font=font)
text_width = bbox_text[2] - bbox_text[0]
text_height = bbox_text[3] - bbox_text[1]
# Position label above the bbox top (centered horizontally)
text_x = x_2d - text_width / 2.0
text_y = y_2d - text_height - 10 # 10px above the point
# Clamp to image bounds
text_x = max(5, min(text_x, img_width - text_width - 5))
text_y = max(5, min(text_y, img_height - text_height - 5))
# Draw semi-transparent colored background
bg_padding = 8
bg_coords = [
text_x - bg_padding,
text_y - bg_padding,
text_x + text_width + bg_padding,
text_y + text_height + bg_padding
]
# Draw background with zone color at 60% opacity
draw.rectangle(bg_coords, fill=rgb_color + (153,), outline=(0, 0, 0, 255), width=2)
# Draw text in white for contrast
draw.text((text_x, text_y), label_text, fill=(255, 255, 255), font=font)
# Save annotated image
img.save(output_path)
return True
def run_command(cmd, env=None, quiet=False):
"""Run a shell command."""
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 visualize_zones(
layout_path: str,
output_dir: str,
render_diagonal: bool = True,
render_diagonal2: bool = True,
render_topdown: bool = True,
use_retrieval: bool = True,
show_labels: bool = True,
# Zone bbox visualization parameters
face_alpha: float = 0.25,
edge_alpha: float = 0.8,
edge_radius: float = 0.015,
render_faces: bool = True,
render_edges: bool = True,
):
"""
Main function to visualize functional zones in a layout.
Args:
layout_path: Path to layout.json file
output_dir: Directory to save outputs
render_diagonal: Whether to render diagonal view (front-left)
render_diagonal2: Whether to render opposite diagonal view (back-right)
render_topdown: Whether to render top-down view
use_retrieval: Whether to run asset retrieval (requires embedding manager)
show_labels: Whether to add semantic label text overlays on rendered images
face_alpha: Alpha value for zone bbox faces (0.0-1.0, default 0.25 for high transparency)
edge_alpha: Alpha value for zone bbox edges (0.0-1.0, default 0.8)
edge_radius: Radius of edge cylinders in meters (default 0.015)
render_faces: Whether to render transparent box faces (default True)
render_edges: Whether to render wireframe edges (default True)
"""
print(f"\n=== Visualizing Zones for: {layout_path} ===")
# Load layout
with open(layout_path, 'r') as f:
layout = json.load(f)
# Create output directory
os.makedirs(output_dir, exist_ok=True)
# Compute zone bounding boxes
print("\nComputing zone bounding boxes...")
zones_info = compute_all_zone_bboxes(layout)
# Get scene bounds for clamping bbox visualization
scene_bounds = get_scene_bounds(layout)
for zone in zones_info:
bbox = zone['bbox']
print(f" {zone['zone_id']} ({zone['semantic_label']}): "
f"{zone['asset_count']} assets, "
f"size={bbox['size'][0]:.2f}x{bbox['size'][1]:.2f}x{bbox['size'][2]:.2f}")
# Save zone info
zones_info_path = os.path.join(output_dir, "zones_info.json")
with open(zones_info_path, 'w') as f:
json.dump(zones_info, f, indent=2)
print(f"\nSaved zones info to: {zones_info_path}")
# Create zone bbox GLB (pass scene_bounds to clamp padding)
zone_bbox_glb_path = os.path.join(output_dir, "zone_bboxes.glb")
create_zone_bbox_glb(
zones_info,
zone_bbox_glb_path,
scene_bounds=scene_bounds,
face_alpha=face_alpha,
edge_alpha=edge_alpha,
edge_radius=edge_radius,
render_faces=render_faces,
render_edges=render_edges,
)
# Optionally run retrieval and compose scene
scene_glb_path = os.path.join(output_dir, "scene.glb")
if use_retrieval:
print("\nRunning asset retrieval and scene composition...")
from tools.asset_description.asset_embedding_manager import AssetEmbeddingManager
from tools.asset_description.asset_finder import AssetFinder
from tools.data_gen.layout_retrieval import process_layout
from tools.data_gen.compose_generated import compose_scene
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)
retrieved_layout = process_layout(layout, embedding_manager, asset_finder)
retrieved_path = os.path.join(output_dir, "layout_retrieved.json")
with open(retrieved_path, 'w') as f:
json.dump(retrieved_layout, f, indent=4)
compose_scene(
layout=retrieved_layout,
output_path=scene_glb_path,
add_walls=False,
add_ceiling=False
)
else:
print("\nSkipping retrieval (use_retrieval=False)")
# Check if scene.glb already exists
if not os.path.exists(scene_glb_path):
print(f" Warning: {scene_glb_path} does not exist. Cannot render without scene.")
return zones_info
# Merge scene.glb with zone_bboxes.glb
print("\nMerging scene with zone bboxes...")
merged_glb_path = os.path.join(output_dir, "scene_with_zones.glb")
try:
import trimesh
# Load scene
scene_mesh = trimesh.load(scene_glb_path)
# Load zone bboxes
if os.path.exists(zone_bbox_glb_path):
zone_mesh = trimesh.load(zone_bbox_glb_path)
# Merge
if isinstance(scene_mesh, trimesh.Scene):
if isinstance(zone_mesh, trimesh.Scene):
for name, geom in zone_mesh.geometry.items():
scene_mesh.add_geometry(geom, node_name=f"zone_bbox_{name}")
else:
scene_mesh.add_geometry(zone_mesh, node_name="zone_bboxes")
else:
# Convert to scene
scene = trimesh.Scene()
scene.add_geometry(scene_mesh, node_name="scene")
if isinstance(zone_mesh, trimesh.Scene):
for name, geom in zone_mesh.geometry.items():
scene.add_geometry(geom, node_name=f"zone_bbox_{name}")
else:
scene.add_geometry(zone_mesh, node_name="zone_bboxes")
scene_mesh = scene
scene_mesh.export(merged_glb_path)
print(f" Created merged GLB: {merged_glb_path}")
else:
# Just copy scene
shutil.copy(scene_glb_path, merged_glb_path)
except Exception as e:
print(f" Warning: Could not merge GLBs: {e}")
merged_glb_path = scene_glb_path
# Render
current_env = os.environ.copy()
# Calculate scene center and radius for 3D->2D projection
import numpy as np
scene_min = np.array(scene_bounds['min'])
scene_max = np.array(scene_bounds['max'])
scene_center_arr = (scene_min + scene_max) / 2.0
scene_radius = np.linalg.norm(scene_max - scene_min) / 2.0
scene_bounds_for_projection = {
'center': scene_center_arr.tolist(),
'radius': float(scene_radius)
}
if render_diagonal:
print("\nRendering diagonal view (front-left)...")
render_path = os.path.join(output_dir, "render_diagonal.png")
cmd = (
f"conda run -n blender python InternScenes/InternScenes_Real2Sim/blender_renderer.py "
f"--input '{merged_glb_path}' "
f"--output '{render_path}' "
f"--width 1600 --height 900 "
f"--engine BLENDER_EEVEE --samples 64 "
f"--view-mode diagonal --auto-crop "
f"--floor-material ceramic_tile"
)
run_command(cmd, env=current_env, quiet=True)
# Add zone labels as text overlays
if show_labels:
add_zone_labels_to_image(render_path, zones_info, scene_bounds_for_projection, view_mode="diagonal")
if render_diagonal2:
print("\nRendering diagonal view (back-right)...")
render_path = os.path.join(output_dir, "render_diagonal2.png")
cmd = (
f"conda run -n blender python InternScenes/InternScenes_Real2Sim/blender_renderer.py "
f"--input '{merged_glb_path}' "
f"--output '{render_path}' "
f"--width 1600 --height 900 "
f"--engine BLENDER_EEVEE --samples 64 "
f"--view-mode diagonal2 --auto-crop "
f"--floor-material concrete"
)
run_command(cmd, env=current_env, quiet=True)
# Add zone labels as text overlays
if show_labels:
add_zone_labels_to_image(render_path, zones_info, scene_bounds_for_projection, view_mode="diagonal2")
if render_topdown:
print("\nRendering top-down view...")
render_path = os.path.join(output_dir, "render_topdown.png")
cmd = (
f"conda run -n blender python InternScenes/InternScenes_Real2Sim/blender_renderer.py "
f"--input '{merged_glb_path}' "
f"--output '{render_path}' "
f"--width 1600 --height 900 "
f"--engine BLENDER_EEVEE --samples 64 "
f"--view-mode topdown --auto-crop "
f"--floor-material ceramic_tile"
)
run_command(cmd, env=current_env, quiet=True)
# Note: topdown uses orthographic projection, 2D label positioning needs different logic
# For now, diagonal views are the main focus
print(f"\n=== Done! Outputs saved to: {output_dir} ===")
# Print legend
print("\n=== Zone Color Legend ===")
for zone in zones_info:
color = zone['color']
color_str = f"RGB({int(color[0]*255)}, {int(color[1]*255)}, {int(color[2]*255)})"
print(f" {zone['zone_id']}: {zone['semantic_label']} - {color_str}")
return zones_info
def main():
parser = argparse.ArgumentParser(description="Visualize functional zones in a 3D scene layout")
parser.add_argument("--input", default="/home/v-meiszhang/backup/datas/unified-layout-aligned/scannet/scene0024_00/layout.json", help="Path to layout.json file")
parser.add_argument("--output", default="zone_vis_output", help="Output directory")
parser.add_argument("--no-retrieval", action="store_true", help="Skip asset retrieval (use existing scene.glb)")
parser.add_argument("--no-diagonal", action="store_true", help="Skip diagonal view rendering (front-left)")
parser.add_argument("--no-diagonal2", action="store_true", help="Skip diagonal2 view rendering (back-right)")
parser.add_argument("--no-topdown", action="store_true", help="Skip top-down view rendering")
parser.add_argument("--no-labels", dest="show_labels", action="store_false", default=True,
help="Don't add semantic label text overlays on rendered images")
# Zone bbox visualization options
parser.add_argument("--face-alpha", type=float, default=0.25,
help="Alpha value for zone bbox faces (0.0-1.0, default 0.25)")
parser.add_argument("--edge-alpha", type=float, default=0.8,
help="Alpha value for zone bbox edges (0.0-1.0, default 0.8)")
parser.add_argument("--edge-radius", type=float, default=0.015,
help="Radius of edge cylinders in meters (default 0.015)")
parser.add_argument("--no-faces", dest="render_faces", action="store_false", default=True,
help="Don't render transparent box faces (wireframe only)")
parser.add_argument("--no-edges", dest="render_edges", action="store_false", default=True,
help="Don't render wireframe edges (faces only)")
args = parser.parse_args()
visualize_zones(
layout_path=args.input,
output_dir=args.output,
render_diagonal=not args.no_diagonal,
render_diagonal2=not args.no_diagonal2,
render_topdown=not args.no_topdown,
use_retrieval=not args.no_retrieval,
show_labels=args.show_labels,
face_alpha=args.face_alpha,
edge_alpha=args.edge_alpha,
edge_radius=args.edge_radius,
render_faces=args.render_faces,
render_edges=args.render_edges,
)
if __name__ == "__main__":
main()