2
$\begingroup$

I would like to bake normals (and potentially other parameters later) of an object via python code.

I came up with the following code, but it fails on the last line saying that it cannot find a valid image to bake to (I use the standard blender scene with the default cube).

I suspect this is because the image I created is not linked with the UV Map generated from the cube_project function.

How do I associate it to the image ?

Or maybe I am taking a wrong approach?

import bpy
cube = bpy.data.objects["Cube"]
bpy.context.scene.objects.active = cube

bpy.ops.object.editmode_toggle()
bpy.ops.mesh.select_all(action='SELECT')
bpy.ops.uv.cube_project()
bpy.ops.object.editmode_toggle()

image = bpy.data.images.new(name="test", width=512, height=512)

bpy.ops.object.bake_image()
$\endgroup$
2
$\begingroup$

Every UV face needs to be set to the image datablock:

image = bpy.data.images.new(name="test", width=512, height=512)

for uv_face in cube.data.uv_textures.active.data:
    uv_face.image = image

bpy.ops.object.bake_image()

Note that a uv_texture can't be accessed in edit-mode.

In addition to the UV face assignment, every mesh face should get a material with an image texture assigned (same image as for UV faces) and the texture coordinates be set to UV. Otherwise the texture may not show correct in viewport, although it might be baked correctly (better test!).

Have a look at the Material Utils addons, it let's you transfer UV face image assignments to material texture assignments and vice versa.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.