| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| """Blender script to render images of 3D models.""" |
| import argparse |
| import json |
| import math |
| import os |
| import random |
| import sys |
| from typing import Any, Callable, Dict, Generator, List, Literal, Optional, Set, Tuple |
|
|
| import bpy |
| import numpy as np |
| from mathutils import Matrix, Vector |
|
|
| IMPORT_FUNCTIONS: Dict[str, Callable] = { |
| "obj": bpy.ops.import_scene.obj, |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| } |
|
|
|
|
| def set_camera( |
| radius: float = 1.8, |
| theta: float = 0, |
| x: float = 0, |
| ) -> bpy.types.Object: |
| """Randomizes the camera location on a circle in the x,y plane and rotation towards the origin. |
| |
| Args: |
| radius (float, optional): Radius of the circle in the x,y plane. Defaults to 2.0. |
| minz (float, optional): Minimum z value of the camera. Defaults to -2.2. |
| maxz (float, optional): Maximum z value of the camera. Defaults to 2.2. |
| |
| Returns: |
| bpy.types.Object: The camera object. |
| """ |
|
|
| |
| z = radius * np.cos(theta) |
| y = radius * np.sin(theta) |
|
|
| |
| camera = bpy.data.objects["Camera"] |
| camera.location = Vector(np.array([x, y, z])) |
|
|
| |
| direction = -camera.location |
| rotation_euler = direction.to_track_quat("-Z", "Y").to_euler() |
| |
| camera.rotation_euler = rotation_euler |
|
|
| return camera |
|
|
|
|
| def _set_camera_at_size(i: int, scale: float = 1.5) -> bpy.types.Object: |
| """Debugging function to set the camera on the 6 faces of a cube. |
| |
| Args: |
| i (int): Index of the face of the cube. |
| scale (float, optional): Scale of the cube. Defaults to 1.5. |
| |
| Returns: |
| bpy.types.Object: The camera object. |
| """ |
| if i == 0: |
| x, y, z = scale, 0, 0 |
| elif i == 1: |
| x, y, z = -scale, 0, 0 |
| elif i == 2: |
| x, y, z = 0, scale, 0 |
| elif i == 3: |
| x, y, z = 0, -scale, 0 |
| elif i == 4: |
| x, y, z = 0, 0, scale |
| elif i == 5: |
| x, y, z = 0, 0, -scale |
| else: |
| raise ValueError(f"Invalid index: i={i}, must be int in range [0, 5].") |
| camera = bpy.data.objects["Camera"] |
| camera.location = Vector(np.array([x, y, z])) |
| direction = -camera.location |
| rot_quat = direction.to_track_quat("-Z", "Y") |
| camera.rotation_euler = rot_quat.to_euler() |
| return camera |
|
|
|
|
| def _create_light( |
| name: str, |
| light_type: Literal["POINT", "SUN", "SPOT", "AREA"], |
| location: Tuple[float, float, float], |
| rotation: Tuple[float, float, float], |
| energy: float, |
| use_shadow: bool = False, |
| specular_factor: float = 1.0, |
| ): |
| """Creates a light object. |
| |
| Args: |
| name (str): Name of the light object. |
| light_type (Literal["POINT", "SUN", "SPOT", "AREA"]): Type of the light. |
| location (Tuple[float, float, float]): Location of the light. |
| rotation (Tuple[float, float, float]): Rotation of the light. |
| energy (float): Energy of the light. |
| use_shadow (bool, optional): Whether to use shadows. Defaults to False. |
| specular_factor (float, optional): Specular factor of the light. Defaults to 1.0. |
| |
| Returns: |
| bpy.types.Object: The light object. |
| """ |
|
|
| light_data = bpy.data.lights.new(name=name, type=light_type) |
| light_object = bpy.data.objects.new(name, light_data) |
| bpy.context.collection.objects.link(light_object) |
| light_object.location = location |
| light_object.rotation_euler = rotation |
| light_data.use_shadow = use_shadow |
| light_data.specular_factor = specular_factor |
| light_data.energy = energy |
| return light_object |
|
|
|
|
| def randomize_lighting() -> Dict[str, bpy.types.Object]: |
| """Randomizes the lighting in the scene. |
| |
| Returns: |
| Dict[str, bpy.types.Object]: Dictionary of the lights in the scene. The keys are |
| "key_light", "fill_light", "rim_light", and "bottom_light". |
| """ |
|
|
| |
| bpy.ops.object.select_all(action="DESELECT") |
| bpy.ops.object.select_by_type(type="LIGHT") |
| bpy.ops.object.delete() |
|
|
| |
| key_light = _create_light( |
| name="Key_Light", |
| light_type="SUN", |
| location=(0, 0, 0), |
| rotation=(0.785398, 0, -0.785398), |
| energy=random.choice([3, 4, 5]), |
| ) |
|
|
| |
| fill_light = _create_light( |
| name="Fill_Light", |
| light_type="SUN", |
| location=(0, 0, 0), |
| rotation=(0.785398, 0, 2.35619), |
| energy=random.choice([2, 3, 4]), |
| ) |
|
|
| |
| rim_light = _create_light( |
| name="Rim_Light", |
| light_type="SUN", |
| location=(0, 0, 0), |
| rotation=(-0.785398, 0, -3.92699), |
| energy=random.choice([3, 4, 5]), |
| ) |
|
|
| |
| bottom_light = _create_light( |
| name="Bottom_Light", |
| light_type="SUN", |
| location=(0, 0, 0), |
| rotation=(3.14159, 0, 0), |
| energy=random.choice([1, 2, 3]), |
| ) |
|
|
| return dict( |
| key_light=key_light, |
| fill_light=fill_light, |
| rim_light=rim_light, |
| bottom_light=bottom_light, |
| ) |
|
|
|
|
| def reset_scene() -> None: |
| """Resets the scene to a clean state. |
| |
| Returns: |
| None |
| """ |
| |
| for obj in bpy.data.objects: |
| if obj.type not in {"CAMERA", "LIGHT"}: |
| bpy.data.objects.remove(obj, do_unlink=True) |
|
|
| |
| for material in bpy.data.materials: |
| bpy.data.materials.remove(material, do_unlink=True) |
|
|
| |
| for texture in bpy.data.textures: |
| bpy.data.textures.remove(texture, do_unlink=True) |
|
|
| |
| for image in bpy.data.images: |
| bpy.data.images.remove(image, do_unlink=True) |
|
|
|
|
| def load_object(object_path: str) -> None: |
| """Loads a model with a supported file extension into the scene. |
| |
| Args: |
| object_path (str): Path to the model file. |
| |
| Raises: |
| ValueError: If the file extension is not supported. |
| |
| Returns: |
| None |
| """ |
| |
|
|
| |
| |
| |
| bpy.ops.import_scene.obj(filepath=object_path) |
| return bpy.context.selected_objects[0] |
|
|
|
|
| def scene_bbox( |
| single_obj: Optional[bpy.types.Object] = None, ignore_matrix: bool = False |
| ) -> Tuple[Vector, Vector]: |
| """Returns the bounding box of the scene. |
| |
| Taken from Shap-E rendering script |
| (https://github.com/openai/shap-e/blob/main/shap_e/rendering/blender/blender_script.py#L68-L82) |
| |
| Args: |
| single_obj (Optional[bpy.types.Object], optional): If not None, only computes |
| the bounding box for the given object. Defaults to None. |
| ignore_matrix (bool, optional): Whether to ignore the object's matrix. Defaults |
| to False. |
| |
| Raises: |
| RuntimeError: If there are no objects in the scene. |
| |
| Returns: |
| Tuple[Vector, Vector]: The minimum and maximum coordinates of the bounding box. |
| """ |
| bbox_min = (math.inf,) * 3 |
| bbox_max = (-math.inf,) * 3 |
| found = False |
| for obj in get_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 get_scene_root_objects() -> Generator[bpy.types.Object, None, None]: |
| """Returns all root objects in the scene. |
| |
| Yields: |
| Generator[bpy.types.Object, None, None]: Generator of all root objects in the |
| scene. |
| """ |
| for obj in bpy.context.scene.objects.values(): |
| if not obj.parent: |
| yield obj |
|
|
|
|
| def get_scene_meshes() -> Generator[bpy.types.Object, None, None]: |
| """Returns all meshes in the scene. |
| |
| Yields: |
| Generator[bpy.types.Object, None, None]: Generator of all meshes in the scene. |
| """ |
| for obj in bpy.context.scene.objects.values(): |
| if isinstance(obj.data, (bpy.types.Mesh)): |
| yield obj |
|
|
|
|
| def get_3x4_RT_matrix_from_blender(cam: bpy.types.Object) -> Matrix: |
| """Returns the 3x4 RT matrix from the given camera. |
| |
| Taken from Zero123, which in turn was taken from |
| https://github.com/panmari/stanford-shapenet-renderer/blob/master/render_blender.py |
| |
| Args: |
| cam (bpy.types.Object): The camera object. |
| |
| Returns: |
| Matrix: The 3x4 RT matrix from the given camera. |
| """ |
| |
| location, rotation = cam.matrix_world.decompose()[0:2] |
| R_world2bcam = rotation.to_matrix().transposed() |
|
|
| |
| T_world2bcam = -1 * R_world2bcam @ location |
|
|
| |
| RT = Matrix( |
| ( |
| R_world2bcam[0][:] + (T_world2bcam[0],), |
| R_world2bcam[1][:] + (T_world2bcam[1],), |
| R_world2bcam[2][:] + (T_world2bcam[2],), |
| ) |
| ) |
| return RT |
|
|
|
|
| def delete_invisible_objects() -> None: |
| """Deletes all invisible objects in the scene. |
| |
| Returns: |
| None |
| """ |
| bpy.ops.object.select_all(action="DESELECT") |
| for obj in scene.objects: |
| if obj.hide_viewport or obj.hide_render: |
| obj.hide_viewport = False |
| obj.hide_render = False |
| obj.hide_select = False |
| obj.select_set(True) |
| bpy.ops.object.delete() |
|
|
| |
| invisible_collections = [col for col in bpy.data.collections if col.hide_viewport] |
| for col in invisible_collections: |
| bpy.data.collections.remove(col) |
|
|
|
|
| def normalize_scene() -> None: |
| """Normalizes the scene by scaling and translating it to fit in a unit cube centered |
| at the origin. |
| |
| Mostly taken from the Point-E / Shap-E rendering script |
| (https://github.com/openai/point-e/blob/main/point_e/evals/scripts/blender_script.py#L97-L112), |
| but fix for multiple root objects: (see bug report here: |
| https://github.com/openai/shap-e/pull/60). |
| |
| Returns: |
| None |
| """ |
| if len(list(get_scene_root_objects())) > 1: |
| |
| parent_empty = bpy.data.objects.new("ParentEmpty", None) |
| bpy.context.scene.collection.objects.link(parent_empty) |
|
|
| |
| for obj in get_scene_root_objects(): |
| if obj != parent_empty: |
| obj.parent = parent_empty |
|
|
| bbox_min, bbox_max = scene_bbox() |
| scale = 1 / max(bbox_max - bbox_min) |
| for obj in get_scene_root_objects(): |
| obj.scale = obj.scale * scale |
|
|
| |
| bpy.context.view_layer.update() |
| bbox_min, bbox_max = scene_bbox() |
| offset = -(bbox_min + bbox_max) / 2 |
| for obj in get_scene_root_objects(): |
| obj.matrix_world.translation += offset |
| bpy.ops.object.select_all(action="DESELECT") |
|
|
| |
| bpy.data.objects["Camera"].parent = None |
|
|
|
|
| def delete_missing_textures() -> Dict[str, Any]: |
| """Deletes all missing textures in the scene. |
| |
| Returns: |
| Dict[str, Any]: Dictionary with keys "count", "files", and "file_path_to_color". |
| "count" is the number of missing textures, "files" is a list of the missing |
| texture file paths, and "file_path_to_color" is a dictionary mapping the |
| missing texture file paths to a random color. |
| """ |
| missing_file_count = 0 |
| out_files = [] |
| file_path_to_color = {} |
|
|
| |
| for material in bpy.data.materials: |
| if material.use_nodes: |
| for node in material.node_tree.nodes: |
| if node.type == "TEX_IMAGE": |
| image = node.image |
| if image is not None: |
| file_path = bpy.path.abspath(image.filepath) |
| if file_path == "": |
| |
| continue |
|
|
| if not os.path.exists(file_path): |
| |
| connected_node = node.outputs[0].links[0].to_node |
|
|
| if connected_node.type == "BSDF_PRINCIPLED": |
| if file_path not in file_path_to_color: |
| |
| random_color = [random.random() for _ in range(3)] |
| file_path_to_color[file_path] = random_color + [1] |
|
|
| connected_node.inputs[ |
| "Base Color" |
| ].default_value = file_path_to_color[file_path] |
|
|
| |
| material.node_tree.nodes.remove(node) |
| missing_file_count += 1 |
| out_files.append(image.filepath) |
| return { |
| "count": missing_file_count, |
| "files": out_files, |
| "file_path_to_color": file_path_to_color, |
| } |
|
|
|
|
| def _get_random_color() -> Tuple[float, float, float, float]: |
| """Generates a random RGB-A color. |
| |
| The alpha value is always 1. |
| |
| Returns: |
| Tuple[float, float, float, float]: A random RGB-A color. Each value is in the |
| range [0, 1]. |
| """ |
| return (random.random(), random.random(), random.random(), 1) |
|
|
|
|
| def _apply_color_to_object( |
| obj: bpy.types.Object, color: Tuple[float, float, float, float] |
| ) -> None: |
| """Applies the given color to the object. |
| |
| Args: |
| obj (bpy.types.Object): The object to apply the color to. |
| color (Tuple[float, float, float, float]): The color to apply to the object. |
| |
| Returns: |
| None |
| """ |
| mat = bpy.data.materials.new(name=f"RandomMaterial_{obj.name}") |
| mat.use_nodes = True |
| nodes = mat.node_tree.nodes |
| principled_bsdf = nodes.get("Principled BSDF") |
| if principled_bsdf: |
| principled_bsdf.inputs["Base Color"].default_value = color |
| obj.data.materials.append(mat) |
|
|
|
|
| def apply_single_random_color_to_all_objects() -> Tuple[float, float, float, float]: |
| """Applies a single random color to all objects in the scene. |
| |
| Returns: |
| Tuple[float, float, float, float]: The random color that was applied to all |
| objects. |
| """ |
| rand_color = _get_random_color() |
| for obj in bpy.context.scene.objects: |
| if obj.type == "MESH": |
| _apply_color_to_object(obj, rand_color) |
| return rand_color |
|
|
|
|
| class MetadataExtractor: |
| """Class to extract metadata from a Blender scene.""" |
|
|
| def __init__( |
| self, object_path: str, scene: bpy.types.Scene, bdata: bpy.types.BlendData |
| ) -> None: |
| """Initializes the MetadataExtractor. |
| |
| Args: |
| object_path (str): Path to the object file. |
| scene (bpy.types.Scene): The current scene object from `bpy.context.scene`. |
| bdata (bpy.types.BlendData): The current blender data from `bpy.data`. |
| |
| Returns: |
| None |
| """ |
| self.object_path = object_path |
| self.scene = scene |
| self.bdata = bdata |
|
|
| def get_poly_count(self) -> int: |
| """Returns the total number of polygons in the scene.""" |
| total_poly_count = 0 |
| for obj in self.scene.objects: |
| if obj.type == "MESH": |
| total_poly_count += len(obj.data.polygons) |
| return total_poly_count |
|
|
| def get_vertex_count(self) -> int: |
| """Returns the total number of vertices in the scene.""" |
| total_vertex_count = 0 |
| for obj in self.scene.objects: |
| if obj.type == "MESH": |
| total_vertex_count += len(obj.data.vertices) |
| return total_vertex_count |
|
|
| def get_edge_count(self) -> int: |
| """Returns the total number of edges in the scene.""" |
| total_edge_count = 0 |
| for obj in self.scene.objects: |
| if obj.type == "MESH": |
| total_edge_count += len(obj.data.edges) |
| return total_edge_count |
|
|
| def get_lamp_count(self) -> int: |
| """Returns the number of lamps in the scene.""" |
| return sum(1 for obj in self.scene.objects if obj.type == "LIGHT") |
|
|
| def get_mesh_count(self) -> int: |
| """Returns the number of meshes in the scene.""" |
| return sum(1 for obj in self.scene.objects if obj.type == "MESH") |
|
|
| def get_material_count(self) -> int: |
| """Returns the number of materials in the scene.""" |
| return len(self.bdata.materials) |
|
|
| def get_object_count(self) -> int: |
| """Returns the number of objects in the scene.""" |
| return len(self.bdata.objects) |
|
|
| def get_animation_count(self) -> int: |
| """Returns the number of animations in the scene.""" |
| return len(self.bdata.actions) |
|
|
| def get_linked_files(self) -> List[str]: |
| """Returns the filepaths of all linked files.""" |
| image_filepaths = self._get_image_filepaths() |
| material_filepaths = self._get_material_filepaths() |
| linked_libraries_filepaths = self._get_linked_libraries_filepaths() |
|
|
| all_filepaths = ( |
| image_filepaths | material_filepaths | linked_libraries_filepaths |
| ) |
| if "" in all_filepaths: |
| all_filepaths.remove("") |
| return list(all_filepaths) |
|
|
| def _get_image_filepaths(self) -> Set[str]: |
| """Returns the filepaths of all images used in the scene.""" |
| filepaths = set() |
| for image in self.bdata.images: |
| if image.source == "FILE": |
| filepaths.add(bpy.path.abspath(image.filepath)) |
| return filepaths |
|
|
| def _get_material_filepaths(self) -> Set[str]: |
| """Returns the filepaths of all images used in materials.""" |
| filepaths = set() |
| for material in self.bdata.materials: |
| if material.use_nodes: |
| for node in material.node_tree.nodes: |
| if node.type == "TEX_IMAGE": |
| image = node.image |
| if image is not None: |
| filepaths.add(bpy.path.abspath(image.filepath)) |
| return filepaths |
|
|
| def _get_linked_libraries_filepaths(self) -> Set[str]: |
| """Returns the filepaths of all linked libraries.""" |
| filepaths = set() |
| for library in self.bdata.libraries: |
| filepaths.add(bpy.path.abspath(library.filepath)) |
| return filepaths |
|
|
| def get_scene_size(self) -> Dict[str, list]: |
| """Returns the size of the scene bounds in meters.""" |
| bbox_min, bbox_max = scene_bbox() |
| return {"bbox_max": list(bbox_max), "bbox_min": list(bbox_min)} |
|
|
| def get_shape_key_count(self) -> int: |
| """Returns the number of shape keys in the scene.""" |
| total_shape_key_count = 0 |
| for obj in self.scene.objects: |
| if obj.type == "MESH": |
| shape_keys = obj.data.shape_keys |
| if shape_keys is not None: |
| total_shape_key_count += ( |
| len(shape_keys.key_blocks) - 1 |
| ) |
| return total_shape_key_count |
|
|
| def get_armature_count(self) -> int: |
| """Returns the number of armatures in the scene.""" |
| total_armature_count = 0 |
| for obj in self.scene.objects: |
| if obj.type == "ARMATURE": |
| total_armature_count += 1 |
| return total_armature_count |
|
|
| def read_file_size(self) -> int: |
| """Returns the size of the file in bytes.""" |
| return os.path.getsize(self.object_path) |
|
|
| def get_metadata(self) -> Dict[str, Any]: |
| """Returns the metadata of the scene. |
| |
| Returns: |
| Dict[str, Any]: Dictionary of the metadata with keys for "file_size", |
| "poly_count", "vert_count", "edge_count", "material_count", "object_count", |
| "lamp_count", "mesh_count", "animation_count", "linked_files", "scene_size", |
| "shape_key_count", and "armature_count". |
| """ |
| return { |
| "file_size": self.read_file_size(), |
| "poly_count": self.get_poly_count(), |
| "vert_count": self.get_vertex_count(), |
| "edge_count": self.get_edge_count(), |
| "material_count": self.get_material_count(), |
| "object_count": self.get_object_count(), |
| "lamp_count": self.get_lamp_count(), |
| "mesh_count": self.get_mesh_count(), |
| "animation_count": self.get_animation_count(), |
| "linked_files": self.get_linked_files(), |
| "scene_size": self.get_scene_size(), |
| "shape_key_count": self.get_shape_key_count(), |
| "armature_count": self.get_armature_count(), |
| } |
|
|
|
|
| def set_background_color(r, g, b): |
| |
| scene = bpy.context.scene |
|
|
| |
| if not scene.world: |
| scene.world = bpy.data.worlds.new("World") |
|
|
| |
| scene.world.use_nodes = True |
| bg_node = scene.world.node_tree.nodes['Background'] |
| bg_node.inputs['Color'].default_value = (r, g, b, 1) |
|
|
| |
| scene.render.film_transparent = False |
|
|
|
|
| def render_object( |
| object_file: str, |
| num_renders: int, |
| only_northern_hemisphere: bool, |
| output_dir: str, |
| ) -> None: |
| """Saves rendered images with its camera matrix and metadata of the object. |
| |
| Args: |
| object_file (str): Path to the object file. |
| num_renders (int): Number of renders to save of the object. |
| only_northern_hemisphere (bool): Whether to only render sides of the object that |
| are in the northern hemisphere. This is useful for rendering objects that |
| are photogrammetrically scanned, as the bottom of the object often has |
| holes. |
| output_dir (str): Path to the directory where the rendered images and metadata |
| will be saved. |
| |
| Returns: |
| None |
| """ |
| os.makedirs(output_dir, exist_ok=True) |
|
|
| |
| reset_scene() |
| obj = load_object(object_file) |
|
|
| |
| cam = scene.objects["Camera"] |
| cam.data.lens = 35 |
| cam.data.sensor_width = 32 |
|
|
| |
| cam_constraint = cam.constraints.new(type="TRACK_TO") |
| cam_constraint.track_axis = "TRACK_NEGATIVE_Z" |
| cam_constraint.up_axis = "UP_Y" |
| |
| |
| |
|
|
| |
| |
| metadata_extractor = MetadataExtractor( |
| object_path=object_file, scene=scene, bdata=bpy.data |
| ) |
| metadata = metadata_extractor.get_metadata() |
|
|
| |
| |
| |
| |
| |
| missing_textures = delete_missing_textures() |
| metadata["missing_textures"] = missing_textures |
|
|
| |
| |
| |
| |
| |
| |
| metadata["random_color"] = None |
|
|
| |
| metadata_path = os.path.join(output_dir, "metadata.json") |
| os.makedirs(os.path.dirname(metadata_path), exist_ok=True) |
| with open(metadata_path, "w", encoding="utf-8") as f: |
| json.dump(metadata, f, sort_keys=True, indent=2) |
|
|
| |
| normalize_scene() |
|
|
| |
| set_background_color(0.5, 0.5, 0.5) |
| |
| |
| randomize_lighting() |
|
|
| |
| for i in range(num_renders): |
|
|
| theta = i * np.pi / 36 |
| |
| obj.rotation_euler.y = theta |
| |
|
|
| |
| camera = set_camera() |
|
|
| |
| render_path = os.path.join(output_dir, f"{i:03d}.png") |
| scene.render.filepath = render_path |
| bpy.ops.render.render(write_still=True) |
|
|
| |
| |
| |
| |
|
|
| def render_object_mask( |
| object_file: str, |
| num_renders: int, |
| output_dir: str, |
| ) -> None: |
| """Saves rendered masks of the object directly as npy files.""" |
| |
| os.makedirs(output_dir, exist_ok=True) |
|
|
| |
| reset_scene() |
| obj = load_object(object_file) |
|
|
| |
| cam = scene.objects["Camera"] |
| cam.data.lens = 35 |
| cam.data.sensor_width = 32 |
|
|
| |
| cam_constraint = cam.constraints.new(type="TRACK_TO") |
| cam_constraint.track_axis = "TRACK_NEGATIVE_Z" |
| cam_constraint.up_axis = "UP_Y" |
|
|
| |
| normalize_scene() |
|
|
| |
| mat = bpy.data.materials.new(name="WhiteMaterial") |
| mat.use_nodes = True |
| nodes = mat.node_tree.nodes |
| principled_bsdf = nodes.get("Principled BSDF") |
| if principled_bsdf: |
| principled_bsdf.inputs["Base Color"].default_value = (1, 1, 1, 1) |
| principled_bsdf.inputs["Emission"].default_value = (1, 1, 1, 1) |
| principled_bsdf.inputs["Emission Strength"].default_value = 2.0 |
|
|
| |
| if obj.data.materials: |
| obj.data.materials.clear() |
| obj.data.materials.append(mat) |
|
|
| |
| set_background_color(0, 0, 0) |
|
|
| |
| randomize_lighting() |
|
|
| |
| for i in range(num_renders): |
| print(f"Rendering mask {i+1}/{num_renders}") |
| |
| theta = i * np.pi / 36 |
| obj.rotation_euler.y = theta |
|
|
| |
| camera = set_camera() |
|
|
| |
| temp_png_path = os.path.join(output_dir, f"temp_{i:03d}.png") |
| scene.render.filepath = temp_png_path |
| bpy.ops.render.render(write_still=True) |
|
|
| |
| try: |
| |
| img = bpy.data.images.load(temp_png_path) |
| |
| |
| width, height = img.size |
| |
| |
| pixel_data = np.array(img.pixels[:]).reshape((height, width, 4)) |
| |
| |
| gray = np.mean(pixel_data[:, :, :3], axis=2) |
| mask = (gray > 0.5).astype(np.uint8) |
| |
| |
| mask = np.flipud(mask) |
|
|
| |
| npy_path = os.path.join(output_dir, f"{i:03d}_mask.npy") |
| np.save(npy_path, mask) |
| print(f"Saved mask to {npy_path}, mask shape: {mask.shape}") |
|
|
| |
| bpy.data.images.remove(img) |
| os.remove(temp_png_path) |
| |
| except Exception as e: |
| print(f"Failed to process mask for frame {i}: {e}") |
| |
| if os.path.exists(temp_png_path): |
| os.remove(temp_png_path) |
|
|
| def get_directories(input_path, output_path): |
| input_dir = [] |
| output_dir = [] |
| for root, dirs, files in os.walk(input_path): |
| if not dirs: |
| input_dir.append(root + "/Scan.obj") |
| no_head = root.replace(input_path, '') |
| output_dir.append(output_path + no_head) |
| return input_dir, output_dir |
|
|
| if __name__ == "__main__": |
| parser = argparse.ArgumentParser() |
| parser.add_argument( |
| "--object_path", |
| type=str, |
| required=True, |
| help="Path to the object file", |
| ) |
| parser.add_argument( |
| "--output_dir", |
| type=str, |
| required=True, |
| help="Path to the directory where the rendered images and metadata will be saved.", |
| ) |
| parser.add_argument( |
| "--engine", |
| type=str, |
| default="BLENDER_EEVEE", |
| choices=["CYCLES", "BLENDER_EEVEE"], |
| ) |
| parser.add_argument( |
| "--only_northern_hemisphere", |
| action="store_true", |
| help="Only render the northern hemisphere of the object.", |
| default=False, |
| ) |
| parser.add_argument( |
| "--num_renders", |
| type=int, |
| default=72, |
| help="Number of renders to save of the object.", |
| ) |
| parser.add_argument( |
| "--save_image", |
| type=str, |
| choices=["True", "False"], |
| default="True", |
| help="Whether to save the rendered images.", |
| ) |
|
|
|
|
| parser.add_argument( |
| "--save_mask", |
| type=str, |
| choices=["True", "False"], |
| default="False", |
| help="Whether to save the rendered masks as npy files.", |
| ) |
| argv = sys.argv[sys.argv.index("--") + 1 :] |
| args = parser.parse_args(argv) |
| args.save_image = args.save_image == "True" |
| args.save_mask = args.save_mask == "True" |
|
|
| context = bpy.context |
| scene = context.scene |
| render = scene.render |
|
|
| |
| render.engine = args.engine |
| render.image_settings.file_format = "PNG" |
| render.image_settings.color_mode = "RGB" |
| render.resolution_x = 128 |
| render.resolution_y = 128 |
| render.resolution_percentage = 100 |
|
|
| |
| scene.cycles.device = "GPU" |
| scene.cycles.samples = 128 |
| scene.cycles.diffuse_bounces = 1 |
| scene.cycles.glossy_bounces = 1 |
| scene.cycles.transparent_max_bounces = 3 |
| scene.cycles.transmission_bounces = 3 |
| scene.cycles.filter_width = 0.01 |
| scene.cycles.use_denoising = True |
| scene.render.film_transparent = True |
| bpy.context.preferences.addons["cycles"].preferences.get_devices() |
| bpy.context.preferences.addons[ |
| "cycles" |
| ].preferences.compute_device_type = "CUDA" |
|
|
| |
| input_dir, output_dir = get_directories(args.object_path, args.output_dir) |
| num_render_files = len(input_dir) |
| for i in range(num_render_files): |
| |
| |
| if args.save_image and not os.path.exists( |
| os.path.join(output_dir[i], f"{args.num_renders - 1:03d}.png") |
| ): |
| |
| render_object( |
| object_file=input_dir[i], |
| num_renders=args.num_renders, |
| only_northern_hemisphere=args.only_northern_hemisphere, |
| output_dir=output_dir[i], |
| ) |
| |
| if args.save_mask and not os.path.exists( |
| os.path.join(output_dir[i], f"{args.num_renders - 1:03d}_mask.npy") |
| ): |
| |
| render_object_mask( |
| object_file=input_dir[i], |
| num_renders=args.num_renders, |
| output_dir=output_dir[i], |
| ) |
|
|