ZoneMaestro_code / eval /LayoutVLM /render_final_scene.py
kkkkiiii's picture
Add files using upload-large-folder tool
231562a verified
#!/usr/bin/env python3
"""
Render the final 3D scene from a generated layout.json file.
Usage: python render_final_scene.py --layout_file ./results/test_run3/layout.json --scene_json ./benchmark_tasks/bookstore/bookstore_2.json
"""
import os
import json
import argparse
from utils.blender_render import render_existing_scene
from utils.blender_utils import reset_blender
import collections
def parse_args():
parser = argparse.ArgumentParser(description="Render final 3D scene from layout.json")
parser.add_argument("--layout_file", required=True, help="Path to layout.json file")
parser.add_argument("--scene_json", required=True, help="Path to original scene JSON file")
parser.add_argument("--asset_dir", default="/home/v-meiszhang/backup/objaverse_processed", help="Directory with 3D assets")
parser.add_argument("--output_dir", default=None, help="Output directory (defaults to same dir as layout_file)")
return parser.parse_args()
def prepare_scene_config(scene_json_path, asset_dir):
"""Load and prepare scene configuration"""
with open(scene_json_path, 'r') as f:
scene_config = json.load(f)
# Prepare asset metadata
all_data = collections.defaultdict(list)
for original_uid in scene_config["assets"].keys():
uid = '-'.join(original_uid.split('-')[:-1])
data_path = os.path.join(asset_dir, uid, "data.json")
if not os.path.exists(data_path):
print(f"Warning: Asset data not found for {uid}")
continue
with open(data_path, 'r') as f:
data = json.load(f)
data['path'] = os.path.join(asset_dir, uid, f"{uid}.glb")
all_data[uid].append(data)
# Build asset info
category_count = collections.defaultdict(int)
for uid, duplicated_assets in all_data.items():
category_var_name = duplicated_assets[0]['annotations']['category']
category_var_name = category_var_name.replace('-', "_").replace(" ", "_").replace("'", "_").replace("/", "_").replace(",", "_").lower()
category_count[category_var_name] += 1
scene_config["assets"] = {}
category_idx = collections.defaultdict(int)
for uid, duplicated_assets in all_data.items():
category_var_name = duplicated_assets[0]['annotations']['category']
category_var_name = category_var_name.replace('-', "_").replace(" ", "_").replace("'", "_").replace("/", "_").replace(",", "_").lower()
category_idx[category_var_name] += 1
for instance_idx, data in enumerate(duplicated_assets):
category_var_name = f"{category_var_name}_{chr(ord('A') + category_idx[category_var_name]-1)}" if category_count[category_var_name] > 1 else category_var_name
var_name = f"{category_var_name}_{instance_idx}" if len(duplicated_assets) > 1 else category_var_name
scene_config["assets"][f"{category_var_name}-{instance_idx}"] = {
"uid": uid,
"count": len(duplicated_assets),
"instance_var_name": var_name,
"asset_var_name": category_var_name,
"instance_idx": instance_idx,
"annotations": data["annotations"],
"category": data["annotations"]["category"],
'description': data['annotations']['description'],
'path': data['path'],
'onCeiling': data['annotations']['onCeiling'],
'onFloor': data['annotations']['onFloor'],
'onWall': data['annotations']['onWall'],
'onObject': data['annotations']['onObject'],
'frontView': data['annotations']['frontView'],
'assetMetadata': {
"boundingBox": {
"x": float(data['assetMetadata']['boundingBox']['y']),
"y": float(data['assetMetadata']['boundingBox']['x']),
"z": float(data['assetMetadata']['boundingBox']['z'])
},
}
}
return scene_config
def main():
args = parse_args()
# Determine output directory
if args.output_dir is None:
args.output_dir = os.path.dirname(args.layout_file)
os.makedirs(args.output_dir, exist_ok=True)
print(f"Loading layout from: {args.layout_file}")
print(f"Loading scene config from: {args.scene_json}")
print(f"Output directory: {args.output_dir}")
# Load layout
with open(args.layout_file, 'r') as f:
layout = json.load(f)
# Prepare scene configuration with asset metadata
scene_config = prepare_scene_config(args.scene_json, args.asset_dir)
print(f"\nRendering scene with {len(layout)} placed objects...")
# Render the scene
try:
# 1. 渲染带标注的版本 (用于调试和分析)
print("\n🎨 渲染带标注的版本...")
annotated_images, visual_marks = render_existing_scene(
layout, # placed_assets
scene_config, # task
save_dir=args.output_dir,
high_res=True,
render_top_down=True,
apply_3dfront_texture=False,
combine_obj_components=False,
fov_multiplier=1.3,
add_coordinate_mark=True,
annotate_object=True,
annotate_wall=True,
add_object_bbox=False,
topdown_save_file=os.path.join(args.output_dir, 'final_scene_top_down_annotated.png'),
sideview_save_file=os.path.join(args.output_dir, 'final_scene_side_view_annotated.png'),
side_view_indices=[0, 1, 2, 3] # Multiple angles
)
reset_blender()
# 2. 渲染干净的版本 (无标注,用于最终展示)
print("\n🎨 渲染干净版本...")
clean_images, _ = render_existing_scene(
layout, # placed_assets
scene_config, # task
save_dir=args.output_dir,
high_res=True,
render_top_down=True,
apply_3dfront_texture=False,
combine_obj_components=False,
fov_multiplier=1.3,
add_coordinate_mark=False, # 不添加坐标标记
annotate_object=False, # 不标注物体
annotate_wall=False, # 不标注墙壁
add_object_bbox=False,
topdown_save_file=os.path.join(args.output_dir, 'final_scene_top_down_clean.png'),
sideview_save_file=os.path.join(args.output_dir, 'final_scene_side_view_clean.png'),
side_view_indices=[0, 1, 2, 3] # Multiple angles
)
reset_blender()
all_images = annotated_images + clean_images
print(f"\n✅ Successfully rendered final scene!")
print(f"\n📊 带标注的版本 (用于调试):")
for img_path in annotated_images:
print(f" - {img_path}")
print(f"\n🎬 干净版本 (用于展示):")
for img_path in clean_images:
print(f" - {img_path}")
except Exception as e:
print(f"\n❌ Error rendering scene: {e}")
import traceback
traceback.print_exc()
return 1
return 0
if __name__ == "__main__":
exit(main())