File size: 9,190 Bytes
7e0a892 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 |
import blenderproc as bproc
import numpy as np
import os
os.environ["OPENCV_IO_ENABLE_OPENEXR"]="1"
import json
import bpy
import cv2
import glob
import random
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('--hdri_path', type=str, default=None)
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
def remove_lighting():
# remove world background lighting
world = bpy.context.scene.world
nodes = world.node_tree.nodes
for node in nodes:
if node.type == 'TEX_ENVIRONMENT':
nodes.remove(node)
# remove all lights
for obj in bpy.context.scene.objects.values():
if obj.type == 'LIGHT':
bpy.data.objects.remove(obj)
def set_point_light():
light = bproc.types.Light()
light.set_type('POINT')
light.set_location(bproc.sampler.shell(
center=[0, 0, 0],
radius_min=5,
radius_max=7,
elevation_min=-35,
elevation_max=70
))
light.set_energy(500)
return light
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
output_dir = args.output_dir
obj_name = os.path.basename(glb_path).split('.')[0]
load_object(glb_path)
scale, offset = normalize_scene()
reset_normal()
# load camera info
with open(os.path.join(output_dir, obj_name, 'camera.json'), 'r') as f:
meta_info = json.load(f)
radiuss = np.array(meta_info['raidus'])
azimuths = np.array(meta_info['azimuths'])
elevations = np.array(meta_info['elevations'])
# 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)
lighting_fn = os.path.join(output_dir, obj_name, 'lighting.json')
if os.path.exists(lighting_fn):
with open(lighting_fn, 'r') as f:
lighting_info = json.load(f)
else:
lighting_info = []
hdr_file = args.hdri_path
if hdr_file is not None:
bproc.world.set_world_background_hdr_img(hdr_file)
bproc.renderer.set_output_format(enable_transparency=True)
data = bproc.renderer.render()
for i in range(len(azimuths)):
image = data['colors'][i]
Image.fromarray(image).save(os.path.join(output_dir, obj_name, f'color_{len(lighting_info)}_{i:02d}.png'))
lighting_info.append(
{
'type': 'hdri',
'path': os.path.basename(hdr_file),
}
)
else:
# Point lighting, 1 sample
remove_lighting()
light1 = set_point_light()
light2 = set_point_light()
bproc.renderer.set_output_format(enable_transparency=True)
data = bproc.renderer.render()
for i in range(len(azimuths)):
image = data['colors'][i]
Image.fromarray(image).save(os.path.join(output_dir, obj_name, f'color_{len(lighting_info)}_{i:02d}.png'))
lighting_info.append(
{
'type': 'point',
'locations': [light1.get_location().tolist(), light2.get_location().tolist()],
'energys': [light1.get_energy(), light2.get_energy()],
}
)
with open(lighting_fn, 'w') as f:
json.dump(lighting_info, f, indent=4)
|