I have a textured high-poly mesh A, whose texture I'd like to transfer to its decimated version low-poly mesh B, which already has normalized UV textures (generated using OptCuts so they're nice and compact).
I tried to follow guides such as this one, getting to the following code, which sadly yields a completely black texture:
import bpy
bpy.context.scene.render.engine = 'CYCLES'
# remove default stuff
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete()
# load the mesh to bake from and the one to bake to
bpy.ops.import_scene.gltf(filepath="from_mesh.glb")
bpy.ops.import_scene.gltf(filepath="to_mesh.glb")
# select the two meshes (glb imports a whole scene)
bpy.ops.object.select_all(action='DESELECT')
from_obj, to_obj = [o for o in bpy.context.scene.objects if o.type == 'MESH']
bpy.data.objects[from_obj.name].select_set(True)
bpy.data.objects[to_obj.name].select_set(True)
# create a new image to bake to and assign it to the to_obj material
image_name = to_obj.name + '_BakedTexture'
img = bpy.data.images.new(image_name, 1024, 1024)
for mat in to_obj.data.materials:
mat.use_nodes = True
nodes = mat.node_tree.nodes
texture_node = nodes.new('ShaderNodeTexImage')
texture_node.name = 'Bake_node'
texture_node.select = True
nodes.active = texture_node
texture_node.image = img
# baking
bpy.context.view_layer.objects.active = to_obj
bpy.ops.object.bake('INVOKE_DEFAULT', type='DIFFUSE', pass_filter={'COLOR'}, save_mode='EXTERNAL', use_selected_to_active=True)
# texture export
img.save_render(filepath='texture.jpg')
This is the terminal output:
Data are loaded, start creating Blender stuff
glTF import finished in 0.37s
Data are loaded, start creating Blender stuff
glTF import finished in 0.03s
Fra:1 Mem:106.68M (Peak 137.83M) | Time:470417:15:57.15 | Mem:0.00M, Peak:0.00M | Scene | Synchronizing object | scene_dense_mesh.ply
Fra:1 Mem:122.94M (Peak 137.83M) | Time:470417:15:57.17 | Mem:0.00M, Peak:0.00M | Scene | Initializing
Fra:1 Mem:122.94M (Peak 137.83M) | Time:470417:15:57.17 | Mem:0.00M, Peak:0.00M | Scene | Updating Images | Loading finalResult_mesh_normalizedUV.obj_BakedTexture
Fra:1 Mem:122.94M (Peak 137.83M) | Time:470417:15:57.17 | Mem:0.00M, Peak:0.00M | Scene | Updating Images | Loading Image_0
Fra:1 Mem:122.94M (Peak 137.83M) | Time:470417:15:57.17 | Mem:0.00M, Peak:0.00M | Scene | Updating Images | Loading Image_0.001
Info: Baking map saved to internal image, save it externally or pack it
Intuitively, the code should be doing what I want, but I'm pretty new to Blender's Python API (and Blender in general) so I can't figure out why it's not. Any help / pointers are much appreciated!
Here are links to download from_mesh.glb
and to_mesh.glb
.
Edit: changing bake type to 'UV' seems to correctly bake the UV map from mesh A to mesh B, yielding the following: