import blenderproc as bproc import numpy as np import os os.environ["OPENCV_IO_ENABLE_OPENEXR"]="1" import json import bpy import cv2 from PIL import Image import math from mathutils import Vector, Matrix import argparse parser = argparse.ArgumentParser() parser.add_argument('--glb_path', type=str) parser.add_argument('--output_dir', type=str, default='output') args = parser.parse_args() # load the glb model def load_object(object_path: str) -> None: """Loads a glb model into the scene.""" if object_path.endswith(".glb") or object_path.endswith(".gltf"): bpy.ops.import_scene.gltf(filepath=object_path, merge_vertices=False) elif object_path.endswith(".fbx"): bpy.ops.import_scene.fbx(filepath=object_path) elif object_path.endswith(".obj"): bpy.ops.import_scene.obj(filepath=object_path) elif object_path.endswith(".ply"): bpy.ops.import_mesh.ply(filepath=object_path) else: raise ValueError(f"Unsupported file type: {object_path}") def load_envmap(envmap_path: str) -> None: """Loads an environment map into the scene.""" world = bpy.context.scene.world world.use_nodes = True bg = world.node_tree.nodes['Background'] envmap = world.node_tree.nodes.new('ShaderNodeTexEnvironment') envmap.image = bpy.data.images.load(envmap_path) world.node_tree.links.new(bg.inputs['Color'], envmap.outputs['Color']) def turn_off_metallic(): # use for albedo rendering, metallic will affect the color materials = bproc.material.collect_all() for mat in materials: mat.set_principled_shader_value('Metallic', 0.0) def camera_pose(azimuth, elevation, radius=1.5): """Camera look at the origin.""" azimuth = np.deg2rad(azimuth) elevation = np.deg2rad(elevation) x = radius * np.cos(azimuth) * np.cos(elevation) y = -radius * np.sin(azimuth) * np.cos(elevation) z = radius * np.sin(elevation) camera_position = np.array([x, y, z]) camera_forward = camera_position / np.linalg.norm(camera_position) camera_right = np.cross(np.array([0.0, 0.0, 1.0]), camera_forward) camera_right /= np.linalg.norm(camera_right) camera_up = np.cross(camera_forward, camera_right) camera_up /= np.linalg.norm(camera_up) camera_pose = np.eye(4) camera_pose[:3, 0] = camera_right camera_pose[:3, 1] = camera_up camera_pose[:3, 2] = camera_forward camera_pose[:3, 3] = camera_position return camera_pose def scene_root_objects(): for obj in bpy.context.scene.objects.values(): if not obj.parent: yield obj def scene_meshes(): for obj in bpy.context.scene.objects.values(): if isinstance(obj.data, (bpy.types.Mesh)): yield obj def scene_bbox(single_obj=None, ignore_matrix=False): bbox_min = (math.inf,) * 3 bbox_max = (-math.inf,) * 3 found = False for obj in scene_meshes() if single_obj is None else [single_obj]: found = True for coord in obj.bound_box: coord = Vector(coord) if not ignore_matrix: coord = obj.matrix_world @ coord bbox_min = tuple(min(x, y) for x, y in zip(bbox_min, coord)) bbox_max = tuple(max(x, y) for x, y in zip(bbox_max, coord)) if not found: raise RuntimeError("no objects in scene to compute bounding box for") return Vector(bbox_min), Vector(bbox_max) def normalize_scene(): bbox_min, bbox_max = scene_bbox() scale = 1 / max(bbox_max - bbox_min) for obj in scene_root_objects(): obj.scale = obj.scale * scale # Apply scale to matrix_world. bpy.context.view_layer.update() bbox_min, bbox_max = scene_bbox() offset = -(bbox_min + bbox_max) / 2 for obj in scene_root_objects(): obj.matrix_world.translation += offset bpy.ops.object.select_all(action="DESELECT") return scale, offset def reset_normal(): """experimental!!! reset normal """ for obj in scene_meshes(): bpy.context.view_layer.objects.active = obj bpy.ops.object.mode_set(mode='EDIT') bpy.ops.mesh.normals_tools(mode='RESET') bpy.ops.object.mode_set(mode='OBJECT') def change_to_orm(): materials = bproc.material.collect_all() for mat in materials: orm_color = mat.nodes.new(type='ShaderNodeCombineRGB') principled_bsdf = mat.get_the_one_node_with_type("BsdfPrincipled") # metallic -> Blue if principled_bsdf.inputs['Metallic'].links: metallic_from_socket = principled_bsdf.inputs['Metallic'].links[0].from_socket metallic_link = mat.links.new(metallic_from_socket, orm_color.inputs['B']) mat.links.remove(principled_bsdf.inputs['Metallic'].links[0]) else: metallic_value = principled_bsdf.inputs['Metallic'].default_value orm_color.inputs['B'].default_value = metallic_value principled_bsdf.inputs['Metallic'].default_value = 0.0 # roughness -> Green if principled_bsdf.inputs['Roughness'].links: roughness_from_socket = principled_bsdf.inputs['Roughness'].links[0].from_socket roughness_link = mat.links.new(roughness_from_socket, orm_color.inputs['G']) mat.links.remove(principled_bsdf.inputs['Roughness'].links[0]) else: roughness_value = principled_bsdf.inputs['Roughness'].default_value orm_color.inputs['G'].default_value = roughness_value principled_bsdf.inputs['Roughness'].default_value = 0.5 # link orm_color to principled_bsdf as base color mat.links.new(orm_color.outputs['Image'], principled_bsdf.inputs['Base Color']) def is_bsdf(): for mat in bproc.material.collect_all(): node = mat.get_nodes_with_type('BsdfPrincipled') if node and len(node) == 1: pass else: return False return True def sample_sphere(num_samples): radiuss = np.random.uniform(1.5, 2.0, size=num_samples) azimuth = np.random.uniform(0, 360, size=num_samples) elevation = np.random.uniform(-90, 90, size=num_samples) return radiuss, azimuth, elevation NUM_IMAGES = 12 meta_info = {'transform_matrix': []} bproc.init() # bproc.renderer.set_render_devices(use_only_cpu=True) bpy.context.scene.view_settings.view_transform = 'Raw' # do not use sRGB glb_path = args.glb_path obj_name = os.path.basename(glb_path).split('.')[0] load_object(glb_path) if not is_bsdf(): exit() scale, offset = normalize_scene() meta_info['scale'] = scale meta_info['offset'] = offset.to_tuple() reset_normal() change_to_orm() radiuss, azimuths, elevations = sample_sphere(NUM_IMAGES) meta_info['raidus'] = radiuss.tolist() meta_info['azimuths'] = azimuths.tolist() meta_info['elevations'] = elevations.tolist() # set camera bproc.camera.set_resolution(512, 512) for radius, azimuth, elevation in zip(radiuss, azimuths, elevations): cam_pose = camera_pose(azimuth, elevation, radius=radius) bproc.camera.add_camera_pose(cam_pose) meta_info['transform_matrix'].append(cam_pose.tolist()) bproc.renderer.enable_normals_output() bproc.renderer.enable_diffuse_color_output() bproc.renderer.set_output_format(enable_transparency=True) data = bproc.renderer.render() output_dir = args.output_dir os.makedirs(os.path.join(output_dir, obj_name), exist_ok=True) for i in range(len(azimuths)): image = data['diffuse'][i] Image.fromarray(image).save(os.path.join(output_dir, obj_name, f'orm_{i:02d}.png')) normal = data['normals'][i] cv2.imwrite(os.path.join(output_dir, obj_name, f'normal_{i:02d}.exr'), normal) with open(os.path.join(output_dir, obj_name, 'camera.json'), 'w') as f: json.dump(meta_info, f, indent=4)