enviably9625's picture
Upload folder using huggingface_hub (part 2)
acdc230 verified
Raw History Blame Contribute Delete
9.35 kB
import tomllib
import bpy
import os
import json
import mathutils
import itertools
import math
import tomllib
import sys
import argparse
cam_order_file = "splatworks_cam_order.txt"
depth_dir = "depths/"
normal_dir = "normals/"
masks_dir = "masks/"
params_dir = "cam_params/"
output_dir = bpy.path.abspath("//")
with open(output_dir + "scene_data.toml", "rb") as f:
data = tomllib.load(f)
scene_data = data["scene_data"]
# TOML has no tuple type, so ref_objs comes back as a list of lists.
# Convert back to a list of tuples to match the original structure.
scene_data["ref_objs"] = [tuple(obj) for obj in scene_data["ref_objs"]]
if len(scene_data["ref_objs"]) == 0:
skip_ref = True
else:
skip_ref = False
soils2weights = data["soils2weights"]
traj2offset = data["traj2offset"]
def parse_args():
# Blender swallows its own args and passes everything after a
# standalone "--" straight through, so only look at that slice.
if "--" in sys.argv:
argv = sys.argv[sys.argv.index("--") + 1:]
else:
argv = []
parser = argparse.ArgumentParser()
parser.add_argument(
"--world",
type=str,
default=None,
help="Name of a single world map to render (must match a name in "
"scene_data['world_maps']). If omitted, all world maps are "
"rendered, same as before.",
)
parser.add_argument(
"--gt",
action=argparse.BooleanOptionalAction,
default=None,
help="Whether to write ground truth depth/mask output. Pass "
"--gt to force it on, --no-gt to force it off and save "
"disk space. If omitted, falls back to scene_data['gt'] "
"from the TOML, same as before.",
)
return parser.parse_args(argv)
def main():
args = parse_args()
write_gt = scene_data["gt"] if args.gt is None else args.gt
render(scene_data, selected_world=args.world, write_gt=write_gt)
def render(scene_data, selected_world=None, write_gt=None):
if write_gt is None:
write_gt = scene_data["gt"]
world_maps = scene_data["world_maps"]
if selected_world is not None:
if selected_world not in world_maps:
raise ValueError(
f"'{selected_world}' not found in scene_data['world_maps']: "
f"{world_maps}"
)
world_maps = [selected_world]
for traj in scene_data["trajectories"]:
for world in world_maps:
bpy.context.scene.world = bpy.data.worlds[world]
render_world(
traj,
scene_data["soil_settings"],
world,
output_dir,
True,
write_gt,
)
if not skip_ref:
render_world(
traj,
scene_data["ref_settings"],
world,
output_dir,
False,
write_gt,
)
def render_world(traj, settings, world, output_dir, is_soiling: bool, write_gt: bool):
frame_start = scene_data["frame_start"]
frame_stop = scene_data["frame_end"]
traj_label, frame_stop = get_traj_label_frame_stop(traj, frame_stop)
nodes = bpy.data.node_groups["Compositing Node Tree"].nodes
for setting in settings:
if skip_ref:
coat_label = "soil=verylow"
else:
coat_label = setup_material(is_soiling, setting)
coat_dir = ",".join([coat_label, traj_label, "clean"])
img_path = os.path.join(output_dir, world, coat_dir)
coat_gt_dir = ",".join([coat_label, traj_label])
depth_path = os.path.join(output_dir, depth_dir, world, coat_gt_dir)
param_path = os.path.join(
output_dir, params_dir, world, coat_gt_dir)
mask_path = os.path.join(output_dir, masks_dir, world, coat_gt_dir)
os.makedirs(img_path, exist_ok=True)
os.makedirs(depth_path, exist_ok=True)
os.makedirs(param_path, exist_ok=True)
os.makedirs(mask_path, exist_ok=True)
nodes["Depth Output"].directory = depth_path
nodes["Image Output"].directory = img_path
nodes["Mask Output"].directory = mask_path
render_frames(traj, frame_start, frame_stop,
param_path, write_gt)
def setup_material(is_soiling, setting):
ref_obj_names = scene_data["ref_objs"]
if is_soiling:
set_objs_materials(ref_obj_names, scene_data["soiling_mat_name"])
set_soil_weight(
scene_data["soiling_mat_name"], soils2weights[setting])
coat_label = "soil=" + setting
else:
# if it's not soiling, it's reflectivity
set_objs_materials(ref_obj_names, scene_data['ref_mat_name'])
set_ref_weight(scene_data["ref_mat_name"], setting)
coat_label = "ref=" + str(setting)
return coat_label
def render_frames(
traj: str,
frame_start: int,
frame_stop: int,
param_frame_dir: str,
write_GT: bool,
):
if traj != "trendspek":
valid_cams = get_valid_cams(traj)
else:
valid_cams = ["Camera"]*frame_stop
print(f"Rendering up to frame: {frame_stop}")
nodes = bpy.data.node_groups["Compositing Node Tree"].nodes
for frame in range(frame_start, frame_stop):
bpy.context.scene.frame_set(frame) # set the current frame
frame_string = str("%08d" % frame)
print(f"Rendering Frame {frame}")
cam_name = valid_cams[frame]
select_camera(cam_name)
cam = bpy.data.objects[cam_name]
cam_data_name = os.path.join(
param_frame_dir, frame_string + ".json")
nodes["Enable Depth"].inputs[0].default_value = write_GT
nodes["Enable Mask"].inputs[0].default_value = write_GT
nodes["Image Output"].file_name = frame_string + ".jpg"
nodes["Mask Output"].file_name = frame_string + ".png"
nodes["Depth Output"].file_name = frame_string + ".exr"
bpy.ops.render.render()
export_cam_parameters(cam_data_name, cam)
def get_traj_label_frame_stop(traj, frame_stop):
if traj == "trendspek":
traj_label = "traj=" + traj
else:
valid_cams = get_valid_cams(traj)
n_valid_cams = len(valid_cams)
frame_stop = min(frame_stop, n_valid_cams)
traj_label = "traj=proxy_surface_" + str(traj2offset[traj])
return traj_label, frame_stop
def get_valid_cams(traj):
offset = traj2offset[traj]
scene = bpy.context.scene
scene.splatworks_props.camera_proxy_offset = offset
cam_order_file_path = os.path.join(
output_dir,
"cam_order",
f"traj=proxy_surface_{offset}",
cam_order_file
)
valid_cams = load_cam_names(cam_order_file_path)
return valid_cams
def select_camera(name):
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
if "vehicle" in bpy.data.objects.keys():
drone = bpy.data.objects['vehicle']
drone.constraints['Copy Location'].target = bpy.data.objects[name]
drone.constraints['Copy Rotation'].target = bpy.data.objects[name]
print(drone.constraints['Copy Location'].target)
except KeyError:
print(f"No camera object called {name}")
raise ValueError(f"No camera object called {name}")
def load_cam_names(f_name):
with open(f_name) as f:
contents = f.read()
return contents.split('\n')[:-1]
def set_objs_materials(ref_objs: list[tuple], mat_name: str):
for ref_obj in ref_objs:
obj_name = ref_obj[0]
slot = ref_obj[1]
obj = bpy.data.objects[obj_name]
obj_mat_slot = obj.material_slots[slot]
obj_mat_slot.material = bpy.data.materials[mat_name]
def set_soil_weight(mat_name: str, weight: float):
mat = bpy.data.materials[mat_name]
mat.node_tree.nodes["Math"].inputs[1].default_value = weight
def set_ref_weight(mat_name: str, weight: float):
mat = bpy.data.materials[mat_name]
mat.node_tree.nodes["Mix Shader.001"].inputs[0].default_value = 1 - 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.Quaternion(cam_obj.rotation_quaternion)
out_dict = {
"name": cam_obj.name,
"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()