There's any way to change it directly by Python, or there's any way to set by Python what node image is the active to display in viewport (Textured) and bake?
4 Answers
So far as I know, when baking with Cycles, the only way to bake to a texture is to create a texture and click on that node to make it the Active texture. Whatever Texture Node is active is the one which will be baked to. I reported something similar as a bug when Cycles Baking was still new and Brecht wrote back saying
The image texture assignment workflow in Cycles is very different from Blender Internal, that's by design and has been working this way for years. Images are assigned to materials, and the image shown in the image editor is not automatically linked to the UV layer or object you select, that's separate. http://wiki.blender.org/index.php/Doc:2.6/Manual/Render/Cycles/Texture_Editing
We can argue if this is good or bad, but can't consider it a bug.
Here's an example node setup snippet,
I hope this helps even though it's not a Python related answer.
Here is an example that creates a Texture Image Node for the material Material
with Python:
import bpy
node_tree = bpy.data.materials['Material'].node_tree
node = node_tree.nodes.new("ShaderNodeTexImage")
node.select = True
node_tree.nodes.active = node
The new node is selected and made the active node of the node tree.
To expand on CoDEmanX's answer you may also want to create an image for the new node
newimg = bpy.data.images.new('targetImg',1024,1024)
node.image = newimg
And if you want to activate an existing image node for the active object -
matnodes = bpy.context.active_object.material_slots[0].material.node_tree.nodes
imgnodes = [n for n in matnodes if n.type == 'TEX_IMAGE']
for n in imgnodes:
if n.image.name == 'targetImg':
n.select = True
matnodes.active = n
-
$\begingroup$ It seems that this method does not work for activating Viewer nodes. Although I feel I am literally doing what you've said here, but things don't work. Could you take a look at my question here and let me know if you think I am doing something wrong? It would be great if you can offer a solution. $\endgroup$– AmirCommented Mar 10, 2018 at 9:21
It seems like that as of v2.79 we have to define the Material to use nodes:
mater = bpy.data.materials['Material']
mater.use_nodes = True
node_tree = mater.node_tree
and continue with the suggestions above.