| |
| """ |
| 批量渲染 IDesign 生成的场景 - 使用 bpy 直接渲染 |
| 需要在 blender conda 环境下运行: conda activate blender |
| |
| 高质量渲染设置:与 InternScenes 项目的 blender 渲染器对齐 |
| """ |
|
|
| import bpy |
| import json |
| import math |
| import os |
| import sys |
| from pathlib import Path |
| from datetime import datetime |
| from mathutils import Vector |
|
|
| try: |
| from PIL import Image |
| HAS_PIL = True |
| except ImportError: |
| HAS_PIL = False |
|
|
|
|
| |
| |
| |
| RENDER_CONFIG = { |
| |
| "width": 1600, |
| "height": 900, |
| |
| "engine": "CYCLES", |
| "samples": 256, |
| "exposure": 0.0, |
| |
| "camera_lens": 35.0, |
| "camera_clip_start": 0.01, |
| "camera_clip_end": 1000.0, |
| |
| "view_mode": "diagonal", |
| "diagonal_distance": 2.2, |
| "diagonal_height_offset": 0.1, |
| "topdown_height": 1.5, |
| "topdown_scale": 1.0, |
| |
| "sun_intensity": 3.5, |
| "sun_color": (1.0, 0.98, 0.94), |
| "ambient_intensity": 1.0, |
| "use_fill_lights": True, |
| "fill_intensity": 0.5, |
| |
| "background": (1.0, 1.0, 1.0, 1.0), |
| "use_transparent_background": True, |
| |
| "auto_crop": True, |
| "crop_padding": 10, |
| } |
|
|
| |
| def clear_default_cube(): |
| obj = bpy.data.objects.get('Cube') |
| if obj: |
| bpy.data.objects.remove(obj, do_unlink=True) |
|
|
| def clear_scene(): |
| """完全清空场景""" |
| bpy.ops.object.select_all(action='SELECT') |
| bpy.ops.object.delete() |
| |
| |
| for mesh in bpy.data.meshes: |
| bpy.data.meshes.remove(mesh) |
| for material in bpy.data.materials: |
| bpy.data.materials.remove(material) |
|
|
| def import_glb(file_path, object_name): |
| """导入 GLB 文件""" |
| try: |
| bpy.ops.import_scene.gltf(filepath=file_path) |
| imported_object = bpy.context.view_layer.objects.active |
| if imported_object is not None: |
| imported_object.name = object_name |
| return imported_object |
| except Exception as e: |
| print(f"导入失败 {object_name}: {e}") |
| return None |
|
|
| def find_glb_files(directories): |
| """在多个目录中查找 GLB 文件""" |
| glb_files = {} |
| for directory in directories: |
| if not os.path.exists(directory): |
| continue |
| for root, dirs, files in os.walk(directory): |
| for file in files: |
| if file.endswith(".glb"): |
| key = file.replace(".glb", "") |
| if key not in glb_files: |
| glb_files[key] = os.path.join(root, file) |
| return glb_files |
|
|
| def get_highest_parent_objects(): |
| """获取最高层父对象""" |
| return [obj for obj in bpy.data.objects if obj.parent is None] |
|
|
| def select_meshes_under_empty(empty_object_name): |
| """递归选择 Empty 下的所有 Mesh""" |
| empty_object = bpy.data.objects.get(empty_object_name) |
| if empty_object is not None and empty_object.type == 'EMPTY': |
| for child in empty_object.children: |
| if child.type == 'MESH': |
| child.select_set(True) |
| bpy.context.view_layer.objects.active = child |
| else: |
| select_meshes_under_empty(child.name) |
|
|
| def delete_empty_objects(): |
| """删除所有 Empty 对象""" |
| empties = [obj for obj in bpy.context.scene.objects if obj.type == 'EMPTY'] |
| for obj in empties: |
| bpy.data.objects.remove(obj) |
|
|
| def rescale_object(obj, scale): |
| """缩放对象到指定尺寸""" |
| if obj.type == 'MESH': |
| bbox_dimensions = obj.dimensions |
| if bbox_dimensions.x > 0 and bbox_dimensions.y > 0 and bbox_dimensions.z > 0: |
| scale_factors = ( |
| scale.get("length", 1) / bbox_dimensions.x, |
| scale.get("width", 1) / bbox_dimensions.y, |
| scale.get("height", 1) / bbox_dimensions.z |
| ) |
| obj.scale = scale_factors |
|
|
|
|
| def ensure_principled_materials(objects): |
| """确保所有网格对象有正确的 Principled BSDF 材质(与 InternScenes 渲染器对齐) |
| |
| 增强现有材质的 PBR 参数以获得更好的渲染效果。 |
| """ |
| for obj in objects: |
| if obj.type != "MESH" or not obj.data.materials: |
| continue |
| |
| for mat_idx, material in enumerate(obj.data.materials): |
| if material is None: |
| continue |
| |
| |
| if material.name == "FloorMaterial": |
| continue |
| |
| |
| material.use_nodes = True |
| nodes = material.node_tree.nodes |
| |
| |
| principled = None |
| for node in nodes: |
| if node.type == "BSDF_PRINCIPLED": |
| principled = node |
| break |
| |
| if principled is None: |
| |
| nodes.clear() |
| principled = nodes.new(type="ShaderNodeBsdfPrincipled") |
| output = nodes.new(type="ShaderNodeOutputMaterial") |
| material.node_tree.links.new(principled.outputs["BSDF"], output.inputs["Surface"]) |
| |
| |
| if "Base Color" in principled.inputs: |
| bc = principled.inputs["Base Color"].default_value |
| if bc[0] == 0 and bc[1] == 0 and bc[2] == 0: |
| principled.inputs["Base Color"].default_value = (0.8, 0.8, 0.8, 1.0) |
| |
| if "Roughness" in principled.inputs: |
| current_rough = principled.inputs["Roughness"].default_value |
| if current_rough < 0.1 or current_rough > 0.99: |
| principled.inputs["Roughness"].default_value = 0.5 |
| |
| if "Metallic" in principled.inputs: |
| principled.inputs["Metallic"].default_value = 0.0 |
|
|
|
|
| def create_room(width, depth, height): |
| """创建地板(纯白色材质)""" |
| |
| bpy.ops.mesh.primitive_plane_add(size=1, location=(width/2, depth/2, 0)) |
| floor = bpy.context.active_object |
| floor.scale = (width, depth, 1) |
| floor.name = "Floor" |
| |
| |
| mat = bpy.data.materials.new(name="FloorMaterial") |
| mat.use_nodes = True |
| nodes = mat.node_tree.nodes |
| links = mat.node_tree.links |
| nodes.clear() |
| |
| |
| bsdf = nodes.new(type="ShaderNodeBsdfPrincipled") |
| bsdf.inputs["Base Color"].default_value = (1.0, 1.0, 1.0, 1.0) |
| bsdf.inputs["Roughness"].default_value = 0.35 |
| bsdf.inputs["Metallic"].default_value = 0.0 |
| |
| |
| output = nodes.new(type="ShaderNodeOutputMaterial") |
| links.new(bsdf.outputs["BSDF"], output.inputs["Surface"]) |
| |
| |
| mat.blend_method = "OPAQUE" |
| if hasattr(mat, 'shadow_method'): |
| mat.shadow_method = "OPAQUE" |
| mat.use_backface_culling = False |
| |
| floor.data.materials.append(mat) |
| return floor |
|
|
| def setup_camera(width, depth, height, view_mode="diagonal"): |
| """设置相机(与 InternScenes 渲染器对齐) |
| |
| Args: |
| width, depth, height: 房间尺寸 |
| view_mode: 相机视角模式 |
| - diagonal: 前右角对角线视角 |
| - diagonal2: 后左角对角线视角 |
| - diagonal3: 后右角对角线视角 |
| - diagonal4: 前左角对角线视角 |
| - topdown: 俯视图(正交) |
| - side_front/side_back/side_left/side_right: 侧视图 |
| """ |
| |
| center = Vector((width/2, depth/2, height/2)) |
| extent = Vector((width, depth, height)) |
| radius = extent.length / 2 |
| |
| bpy.ops.object.camera_add() |
| camera = bpy.context.active_object |
| camera.name = "Camera" |
| |
| config = RENDER_CONFIG |
| diagonal_distance = config.get("diagonal_distance", 1.2) |
| diagonal_height_offset = config.get("diagonal_height_offset", 0.15) |
| topdown_height = config.get("topdown_height", 1.5) |
| topdown_scale = config.get("topdown_scale", 1.0) |
| |
| if view_mode == "topdown": |
| |
| camera.data.type = "ORTHO" |
| camera.data.ortho_scale = radius * topdown_scale |
| eye = center + Vector((0.0, 0.0, radius * topdown_height)) |
| camera.location = eye |
| camera.data.lens = 50.0 |
| |
| _look_at(camera, center) |
| elif view_mode.startswith("side_"): |
| |
| camera.data.type = "PERSP" |
| camera.data.lens = config.get("camera_lens", 35.0) |
| |
| elev_rad = math.radians(30.0) |
| horizontal_dist = math.cos(elev_rad) |
| vertical_dist = math.sin(elev_rad) |
| |
| if view_mode == "side_front": |
| horiz_dir = Vector((0.0, 1.0, 0.0)) |
| elif view_mode == "side_back": |
| horiz_dir = Vector((0.0, -1.0, 0.0)) |
| elif view_mode == "side_left": |
| horiz_dir = Vector((-1.0, 0.0, 0.0)) |
| elif view_mode == "side_right": |
| horiz_dir = Vector((1.0, 0.0, 0.0)) |
| else: |
| horiz_dir = Vector((0.0, 1.0, 0.0)) |
| |
| distance = radius * max(1.0, diagonal_distance * 1.5) |
| direction = Vector(( |
| horiz_dir.x * horizontal_dist, |
| horiz_dir.y * horizontal_dist, |
| vertical_dist |
| )) |
| direction.normalize() |
| |
| eye = center + direction * distance |
| camera.location = eye |
| _look_at(camera, center) |
| else: |
| |
| camera.data.type = "PERSP" |
| camera.data.lens = config.get("camera_lens", 35.0) |
| |
| if view_mode == "diagonal": |
| diag_direction = Vector((1.0, 1.0, 1.0)) |
| elif view_mode == "diagonal2": |
| diag_direction = Vector((-1.0, -1.0, 1.0)) |
| elif view_mode == "diagonal3": |
| diag_direction = Vector((1.0, -1.0, 1.0)) |
| elif view_mode == "diagonal4": |
| diag_direction = Vector((-1.0, 1.0, 1.0)) |
| else: |
| diag_direction = Vector((1.0, 1.0, 1.0)) |
| diag_direction.normalize() |
| |
| distance = radius * max(1.0, diagonal_distance * 1.5) |
| eye = center + diag_direction * distance |
| |
| look_target = center.copy() |
| z_offset = radius * diagonal_height_offset |
| eye.z -= z_offset |
| look_target.z -= z_offset |
| |
| camera.location = eye |
| _look_at(camera, look_target) |
| |
| |
| camera.data.clip_start = config.get("camera_clip_start", 0.01) |
| camera.data.clip_end = config.get("camera_clip_end", radius * 100.0) |
| |
| bpy.context.scene.camera = camera |
| return camera |
|
|
|
|
| def _look_at(camera, target): |
| """让相机朝向目标点""" |
| direction = target - camera.location |
| if direction.length < 1e-6: |
| direction = Vector((0.0, 0.0, -1.0)) |
| else: |
| direction.normalize() |
| quat = direction.to_track_quat("-Z", "Y") |
| camera.rotation_euler = quat.to_euler() |
|
|
| def setup_lighting(width, depth, height): |
| """设置灯光(与 InternScenes 渲染器对齐)""" |
| center = Vector((width/2, depth/2, height/2)) |
| extent = Vector((width, depth, height)) |
| radius = extent.length / 2 |
| |
| config = RENDER_CONFIG |
| sun_intensity = config.get("sun_intensity", 3.5) |
| sun_color = config.get("sun_color", (1.0, 0.98, 0.94)) |
| use_fill_lights = config.get("use_fill_lights", True) |
| fill_intensity = config.get("fill_intensity", 0.5) |
| |
| |
| sun_light_data = bpy.data.lights.new("Sun", type="SUN") |
| sun = bpy.data.objects.new("Sun", sun_light_data) |
| bpy.context.collection.objects.link(sun) |
| |
| |
| camera = bpy.context.scene.camera |
| if camera: |
| view_dir = center - camera.location |
| if view_dir.length < 1e-6: |
| view_dir = Vector((0.0, 0.0, -1.0)) |
| else: |
| view_dir.normalize() |
| sun_dir = view_dir * 0.6 + Vector((0.0, 0.0, -0.8)) |
| if sun_dir.length < 1e-6: |
| sun_dir = Vector((0.0, 0.0, -1.0)) |
| else: |
| sun_dir.normalize() |
| else: |
| sun_dir = Vector((-0.5, -0.5, -0.8)) |
| sun_dir.normalize() |
| |
| sun.location = center + sun_dir * radius * 2.0 |
| quat = sun_dir.to_track_quat("-Z", "Y") |
| sun.rotation_euler = quat.to_euler() |
| |
| sun.data.energy = max(0.01, sun_intensity) |
| sun.data.color = sun_color |
| |
| |
| if hasattr(sun.data, "angle"): |
| sun.data.angle = math.radians(1.0) |
| |
| if not use_fill_lights: |
| return |
| |
| |
| fill_light_data = bpy.data.lights.new("FillLight", type="AREA") |
| fill_light = bpy.data.objects.new("FillLight", fill_light_data) |
| bpy.context.collection.objects.link(fill_light) |
| |
| fill_light.location = center + Vector((0.0, -radius * 0.5, radius * 1.5)) |
| fill_light.rotation_euler = (math.radians(45), 0, 0) |
| fill_light_data.energy = fill_intensity * 100 |
| fill_light_data.color = (1.0, 0.98, 0.95) |
| fill_light_data.size = radius * 2 |
| |
| |
| rim_light_data = bpy.data.lights.new("RimLight", type="AREA") |
| rim_light = bpy.data.objects.new("RimLight", rim_light_data) |
| bpy.context.collection.objects.link(rim_light) |
| |
| rim_light.location = center + Vector((radius * 0.5, radius, radius)) |
| rim_light.rotation_euler = (math.radians(-45), math.radians(30), 0) |
| rim_light_data.energy = fill_intensity * 50 |
| rim_light_data.color = (0.95, 0.97, 1.0) |
| rim_light_data.size = radius |
|
|
|
|
| def setup_world(): |
| """设置世界/环境(与 InternScenes 渲染器对齐)""" |
| scene = bpy.context.scene |
| config = RENDER_CONFIG |
| background = config.get("background", (1.0, 1.0, 1.0, 1.0)) |
| ambient_intensity = config.get("ambient_intensity", 1.0) |
| use_transparent = config.get("use_transparent_background", True) |
| |
| |
| if scene.world is None: |
| scene.world = bpy.data.worlds.new("World") |
| world = scene.world |
| world.use_nodes = True |
| nodes = world.node_tree.nodes |
| links = world.node_tree.links |
| |
| |
| nodes.clear() |
| |
| |
| output_node = nodes.new(type="ShaderNodeOutputWorld") |
| output_node.location = (400, 0) |
| |
| |
| background_node = nodes.new(type="ShaderNodeBackground") |
| background_node.location = (200, 0) |
| background_node.inputs[0].default_value = ( |
| background[0], |
| background[1], |
| background[2], |
| background[3] if len(background) > 3 else 1.0, |
| ) |
| background_node.inputs[1].default_value = max(0.0, ambient_intensity) |
| links.new(background_node.outputs["Background"], output_node.inputs["Surface"]) |
| |
| |
| scene.render.film_transparent = use_transparent |
| scene.render.image_settings.color_mode = "RGBA" |
|
|
| def render_single_scene(scene_dir, output_name="render.png"): |
| """渲染单个场景""" |
| scene_dir = Path(scene_dir) |
| |
| |
| scene_json = None |
| for json_name in ["scene_graph.json", "scene.json"]: |
| candidate = scene_dir / json_name |
| if candidate.exists(): |
| scene_json = candidate |
| break |
| |
| if scene_json is None: |
| print(f" ⚠️ scene_graph.json/scene.json 不存在,跳过") |
| return False |
| |
| |
| with open(scene_json, 'r') as f: |
| data = json.load(f) |
| |
| |
| objects_in_room = {} |
| room_dims = [4, 4, 2.8] |
| |
| for item in data: |
| obj_id = item.get("new_object_id", "") |
| if obj_id == "middle of the room": |
| size = item.get("size_in_meters", {}) |
| room_dims = [size.get("length", 4), size.get("width", 4), 2.8] |
| elif obj_id == "ceiling": |
| pos = item.get("position", {}) |
| room_dims[2] = pos.get("z", 2.8) |
| elif obj_id not in ["south_wall", "north_wall", "east_wall", "west_wall"]: |
| if item.get("position"): |
| objects_in_room[obj_id] = item |
| |
| if not objects_in_room: |
| print(f" ⚠️ 无有效物体,跳过") |
| return False |
| |
| |
| glb_dirs = [ |
| scene_dir / "Assets", |
| scene_dir / "assets", |
| scene_dir / "glb", |
| scene_dir / "objects" |
| ] |
| glb_file_paths = find_glb_files([str(d) for d in glb_dirs]) |
| |
| if not glb_file_paths: |
| print(f" ⚠️ 无 GLB 文件,跳过") |
| return False |
| |
| |
| clear_scene() |
| |
| |
| for item_id in objects_in_room: |
| if item_id in glb_file_paths: |
| import_glb(glb_file_paths[item_id], item_id) |
| |
| |
| parents = get_highest_parent_objects() |
| empty_parents = [p for p in parents if p.type == "EMPTY"] |
| |
| for empty_parent in empty_parents: |
| bpy.ops.object.select_all(action='DESELECT') |
| select_meshes_under_empty(empty_parent.name) |
| |
| if bpy.context.selected_objects: |
| bpy.ops.object.join() |
| bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY', center='BOUNDS') |
| |
| joined_object = bpy.context.view_layer.objects.active |
| if joined_object: |
| joined_object.name = empty_parent.name + "-joined" |
| |
| |
| MSH_OBJS = [m for m in bpy.context.scene.objects if m.type == 'MESH'] |
| for obj in MSH_OBJS: |
| bpy.context.view_layer.objects.active = obj |
| bpy.ops.object.parent_clear(type='CLEAR_KEEP_TRANSFORM') |
| obj.location = (0.0, 0.0, 0.0) |
| obj.select_set(True) |
| bpy.ops.object.transform_apply(location=True, rotation=True, scale=True) |
| bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY', center='BOUNDS') |
| |
| |
| loaded_count = 0 |
| MSH_OBJS = [m for m in bpy.context.scene.objects if m.type == 'MESH'] |
| for obj in MSH_OBJS: |
| |
| key_variants = [ |
| obj.name, |
| obj.name.replace("-joined", ""), |
| obj.name.replace(".001", ""), |
| obj.name.replace(".002", ""), |
| ] |
| key = next((k for k in key_variants if k in objects_in_room), None) |
| if key is None: |
| continue |
| |
| item = objects_in_room[key] |
| pos = item.get("position", {}) |
| rot = item.get("rotation", {}) |
| size = item.get("size_in_meters", {}) |
| |
| |
| obj.location = (pos.get("x", 0), pos.get("y", 0), pos.get("z", 0)) |
| |
| |
| z_angle = rot.get("z_angle", 0) |
| bpy.ops.object.select_all(action='DESELECT') |
| obj.select_set(True) |
| bpy.ops.transform.rotate(value=(z_angle / 180.0) * math.pi + math.pi, orient_axis='Z') |
| |
| |
| if size: |
| rescale_object(obj, size) |
| |
| loaded_count += 1 |
| |
| |
| delete_empty_objects() |
| |
| |
| mesh_objects = [m for m in bpy.context.scene.objects if m.type == 'MESH'] |
| ensure_principled_materials(mesh_objects) |
| |
| |
| create_room(room_dims[0], room_dims[1], room_dims[2]) |
| |
| |
| setup_world() |
| |
| |
| view_mode = RENDER_CONFIG.get("view_mode", "diagonal") |
| setup_camera(room_dims[0], room_dims[1], room_dims[2], view_mode) |
| setup_lighting(room_dims[0], room_dims[1], room_dims[2]) |
| |
| |
| configure_render_settings() |
| |
| |
| output_path = scene_dir / output_name |
| scene = bpy.context.scene |
| scene.render.filepath = str(output_path) |
| bpy.ops.render.render(write_still=True) |
| |
| |
| if RENDER_CONFIG.get("auto_crop", True) and HAS_PIL: |
| auto_crop_image(str(output_path), RENDER_CONFIG.get("crop_padding", 10)) |
| |
| print(f" ✅ 渲染完成 ({loaded_count} 个物体): {output_path}") |
| return True |
|
|
|
|
| def configure_render_settings(): |
| """配置渲染设置(与 InternScenes 渲染器对齐)""" |
| scene = bpy.context.scene |
| render = scene.render |
| config = RENDER_CONFIG |
| |
| engine = config.get("engine", "CYCLES") |
| width = config.get("width", 1600) |
| height = config.get("height", 900) |
| samples = config.get("samples", 256) |
| exposure = config.get("exposure", 0.0) |
| |
| |
| available_engines = {item.identifier for item in render.bl_rna.properties["engine"].enum_items} |
| target_engine = engine |
| if target_engine not in available_engines: |
| if target_engine == "BLENDER_EEVEE" and "BLENDER_EEVEE_NEXT" in available_engines: |
| target_engine = "BLENDER_EEVEE_NEXT" |
| elif "CYCLES" in available_engines: |
| target_engine = "CYCLES" |
| |
| render.engine = target_engine |
| render.resolution_x = width |
| render.resolution_y = height |
| render.image_settings.file_format = "PNG" |
| render.image_settings.color_mode = "RGBA" |
| render.film_transparent = config.get("use_transparent_background", True) |
| render.use_persistent_data = False |
| |
| scene.view_settings.exposure = exposure |
| |
| if target_engine == "CYCLES": |
| scene.cycles.samples = max(1, samples) |
| scene.cycles.preview_samples = min(scene.cycles.samples, 64) |
| scene.cycles.use_denoising = True |
| scene.cycles.use_adaptive_sampling = True |
| scene.cycles.max_bounces = 12 |
| scene.cycles.diffuse_bounces = 4 |
| scene.cycles.glossy_bounces = 4 |
| scene.cycles.transmission_bounces = 8 |
| scene.cycles.volume_bounces = 2 |
| |
| |
| try: |
| prefs = bpy.context.preferences.addons['cycles'].preferences |
| prefs.compute_device_type = 'CUDA' |
| prefs.get_devices() |
| scene.cycles.device = 'GPU' |
| for device in prefs.devices: |
| device.use = True |
| except: |
| pass |
| elif target_engine in {"BLENDER_EEVEE", "BLENDER_EEVEE_NEXT"}: |
| eevee = scene.eevee |
| if hasattr(eevee, "taa_render_samples"): |
| eevee.taa_render_samples = max(1, samples) |
| elif hasattr(eevee, "samples"): |
| eevee.samples = max(1, samples) |
| |
| if hasattr(eevee, "use_gtao"): |
| eevee.use_gtao = True |
| if hasattr(eevee, "gtao_distance"): |
| eevee.gtao_distance = 0.5 |
| if hasattr(eevee, "gtao_quality"): |
| eevee.gtao_quality = 0.5 |
| |
| if hasattr(eevee, "use_bloom"): |
| eevee.use_bloom = True |
| if hasattr(eevee, "bloom_threshold"): |
| eevee.bloom_threshold = 0.8 |
| if hasattr(eevee, "bloom_intensity"): |
| eevee.bloom_intensity = 0.1 |
| |
| if hasattr(eevee, "use_ssr"): |
| eevee.use_ssr = True |
| if hasattr(eevee, "use_ssr_refraction"): |
| eevee.use_ssr_refraction = True |
| |
| if hasattr(eevee, "use_soft_shadows"): |
| eevee.use_soft_shadows = True |
| if hasattr(eevee, "shadow_cube_size"): |
| eevee.shadow_cube_size = '1024' |
| if hasattr(eevee, "shadow_cascade_size"): |
| eevee.shadow_cascade_size = '2048' |
| if hasattr(eevee, "use_denoise"): |
| eevee.use_denoise = True |
|
|
|
|
| def auto_crop_image(image_path, padding=10): |
| """裁剪图像透明边距 |
| |
| Args: |
| image_path: PNG 图像路径 |
| padding: 保留的边距像素 |
| """ |
| img = Image.open(image_path) |
| |
| if img.mode != "RGBA": |
| img = img.convert("RGBA") |
| |
| |
| alpha = img.split()[-1] |
| bbox = alpha.getbbox() |
| |
| if bbox is None: |
| return |
| |
| |
| left = max(0, bbox[0] - padding) |
| top = max(0, bbox[1] - padding) |
| right = min(img.width, bbox[2] + padding) |
| bottom = min(img.height, bbox[3] + padding) |
| |
| |
| cropped = img.crop((left, top, right, bottom)) |
| cropped.save(image_path) |
|
|
|
|
| def batch_render(results_dir, dataset_name=""): |
| """批量渲染""" |
| results_dir = Path(results_dir) |
| if not results_dir.exists(): |
| print(f"⚠️ 目录不存在: {results_dir}") |
| return 0 |
| |
| |
| scene_dirs = [d for d in results_dir.iterdir() |
| if d.is_dir() and ((d / "scene_graph.json").exists() or (d / "scene.json").exists())] |
| |
| print(f"\n📂 {dataset_name}: 找到 {len(scene_dirs)} 个场景") |
| |
| success = 0 |
| for i, scene_dir in enumerate(scene_dirs, 1): |
| |
| if (scene_dir / "render.png").exists(): |
| print(f"[{i}/{len(scene_dirs)}] {scene_dir.name} - 已存在,跳过") |
| success += 1 |
| success += 1 |
| continue |
| |
| print(f"[{i}/{len(scene_dirs)}] {scene_dir.name}") |
| if render_single_scene(scene_dir): |
| success += 1 |
| |
| print(f"\n✅ {dataset_name} 完成: {success}/{len(scene_dirs)}") |
| return success |
|
|
|
|
| def main(): |
| print(f"\n{'='*60}") |
| print("🎬 IDesign 批量渲染 (bpy)") |
| print(f"{'='*60}") |
| print(f"时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") |
| |
| |
| clear_default_cube() |
| |
| |
| zones_dir = "/home/v-meiszhang/amlt-project/MetaSpatial/IDesign/evaluation/evaluation_results" |
| batch_render(zones_dir, "zones") |
| |
| |
| bench_dir = "/home/v-meiszhang/amlt-project/MetaSpatial/IDesign/evaluation/layout_bench_results" |
| batch_render(bench_dir, "bench") |
| |
| print(f"\n{'='*60}") |
| print("✅ 全部完成") |
| print(f"{'='*60}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|