栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

用python脚本实现UE4相机截图渲染(代码)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

用python脚本实现UE4相机截图渲染(代码)

     1. 在插件启用Movie Render Queue和Moive Render Queue Additional Render Passes,项目设置中允许支持Alpha通道。

 

     2.将模型SM_1放到场景原点(0,0,0)、 添加关卡序列 、添加camera cut track、新建相机(设置相机感应器宽高比为1:1,感应器宽度和高度设为13mm,焦距可以调物体远近,根据公式计算,光圈影响景深模糊程度,默认为20,调整模型SM_1在画面中的位置)。

     (1)焦距计算参考一下:

     (2)设置color grading:

      (3)代码如下:

 def create_sequence(self, sequence_name, package_path , asset_path_sm1):
        print("[sequence camera]: load asset")

        # 加载sm_1到视图并且位置设位置为(0,0,0) 
        asset_sm = unreal.load_asset(asset_path_sm1)
        print("asset_path_sm1: " + str(asset_path_sm1))
        actor_location = unreal.Vector(0.0, 0.0, 0.0)
        actor_rotation = unreal.Rotator(0.0, 0.0, 0.0)
        actor = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.StaticMeshActor,actor_location,actor_rotation)
        actor_smc = actor.get_editor_property("static_mesh_component")
        actor_smc.set_static_mesh(asset_sm)

        # create a sequence
        print("[sequence camera]: create a sequence")
        sequence = unreal.AssetToolsHelpers.get_asset_tools().create_asset(sequence_name,package_path,unreal.LevelSequence,unreal.LevelSequenceFactoryNew())
        sequence.set_display_rate(unreal.FrameRate(numerator=60, denominator=1))
        # sequence.set_playback_start(1)
        # sequence.set_playback_end(2)
        sequence.set_playback_start_seconds(0.016)
        sequence.set_playback_end_seconds(0.03)
        
        # add a camera cut track
        print("[sequence camera]: add a camera cut track")
        camera_cut_track = sequence.add_master_track(unreal.MovieSceneCameraCutTrack)
        camera_cut_section = camera_cut_track.add_section()
        camera_cut_section.set_start_frame_bounded(0)
        camera_cut_section.set_end_frame_bounded(10)
        camera_cut_section.set_start_frame_seconds(0)
        camera_cut_section.set_end_frame_seconds(0.5)

        # 计算相机的位置 并且 创造一个cine camera actor
        box = asset_sm.get_bounding_box()
        asset_x = (box.get_editor_property("max").x - box.get_editor_property("min").x)/2
        camera_x = -(500+abs(asset_x)) 
        camera_y = (box.get_editor_property("min").y + box.get_editor_property("max").y)/2
        print("box_y :" + str(camera_y))
        camera_z = (box.get_editor_property("min").z + box.get_editor_property("max").z)/2
        print("box_z :" + str(camera_z))
        print("[sequence camera]: Create a cine camera actor")
        camera_actor = unreal.EditorLevelLibrary().spawn_actor_from_class(unreal.CineCameraActor, unreal.Vector(camera_x,camera_y,camera_z), unreal.Rotator(0,0,0))
        camera_component = camera_actor.get_cine_camera_component()

        # 焦距
        camera_y_focal = box.get_editor_property("max").y - box.get_editor_property("min").y
        camera_z_focal = box.get_editor_property("max").z - box.get_editor_property("min").z
        camera_focal = max(camera_y_focal,camera_z_focal)
        ratio = 9/camera_focal
        focal_length = ratio*abs(camera_x)
        print("camera_y_focal :" + str(camera_y_focal))
        focus_settings = camera_component.get_editor_property("focus_settings")
        focus_settings.set_editor_property("focus_method", unreal.CameraFocusMethod.DISABLE)

        # 感应器长宽
        filmback = camera_component.get_editor_property("filmback")
        camera_component.set_editor_property("current_focal_length" , focal_length)
        camera_component.set_editor_property("current_aperture" , 22)
        filmback.set_editor_property("sensor_height", 13)
        filmback.set_editor_property("sensor_width", 13)

        # 设置color grading
        color_grading = camera_component.post_process_settings
        color_grading.set_editor_property("override_color_gain",True)
        color_grading.set_editor_property("override_color_gamma",True)
        color_grading.set_editor_property("override_color_contrast",True)
        color_grading.set_editor_property("override_color_saturation",True)
        color_grading.set_editor_property("color_saturation",(0.3,0.3,0.3,0.3))
        color_grading.set_editor_property("color_contrast",(0.3,0.3,0.3,0.3))
        color_grading.set_editor_property("color_gamma",(0.3,0.3,0.3,0.3))
        color_grading.set_editor_property("color_gain",(0.3,0.3,0.3,0.3))

        # add a binding for the camera
        print("[sequence camera]: add a binding for the camera")
        camera_binding = sequence.add_possessable(camera_actor)
        camera_binding_id = sequence.make_binding_id(camera_binding, unreal.MovieSceneObjectBindingSpace.LOCAL)
        camera_cut_section.set_camera_binding_id(camera_binding_id)

        # save sequence asset
        unreal.EditorAssetLibrary.save_loaded_asset(sequence, False)      

      3. 渲染的一些操作与设置:

     (1)打开影片渲染列队,选择添加当前关卡序列。

     (2)打开设置,accumulator includes alpha勾上 。

     (3)设置输出尺寸1024×1024、图片名称用文件名称命名:

     (4)添加png格式、渲染至本地:

     (5)代码如下:

def RenderQueue_InPlace(self , sm1_picture_name):
    
        print("[sequence camera]: render sequence to movie")
        subsystem = unreal.get_editor_subsystem(unreal.MoviePipelineQueueSubsystem)
        pipelineQueue = subsystem.get_queue()

        # pipelineQueue = unreal.new_object(unreal.MoviePipelineQueue)
        job_num = len(pipelineQueue.get_jobs())
        print("[sequence camera]: job_num: "+ str(job_num))
        job_arr = pipelineQueue.get_jobs()
        print("[sequence camera]: job_arr: "+ str(job_arr))
        # 
        while(job_num != 0):
            pipelineQueue.delete_job(job_arr[job_num-1])
            job_num = job_num - 1

        newJob = pipelineQueue.allocate_new_job(unreal.MoviePipelineExecutorJob)
        newJob.sequence = unreal.SoftObjectPath(sequence_asset_path)
        newJob.map = unreal.SoftObjectPath(map_path)
        newJob.job_name = str("My_Sequence")

        unreal.log("Validating job " + str(newJob))
        print("[sequence camera]: set a job")
        outputSetting = newJob.get_configuration().find_or_add_setting_by_class(unreal.MoviePipelineOutputSetting)
        outputSetting.output_resolution = unreal.IntPoint(1024,1024)
        outputSetting.file_name_format = sm1_picture_name 
        outputSetting.output_directory = unreal.DirectoryPath(Capture_path)
        # alpha:
        renderPass = newJob.get_configuration().find_or_add_setting_by_class(unreal.MoviePipelineDeferredPassBase)
        renderPass.accumulator_includes_alpha = True

        newJob.get_configuration().find_or_add_setting_by_class(unreal.MoviePipelineImageSequenceOutput_PNG)
        newJob.get_configuration().initialize_transient_settings()

        # 
        global NewExecutor
        NewExecutor = subsystem.render_queue_with_executor(unreal.MoviePipelinePIEExecutor)
        NewExecutor.on_executor_finished_delegate.add_callable_unique(OnQueueFinishedCallback)
        NewExecutor.on_individual_job_finished_delegate.add_callable_unique(OnIndividualJobFinishedCallback)

       4.其他一些所需代码:

# check asset is exist
    def check_sequence_asset_exist(self):
        print("[sequence camera]: check sequence asset exist")
        root_dir = unreal.SystemLibrary.get_project_directory()
        sequence_path = os.path.join(root_dir, 'Content', 'D5_Level_Sequence.uasset')
        if(os.path.exists(sequence_path)):
            unreal.log('---sequence is exist os path---')
            os.remove(sequence_path)
        else:
            unreal.log('---sequence is not exist os path---')
        if unreal.EditorAssetLibrary.does_asset_exist(sequence_asset_path):
            unreal.log('---sequence dose asset exist---')
            unreal.EditorAssetLibrary.delete_asset(sequence_asset_path)
        else:
            unreal.log('---sequence does not asset exist---')
        sequence_asset_data = unreal.AssetRegistryHelpers.get_asset_registry().get_asset_by_object_path(sequence_asset_path)
        if sequence_asset_data:
            unreal.log('---sequence is exist on content---')
            sequence_asset = unreal.AssetData.get_asset(sequence_asset_data)
            unreal.EditorAssetLibrary.delete_loaded_asset(sequence_asset)
        else:
            unreal.log('---sequence is not exit on content---')

def OnQueueFinishedCallback(executor, success):
    unreal.log("Render completed. Success: " + str(success))
    #
    global NewExecutor
    global NewQueue
    # del NewExecutor
    # del NewQueue
    global C_Manager
    C_Manager.run_next()


def OnIndividualJobFinishedCallback(inJob, success):
    unreal.log("Individual job completed. Changing light color.")

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/938072.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号