Ejemplo n.º 1
0
    def run(self):
        # Set language if necessary
        if bpy.context.preferences.view.language != "en_US":
            print("Setting blender language settings to english during this run")
            bpy.context.preferences.view.language = "en_US"

        prefs = bpy.context.preferences.addons['cycles'].preferences
        # Use cycles
        bpy.context.scene.render.engine = 'CYCLES'

        if platform == "darwin":
            # there is no gpu support in mac os so use the cpu with maximum power
            bpy.context.scene.cycles.device = "CPU"
            bpy.context.scene.render.threads = multiprocessing.cpu_count()
        else:
            bpy.context.scene.cycles.device = "GPU"
            preferences = bpy.context.preferences.addons['cycles'].preferences
            for device_type in preferences.get_device_types(bpy.context):
                preferences.get_devices_for_type(device_type[0])
            for gpu_type in ["OPTIX", "CUDA"]:
                found = False
                for device in preferences.devices:
                    if device.type == gpu_type:
                        bpy.context.preferences.addons['cycles'].preferences.compute_device_type = gpu_type
                        print('Device {} of type {} found and used.'.format(device.name, device.type))
                        found = True
                        break
                if found:
                    break
            # make sure that all visible GPUs are used
            for group in prefs.get_devices():
                for d in group:
                    d.use = True

        # setting the frame end, will be changed by the camera loader modules
        bpy.context.scene.frame_end = 0

        # Sets background color
        world = bpy.data.worlds['World']
        world.color[:3] = self.config.get_list("horizon_color", [0.535, 0.633, 0.608])

        # Create the camera
        cam = bpy.data.cameras.new("Camera")
        cam_ob = bpy.data.objects.new("Camera", cam)
        bpy.context.scene.collection.objects.link(cam_ob)
        bpy.context.scene.camera = cam_ob

        # Set default intrinsics
        CameraUtility.set_intrinsics_from_blender_params(DefaultConfig.fov, DefaultConfig.resolution_x, DefaultConfig.resolution_y, DefaultConfig.clip_start, DefaultConfig.clip_end, DefaultConfig.pixel_aspect_x, DefaultConfig.pixel_aspect_y, DefaultConfig.shift_x, DefaultConfig.shift_y, "FOV")
        CameraUtility.set_stereo_parameters(DefaultConfig.stereo_convergence_mode, DefaultConfig.stereo_convergence_distance, DefaultConfig.stereo_interocular_distance)

        random_seed = os.getenv("BLENDER_PROC_RANDOM_SEED")
        if random_seed:
            print("Got random seed: {}".format(random_seed))
            try:
                random_seed = int(random_seed)
            except ValueError as e:
                raise e
            random.seed(random_seed)
            np_random.seed(random_seed)
Ejemplo n.º 2
0
    def set_default_parameters():
        """ Loads and sets default parameters defined in DefaultConfig.py """
        # Set default intrinsics
        CameraUtility.set_intrinsics_from_blender_params(
            DefaultConfig.fov, DefaultConfig.resolution_x,
            DefaultConfig.resolution_y, DefaultConfig.clip_start,
            DefaultConfig.clip_end, DefaultConfig.pixel_aspect_x,
            DefaultConfig.pixel_aspect_y, DefaultConfig.shift_x,
            DefaultConfig.shift_y, "FOV")
        CameraUtility.set_stereo_parameters(
            DefaultConfig.stereo_convergence_mode,
            DefaultConfig.stereo_convergence_distance,
            DefaultConfig.stereo_interocular_distance)

        # Init renderer
        RendererUtility.init()
        RendererUtility.set_samples(DefaultConfig.samples)
        addon_utils.enable("render_auto_tile_size")
        RendererUtility.toggle_auto_tile_size(True)

        # Set number of cpu cores used for rendering (1 thread is always used for coordination => 1
        # cpu thread means GPU-only rendering)
        RendererUtility.set_cpu_threads(1)
        RendererUtility.set_denoiser(DefaultConfig.denoiser)

        RendererUtility.set_simplify_subdivision_render(
            DefaultConfig.simplify_subdivision_render)

        RendererUtility.set_light_bounces(
            DefaultConfig.diffuse_bounces, DefaultConfig.glossy_bounces,
            DefaultConfig.ao_bounces_render, DefaultConfig.max_bounces,
            DefaultConfig.transmission_bounces,
            DefaultConfig.transparency_bounces, DefaultConfig.volume_bounces)
Ejemplo n.º 3
0
    def _set_cam_intrinsics(self, cam, config):
        """ Sets camera intrinsics from a source with following priority

           1. from config function parameter if defined
           2. from custom properties of cam if set in Loader
           3. default config
                resolution_x/y: 512 
                pixel_aspect_x: 1
                clip_start:   : 0.1
                clip_end      : 1000
                fov           : 0.691111
        :param cam: The camera which contains only camera specific attributes.
        :param config: A configuration object with cam intrinsics.
        """
        if config.is_empty():
            return

        width = config.get_int("resolution_x",
                               bpy.context.scene.render.resolution_x)
        height = config.get_int("resolution_y",
                                bpy.context.scene.render.resolution_y)

        # Clipping
        clip_start = config.get_float("clip_start", cam.clip_start)
        clip_end = config.get_float("clip_end", cam.clip_end)

        if config.has_param("cam_K"):
            if config.has_param("fov"):
                print(
                    'WARNING: FOV defined in config is ignored. Mutually exclusive with cam_K'
                )
            if config.has_param("pixel_aspect_x"):
                print(
                    'WARNING: pixel_aspect_x defined in config is ignored. Mutually exclusive with cam_K'
                )

            cam_K = np.array(config.get_list("cam_K")).reshape(3, 3).astype(
                np.float32)

            CameraUtility.set_intrinsics_from_K_matrix(cam_K, width, height,
                                                       clip_start, clip_end)
        else:
            # Set FOV
            fov = config.get_float("fov", cam.angle)

            # Set Pixel Aspect Ratio
            pixel_aspect_x = config.get_float(
                "pixel_aspect_x", bpy.context.scene.render.pixel_aspect_x)
            pixel_aspect_y = config.get_float(
                "pixel_aspect_y", bpy.context.scene.render.pixel_aspect_y)

            # Set camera shift
            shift_x = config.get_float("shift_x", cam.shift_x)
            shift_y = config.get_float("shift_y", cam.shift_y)

            CameraUtility.set_intrinsics_from_blender_params(fov,
                                                             width,
                                                             height,
                                                             clip_start,
                                                             clip_end,
                                                             pixel_aspect_x,
                                                             pixel_aspect_y,
                                                             shift_x,
                                                             shift_y,
                                                             lens_unit="FOV")

        CameraUtility.set_stereo_parameters(
            config.get_string("stereo_convergence_mode",
                              cam.stereo.convergence_mode),
            config.get_float("convergence_distance",
                             cam.stereo.convergence_distance),
            config.get_float("interocular_distance",
                             cam.stereo.interocular_distance))
Ejemplo n.º 4
0
    def _set_cam_intrinsics(self, cam, config):
        """ Sets camera intrinsics from a source with following priority

           1. from config function parameter if defined
           2. from custom properties of cam if set in Loader
           3. default config:
                resolution_x/y: 512
                pixel_aspect_x: 1
                clip_start:   : 0.1
                clip_end      : 1000
                fov           : 0.691111

        :param cam: The camera which contains only camera specific attributes.
        :param config: A configuration object with cam intrinsics.
        """
        if config.is_empty():
            return

        width = config.get_int("resolution_x",
                               bpy.context.scene.render.resolution_x)
        height = config.get_int("resolution_y",
                                bpy.context.scene.render.resolution_y)

        # Clipping
        clip_start = config.get_float("clip_start", cam.clip_start)
        clip_end = config.get_float("clip_end", cam.clip_end)

        if config.has_param("cam_K"):
            if config.has_param("fov"):
                print(
                    'WARNING: FOV defined in config is ignored. Mutually exclusive with cam_K'
                )
            if config.has_param("pixel_aspect_x"):
                print(
                    'WARNING: pixel_aspect_x defined in config is ignored. Mutually exclusive with cam_K'
                )

            cam_K = np.array(config.get_list("cam_K")).reshape(3, 3).astype(
                np.float32)

            CameraUtility.set_intrinsics_from_K_matrix(cam_K, width, height,
                                                       clip_start, clip_end)
        else:
            # Set FOV
            fov = config.get_float("fov", cam.angle)

            # Set Pixel Aspect Ratio
            pixel_aspect_x = config.get_float(
                "pixel_aspect_x", bpy.context.scene.render.pixel_aspect_x)
            pixel_aspect_y = config.get_float(
                "pixel_aspect_y", bpy.context.scene.render.pixel_aspect_y)

            # Set camera shift
            shift_x = config.get_float("shift_x", cam.shift_x)
            shift_y = config.get_float("shift_y", cam.shift_y)

            CameraUtility.set_intrinsics_from_blender_params(fov,
                                                             width,
                                                             height,
                                                             clip_start,
                                                             clip_end,
                                                             pixel_aspect_x,
                                                             pixel_aspect_y,
                                                             shift_x,
                                                             shift_y,
                                                             lens_unit="FOV")

        CameraUtility.set_stereo_parameters(
            config.get_string("stereo_convergence_mode",
                              cam.stereo.convergence_mode),
            config.get_float("convergence_distance",
                             cam.stereo.convergence_distance),
            config.get_float("interocular_distance",
                             cam.stereo.interocular_distance))
        if config.has_param("depth_of_field"):
            depth_of_field_config = Config(
                config.get_raw_dict("depth_of_field"))
            fstop_value = depth_of_field_config.get_float("fstop", 2.4)
            aperture_blades = depth_of_field_config.get_int(
                "aperture_blades", 0)
            aperture_ratio = depth_of_field_config.get_float(
                "aperture_ratio", 1.0)
            aperture_rotation = depth_of_field_config.get_float(
                "aperture_rotation_in_rad", 0.0)
            if depth_of_field_config.has_param(
                    "depth_of_field_dist") and depth_of_field_config.has_param(
                        "focal_object"):
                raise RuntimeError(
                    "You can only use either depth_of_field_dist or a focal_object but not both!"
                )
            if depth_of_field_config.has_param("depth_of_field_dist"):
                depth_of_field_dist = depth_of_field_config.get_float(
                    "depth_of_field_dist")
                CameraUtility.add_depth_of_field(cam, None, fstop_value,
                                                 aperture_blades,
                                                 aperture_rotation,
                                                 aperture_ratio,
                                                 depth_of_field_dist)
            elif depth_of_field_config.has_param("focal_object"):
                focal_object = depth_of_field_config.get_list("focal_object")
                if len(focal_object) != 1:
                    raise RuntimeError(
                        f"There has to be exactly one focal object, use 'random_samples: 1' or change "
                        f"the selector. Found {len(focal_object)}.")
                CameraUtility.add_depth_of_field(cam, focal_object[0],
                                                 fstop_value, aperture_blades,
                                                 aperture_rotation,
                                                 aperture_ratio)
            else:
                raise RuntimeError(
                    "The depth_of_field dict must contain either a focal_object definition or "
                    "a depth_of_field_dist")
Ejemplo n.º 5
0
# load the objects into the scene
objs = BlendLoader.load(args.scene)

# Set some category ids for loaded objects
for j, obj in enumerate(objs):
    obj.set_cp("category_id", j + 1)

# define a light and set its location and energy level
light = Light()
light.set_type("POINT")
light.set_location([5, -5, 5])
light.set_energy(1000)

# define the camera intrinsics
CameraUtility.set_intrinsics_from_blender_params(1, 512, 512, lens_unit="FOV")

# read the camera positions file and convert into homogeneous camera-world transformation
with open(args.camera, "r") as f:
    for line in f.readlines():
        line = [float(x) for x in line.split()]
        position, euler_rotation = line[:3], line[3:6]
        matrix_world = MathUtility.build_transformation_mat(
            position, euler_rotation)
        CameraUtility.add_camera_pose(matrix_world)

# activate normal and distance rendering
RendererUtility.enable_normals_output()
RendererUtility.enable_distance_output()

# set the amount of samples, which should be used for the color rendering
Ejemplo n.º 6
0
                    default="examples/datasets/suncg_basic/output",
                    help="Path to where the final files, will be saved")
args = parser.parse_args()

Initializer.init()

# load the objects into the scene
label_mapping = LabelIdMapping.from_csv(
    Utility.resolve_path(
        os.path.join('resources', 'id_mappings', 'nyu_idset.csv')))
objs = SuncgLoader.load(args.house, label_mapping=label_mapping)

# define the camera intrinsics
CameraUtility.set_intrinsics_from_blender_params(1,
                                                 512,
                                                 512,
                                                 pixel_aspect_x=1.333333333,
                                                 lens_unit="FOV")

# read the camera positions file and convert into homogeneous camera-world transformation
with open(args.camera, "r") as f:
    for line in f.readlines():
        line = [float(x) for x in line.split()]
        position = MathUtility.change_coordinate_frame_of_point(
            line[:3], ["X", "-Z", "Y"])
        rotation = MathUtility.change_coordinate_frame_of_point(
            line[3:6], ["X", "-Z", "Y"])
        matrix_world = MathUtility.build_transformation_mat(
            position, CameraUtility.rotation_from_forward_vec(rotation))
        CameraUtility.add_camera_pose(matrix_world)