1
$\begingroup$

In my scene I have an object that's using 4 different materials. Each material has it's own image node that looks like this:

Image Node

How would I go about selecting a material by name and changing MyImage.png to a string I can input in python? I'm currently using this code to load the scene and render it.

def renderImage():
   bpy.ops.wm.open_mainfile(filepath="../scenes/bodyshot.blend")
   scene = bpy.context.scene        
   obj_camera = bpy.context.scene.camera 
   scene.render.image_settings.file_format = 'PNG'
   scene.render.filepath = "renderOutput.png"
   bpy.ops.render.render(write_still = 1)

renderImage()

Edit: Solved thanks to lemon. The code I used to render the image:

mat = bpy.data.materials.get("shirt")
node = mat.node_tree.nodes["shirtImageNode"]
image = bpy.data.images.load("myShirtImage.png")
node.image = image
$\endgroup$
0
2
$\begingroup$

To get a material by its name:

mat = bpy.data.materials[ mat_name ]

To get a node in it by its name:

node = mat.node_tree.nodes[ node_name ]

To get all the image texture nodes in a material:

nodes = [n for n in mat.node_tree.nodes if n.type == 'TEX_IMAGE']

For the image part, I presume it is loaded and exist in Blender.

If yes, to get it from its name:

image = bpy.data.images[ image_name ]

If no, you can load it:

bpy.data.images.load( filepath )

Setting an image in a image texture node:

image_node.image = image

where 'image_node' is one of the nodes obtained as 'TEX_IMAGE' above.

and where 'image' is the object obtained from bpy.data.images

$\endgroup$
5
  • $\begingroup$ I'm getting the error KeyError: 'bpy_prop_collection[key]: key "shirt" not found' $\endgroup$ – Steven Newhouse Aug 27 '19 at 17:32
  • $\begingroup$ Either use .get(key) to test it or try except. But if you have this error, that means the key does not exist in your collection (I dont' know which one you're talking about) $\endgroup$ – lemon Aug 27 '19 at 17:34
  • $\begingroup$ I have tried using .get and it's gone through to the next line where I get the error AttributeError: 'NoneType' object has no attribute 'node_tree' $\endgroup$ – Steven Newhouse Aug 27 '19 at 17:37
  • $\begingroup$ Man, that means you're try to get something that is not existing in your context. $\endgroup$ – lemon Aug 27 '19 at 17:38
  • $\begingroup$ I've updated my question with the code. $\endgroup$ – Steven Newhouse Aug 27 '19 at 17:38

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.