bpy渲染,保存mp4 相机姿态

这段代码演示了如何在Blender中设置渲染帧数,从1到100,删除场景中的特定对象(如灯光和相机),导入OBJ格式的3D模型,调整模型的位置和旋转,在不同帧上设置不同的旋转角度,然后配置渲染设置,包括分辨率、帧率、视频格式和编码器,最后将渲染输出保存为MP4视频文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

相机姿态 x y z 

设置渲染帧数:

bpy渲染,保存mp4 ,blender 4支持

bpy渲染,保存mp4 ,blender 4报错


相机姿态 x y z 实例

物体obj:x为正,物体位置在右;y为正,物体位置在上;z为负数,物体原理。

import glob
import random

import bpy
from mathutils import Vector
import os

backdrop_dir = r'C:\Users\Administrator\Desktop\tmp\out_0108'

files = glob.glob(os.path.join(backdrop_dir, '*.png'))

for img_path in files:
    bpy.ops.image.open(filepath=img_path)

bpy.context.view_layer.objects.active = bpy.context.selected_objects[0]
bpy.ops.object.delete()

def create_fangxiang_light():
    light_data = bpy.data.lights.new(name='Direct_Light', type='POINT')

    # 将光源对象转换为方向光类型
    light_data.type = 'SUN'
    light_data.energy = 2
    # 将方向光源添加到场景中
    light_object = bpy.data.objects.new(name='My Directional Light', object_data=light_data)
    bpy.context.scene.collection.objects.link(light_object)

    # 设置方向光源的方向
    light_object.rotation_euler = Vector((0, 0, 0))
    light_object.rotation_euler.rotate_axis('X', 1.5708)  # 90度弧度值
    return light_object


def create_point_light(location=(0, 0, 0), power=1000, radius=1, color=(1, 1, 1)):
    # 创建一个新的点光源数据
    light_data = bpy.data.lights.new(name="PointLight", type="POINT")

    # 设置光源亮度、颜色和半径
    light_data.energy = power
    light_data.color = color
    light_data.shadow_soft_size = radius

    # 创建一个新的光源对象并链接到场景
    light_object = bpy.data.objects.new("PointLight", light_data)
    bpy.context.collection.objects.link(light_object)

    # 设置光源位置
    light_object.location = location
    light_object.rotation_euler.y = 1.5708
    return light_object


light = bpy.data.lights[0]
# 删除默认光源对象
bpy.data.lights.remove(light)

# light_object=create_point_light(location=(3,0,0), power=200, radius=0.001, color=(1, 1, 1))
bpy.context.scene.view_layers[0].use_motion_blur = True
# bpy.context.scene.view_layers[0].motion_blur_shutter = 0.5

bpy.context.scene.render.use_motion_blur = True
bpy.context.scene.render.motion_blur_shutter = 0.5

# Set render settings
bpy.context.scene.render.image_settings.file_format = 'JPEG'

bpy.context.scene.render.film_transparent = True
# 启用节点模式
bpy.context.scene.use_nodes = True
tree = bpy.context.scene.node_tree

# 清除现有节点
for node in tree.nodes:
    tree.nodes.remove(node)

image_node = tree.nodes.new("CompositorNodeImage")
# image_node.image = bpy.data.images.load(r'F:\3d\Python-3D-Rasterizer-main\pyrender-main\src\imgs\backdrop\Ori_18_0.mp4_1_down.jpg')
image_node.image = bpy.data.images.load(r"C:\Users\Administrator\AppData\Local\Programs\Microsoft VS Code\out_0108\frame_0015_multiHMR_896_L.png")
# obj = bpy.context.selected_objects[0]


# 创建一个 Alpha Over 节点以将背景图片和渲染结果混合
alpha_over_node = tree.nodes.new("CompositorNodeAlphaOver")
tree.links.new(image_node.outputs[0], alpha_over_node.inputs[1])

render_layers_node = tree.nodes.new("CompositorNodeRLayers")
tree.links.new(render_layers_node.outputs["Image"], alpha_over_node.inputs[2])

# 创建输出节点
output_node = tree.nodes.new("CompositorNodeComposite")
tree.links.new(alpha_over_node.outputs["Image"], output_node.inputs["Image"])

obj_filepath = r"F:\project\qijun\yolov5_55681_dao\xuanran\3dmodel\logo3d.obj"
obj_filepath = r"D:\GZ\soft\yolov5_wx_55681\xuanran\3dmodel\mesh.obj"
bpy.ops.wm.obj_import(filepath=obj_filepath)


obj20_name = os.path.splitext(os.path.basename(obj_filepath))[0]
obj20_name = 'logo_Mesh'
obj_0 = bpy.data.objects[1]

camera = bpy.data.objects['Camera']

camera.location = (0, 0, 10)
camera.rotation_euler = (0, 0, 0)

bpy.context.view_layer.objects.active = obj_0
# 计算场景中心点
center = (sum((v.co for v in bpy.context.view_layer.objects.active.data.vertices), Vector()) / len(bpy.context.view_layer.objects.active.data.vertices))

direction = center - camera.location
rot_quat = direction.to_track_quat('-Z', 'Y')
camera.rotation_mode = 'QUATERNION'
camera.rotation_quaternion = rot_quat

light_object = create_fangxiang_light()

light_object.location = Vector((5, 0, 0))
# 创建遮罩节点
blue_mask_shader = bpy.data.materials.new("BlueMask")
blue_mask_shader.use_nodes = True
nodes = blue_mask_shader.node_tree.nodes
nodes.clear()

output_node = nodes.new(type="ShaderNodeOutputMaterial")
# principled_node = nodes.new(type="ShaderNodeBsdfPrincipled")
emission_node = nodes.new(type="ShaderNodeEmission")
emission_node.inputs["Color"].default_value = (0, 0, 1, 1)  # 纯蓝色
# principled_node.inputs["Base Color"].default_value = (0, 0, 1, 1)  # 纯蓝色
blue_mask_shader.node_tree.links.new(emission_node.outputs["Emission"], output_node.inputs["Surface"])

red_mask_shader = bpy.data.materials.new("BlueMask")
red_mask_shader.use_nodes = True
nodes = red_mask_shader.node_tree.nodes
nodes.clear()

output_node = nodes.new(type="ShaderNodeOutputMaterial")
# principled_node = nodes.new(type="ShaderNodeBsdfPrincipled")
emission_node = nodes.new(type="ShaderNodeEmission")
emission_node.inputs["Color"].default_value = (1, 0, 0, 1)  # 纯蓝色
# principled_node.inputs["Base Color"].default_value = (0, 0, 1, 1)  # 纯蓝色
red_mask_shader.node_tree.links.new(emission_node.outputs["Emission"], output_node.inputs["Surface"])
# output_node = nodes.new(type="ShaderNodeOutputMaterial")
# principled_node = nodes.new(type="ShaderNodeBsdfPrincipled")
#

# 获取所有物体
objects = [obj for obj in bpy.context.scene.objects if obj.type == "MESH"]

original_materials = {}
for obj_tmp in objects:
    original_material = obj_tmp.data.materials[0]
    original_materials[obj_tmp.name] = original_material

obj_0.scale = (7, 7, 7)

move_x_step = -0.2
move_v_step = 0.2
move_y_step = 0.2

loc_x = -10
loc_y = 0
loc_z = -40

angle_x = 0
angle_y = 0
angle_z = 0

back_default = bpy.context.scene.world.node_tree.nodes["Background"].inputs[0].default_value
print(back_default[0], back_default[2], back_default[2], back_default[3])
img_count = 200
for frame_index in range(0, img_count):
    for light in bpy.data.lights:
        if frame_index % 21 == 0:
            light.energy = 10
        else:
            light.energy -= 0.2  # light.color = (0,0,0)
    img_key = os.path.basename(files[frame_index // (img_count // len(files))])
    image_node.image = bpy.data.images[img_key]
    obj_0.rotation_euler = (angle_x, angle_y, angle_z)
    angle_index = frame_index % 180 * 3
    if 0:
        if angle_index % 180 * 3 < 180:
            angle_x += 1.5 / 30
        elif angle_index % 180 * 3 < 180 * 2:
            angle_y += 1.5 / 30
        else:
            angle_z += 0.1

        if frame_index % 5 == 1:
            if abs(loc_x) > 3.5:
                move_x_step *= -1
            if abs(loc_y) > 2.2:
                move_y_step *= -1
            loc_x += move_x_step
            loc_y += move_y_step
        # loc_z = -random.random() * 4
    obj_0.location = (loc_x, loc_y, loc_z)
    # obj_hand.location = (loc_x + 0.7, loc_y - 0.8, loc_z + 1.5)
    obj_0.data.materials[0] = blue_mask_shader
    # obj_hand.data.materials[0] = red_mask_shader
    bpy.context.scene.render.film_transparent = False
    set_alpha_node = tree.nodes.new("CompositorNodeSetAlpha")
    tree.links.new(render_layers_node.outputs["Image"], set_alpha_node.inputs["Image"])
    set_alpha_node.inputs["Alpha"].default_value = 0

    for obj in objects:
        obj.data.materials[0] = original_materials[obj.name]

    bpy.context.scene.render.film_transparent = True
    # 恢复原始材质
    obj_0.data.materials[0] = original_materials[obj_0.name]

    # 渲染并保存带背景图片的正常渲染
    render_output_path = os.path.join(r'E:\project\3d\blender\res', f"image_{frame_index}.jpg")
    bpy.context.scene.render.filepath = render_output_path
    bpy.context.scene.world.node_tree.nodes["Background"].inputs[0].default_value = (0.05, 0.05, 0.05, 0.5)
    bpy.ops.render.render(write_still=True)

设置渲染帧数:

bpy.context.scene.frame_start = 1
bpy.context.scene.frame_end = 100

bpy渲染,保存mp4 ,blender 4支持

import bpy

for obj in bpy.context.scene.objects:
    if obj.name in ['Light', 'Camera']:
        continue
    print('del', obj.name)
    bpy.context.view_layer.objects.active = obj
    bpy.ops.object.delete()

video_path = r"C:\Users\Administrator\Videos\遮挡\person_big_0108.mp4"

if 0:
    # 遍历所有屏幕中的区域
    for area in bpy.context.screen.areas:
        if area.type == 'SEQUENCE_EDITOR':
            bpy.context.area = area
            break
    else:
        # 如果没有找到 'SEQUENCE_EDITOR' 类型的区域,默认使用第一个区域
        bpy.context.area = bpy.context.screen.areas[0]

    # 现在设置类型为 'SEQUENCE_EDITOR'
    bpy.context.area.type = 'SEQUENCE_EDITOR'

    # 添加视频剪辑
    bpy.ops.sequencer.movie_strip_add(filepath=video_path, frame_start=1)

    # 切换回3D视图
    bpy.context.area.type = 'VIEW_3D'
# 导入 OBJ 文件

bpy.ops.wm.obj_import(filepath=r"F:\project\qijun\yolov5_55681_dao\xuanran\3dmodel\logo3d.obj")
# bpy.ops.import_scene.obj(filepath=r"F:\project\qijun\yolov5_55681_dao\xuanran\3dmodel\logo3d.obj")

# 获取导入的对象
# obj = bpy.data.objects[0]
obj = bpy.context.selected_objects[0]

# 在时间轴的第 0 帧设置起始位置和旋转角度
obj.location = (0, 0, 0)
obj.rotation_euler = (0, 0, 0)

# 在时间轴的第 60 帧设置旋转角度
bpy.context.scene.frame_set(60)
obj.rotation_euler = (0, 0, 2 * 3.14)

# 在时间轴的第 120 帧设置旋转角度
bpy.context.scene.frame_set(120)
obj.rotation_euler = (0, 0, 4 * 3.14)

bpy.context.scene.render.resolution_x = 1920
bpy.context.scene.render.resolution_y = 1080
bpy.context.scene.render.fps = 30
bpy.context.scene.render.image_settings.file_format = 'FFMPEG'
bpy.context.scene.render.ffmpeg.format = 'MPEG4'
bpy.context.scene.render.ffmpeg.codec = 'H264'

# 设置输出路径和文件名
bpy.context.scene.render.filepath = r'E:\project\3d\blender\output.mp4'

bpy.context.scene.frame_start = 1
bpy.context.scene.frame_end = 10

# 开始渲染并保存视频
bpy.ops.render.render(animation=True)

bpy.ops.screen.animation_cancel(restore_frame=False)

bpy渲染,保存mp4 ,blender 4报错

import bpy

for obj in bpy.context.scene.objects:
    if obj.name in ['Light','Camera']:
        continue
    print('del',obj.name)
    bpy.context.view_layer.objects.active = obj
    bpy.ops.object.delete()

# 导入 OBJ 文件
bpy.ops.import_scene.obj(filepath=r"B:\project\3d\pygame-show-obj-master\resource\mk.obj")

# 获取导入的对象
# obj = bpy.data.objects[0]
obj = bpy.context.selected_objects[0]

# 在时间轴的第 0 帧设置起始位置和旋转角度
obj.location = (0, 0, 0)
obj.rotation_euler = (0, 0, 0)

# 在时间轴的第 60 帧设置旋转角度
bpy.context.scene.frame_set(60)
obj.rotation_euler = (0, 0, 2 * 3.14)

# 在时间轴的第 120 帧设置旋转角度
bpy.context.scene.frame_set(120)
obj.rotation_euler = (0, 0, 4 * 3.14)


bpy.context.scene.render.resolution_x = 1920
bpy.context.scene.render.resolution_y = 1080
bpy.context.scene.render.fps = 30
bpy.context.scene.render.image_settings.file_format = 'FFMPEG'
bpy.context.scene.render.ffmpeg.format = 'MPEG4'
bpy.context.scene.render.ffmpeg.codec = 'H264'

# 设置输出路径和文件名
bpy.context.scene.render.filepath = r'B:\project\3d\pygame-show-obj-master/output.mp4'


bpy.context.scene.frame_start = 1
bpy.context.scene.frame_end = 100

# 开始渲染并保存视频
bpy.ops.render.render(animation=True)

# 渲染完成后停止渲染
bpy.ops.render.cancel_render()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI算法网奇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值