I am trying to bake the Mix Shader Texture and output it as an image. Here is the original object
I use this code.
import bpy
bpy.data.scenes[0].render.engine = "CYCLES"
# Set the device_type
bpy.context.preferences.addons[
"cycles"
].preferences.compute_device_type = "CUDA" # or "OPENCL"
# Set the device and feature set
bpy.context.scene.cycles.device = "GPU"
# get_devices() to let Blender detects GPU device
bpy.context.preferences.addons["cycles"].preferences.get_devices()
print(bpy.context.preferences.addons["cycles"].preferences.compute_device_type)
for d in bpy.context.preferences.addons["cycles"].preferences.devices:
d["use"] = 1 # Using all devices, include GPU and CPU
print(d["name"], d["use"])
obj = bpy.context.active_object
image_name = obj.name + '_BakedTexture'
img = bpy.data.images.new(image_name,512,512)
for mat in obj.data.materials:
mat.use_nodes = True #Here it is assumed that the materials have been created with nodes, otherwise it would not be possible to assign a node for the Bake, so this step is a bit useless
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 #Assign the image to the node
bpy.context.view_layer.objects.active = obj
bpy.ops.object.bake(type='DIFFUSE', save_mode='EXTERNAL')
img.save_render(filepath='C:\\TEMP\\baked.png')
for mat in obj.data.materials:
for n in mat.node_tree.nodes:
if n.name == 'Bake_node':
mat.node_tree.nodes.remove(n)
However, the output is pretty strange:
Can someone pls tell me what is going on? Why it looks so dark?
Thanks!
Link to the project: https://drive.google.com/file/d/13J2Us042Ic0nXyFtDXT0anJgBzJy9xnA/view?usp=sharing