I use Blender 2.83. For a addon (accessible from the 3D-View) I want to bake texture maps. I am perfectly able to do it without scripting. But with python I was not sucessful sofar.
To reduce my problem to the barest minumum I start with a selected object with valid UV. I then execute the following python script:
import bpy
obj = bpy.context.active_object
# Creating a texture node, linked with a new image
mat = obj.data.materials[0]
mat.use_nodes = True
texImage = mat.node_tree.nodes.new('ShaderNodeTexImage')
img = bpy.ops.image.new(name= obj.name + '_BakedTexture')
texImage = img
# !!! No image is linked to the texture node !!!
# Baking to the newly created image
# The following part works if I create the texture node and the assigning of the image by hand
bpy.context.view_layer.objects.active = obj
bpy.ops.object.bake(type='DIFFUSE', save_mode='EXTERNAL', filepath='C:\\TEMP\\baked.png', use_automatic_name=True, width=512, height=512)
I think what I am missing is the correct linking of the image to the texture node. I consulted similar questions such as
Set active image node with python
but their answers did not help (code for Blender 2.7 that is not compatible anymore, i guess).