Slighting3121's picture
Upload render_office.py
92ca605 verified
"""
Script to render the office building and scenes of that kind
"""
import bpy
import math
import os
import json
import mathutils
import copy
import itertools
output_dir = bpy.path.abspath("//target_dir/")
depth_dir = "depths/"
normal_dir = "normals/"
params_dir = "cam_params/"
cam_data = {
# Ojbect parameters or Camera Extrinsics
# XYZ coordinate
"loc": (0.0, -6.0, 1.0),
# Quarternion for rotation
"rot": (math.sqrt(2) / 2, math.sqrt(2) / 2, 0.0, 0.0),
# Camera intrinisics
"focal_length": 50,
# "focal_length_unit": "FOV",
"sensor_width": 36.0,
}
scene_data = {
"cam_name": "Camera",
"frame_start": 0,
"frame_end": 1,
"key_material_name": "Window Glass Cycle",
"diffuse_weights": [0.01, 0.02, 0.05, 0.1],
}
def selectName(name="Camera", cam_info=None):
try:
ob = bpy.context.scene.objects[name] # Get the object
bpy.ops.object.select_all(action="DESELECT") # Deselect all objects
bpy.context.view_layer.objects.active = ob # Make the cube the active object
ob.select_set(True)
bpy.context.scene.camera = ob
print("Selected object: %s" % name)
if cam_info:
keys = cam_info.keys()
for key, attr in [("loc", "location"), ("rot", "rotation_quaternion")]:
if key in keys:
setattr(ob, attr, cam_info[key])
for key, attr in [
("focal_length_unit", "lens_unit"),
("focal_length", "lens"),
("sensor_width", "sensor_width"),
]:
if key in keys:
setattr(ob.data, attr, cam_info[key])
except:
create_cam(name, cam_info)
def create_cam(name="Camera", cam_info=None):
cam_data = bpy.data.cameras.new(name=name)
cam_obj = bpy.data.objects.new(name=name, object_data=cam_data)
if cam_info:
cam_obj.location = cam_info["loc"]
cam_obj.rotation_quaternion = cam_info["rot"]
bpy.context.collection.objects.link(cam_obj)
def main():
selectName(scene_data["cam_name"])
render(cam_data, scene_data)
def render(cam_info, scene_data):
frame_start = scene_data["frame_start"]
frame_stop = scene_data["frame_end"]
cam = bpy.context.scene.objects[scene_data["cam_name"]]
depth_map_dir = os.path.join(output_dir, depth_dir)
normal_map_dir = os.path.join(output_dir, normal_dir)
nodes = bpy.data.node_groups["Compositing Node Tree"].nodes
param_frame_dir = os.path.join(output_dir, params_dir)
os.makedirs(param_frame_dir, exist_ok=True)
for diffuse_weight in scene_data["diffuse_weights"]:
set_diffuse_weight(scene_data["key_material_name"], diffuse_weight)
coat_dir = "coat_" + "{:.2%}".format(diffuse_weight) + "/"
print(coat_dir)
coat_img_dir = os.path.join(output_dir, coat_dir)
os.makedirs(coat_img_dir, exist_ok=True)
if diffuse_weight == 0.01:
write_GT = True
else:
write_GT = False
for frame in range(frame_start, frame_stop):
bpy.context.scene.frame_set(frame) # set the current frame
frame_string = str("%08d" % frame)
if write_GT:
cam_data_name = os.path.join(
param_frame_dir, frame_string + ".json")
export_cam_parameters(cam_data_name, cam)
nodes["Enable Depth"].inputs[0].default_value = True
nodes["Enable Normal"].inputs[0].default_value = False
else:
nodes["Enable Depth"].inputs[0].default_value = False
nodes["Enable Normal"].inputs[0].default_value = False
nodes["Image Output"].directory = coat_img_dir
nodes["Image Output"].file_name = frame_string + ".jpg"
nodes["Depth Output"].directory = depth_map_dir
nodes["Depth Output"].file_name = frame_string + ".exr"
bpy.ops.render.render()
def set_diffuse_weight(mat_name: str, weight: float):
"""
Very low is 0.01, low is 0.02, medium is 0.05 and high is 0.1
"""
mat = bpy.data.materials[mat_name]
mat.node_tree.nodes["Math"].inputs[1].default_value = weight
def export_cam_parameters(f_name, cam_obj):
"""
Export the camera parameters for a given camera object to a file
"""
rot_mode = cam_obj.rotation_mode
rot_mode_tuple = tuple(rot_mode)
if rot_mode_tuple in list(itertools.permutations("XYZ", 3)):
eul = mathutils.Euler(cam_obj.rotation_euler, rot_mode)
rot_out = eul.to_quaternion()
elif rot_mode == "AXIS_ANGLE":
raise NotImplementedError()
else: # quaternion case
rot_out = mathutils.Quarternion(cam_obj.rotation_quaternion)
out_dict = {
"loc": tuple(cam_obj.location),
"rot": [rot_out.w, rot_out.x, rot_out.y, rot_out.z],
"focal_length": cam_obj.data.lens,
"sensor_width": cam_obj.data.sensor_width,
"clip_end": cam_obj.data.clip_end,
"clip_start": cam_obj.data.clip_start,
}
with open(f_name, "w") as f:
json.dump(out_dict, f, indent="\t")
if __name__ == "__main__":
main()