2
$\begingroup$

I have a Cycles material node group like this:

enter image description here

I can access the user-specified color (red) like this:

bpy.data.objects["Suzanne"].data.materials[0].node_tree.nodes.get("MyNodeGroup").inputs[0].default_value[:]

which gives...

(1.0, 0.0, 0.0, 1.0)

I can also hook an image-texture node into that node group like this:

enter image description here

However, bpy.data.objects["Suzanne"].data.materials[0].node_tree.nodes.get("MyNodeGroup").inputs[0].default_value[:] still gives (1.0, 0.0, 0.0, 1.0).

How can I access the image node? I'd like to get the associated filename and/or image. Thanks!

$\endgroup$
0

2 Answers 2

1
$\begingroup$

A node tree has nodes and links.

Links has 4 attributes that tell the relation between nodes:

  • from_node, from_socket: which correspond to the "upstream" in the relation
  • to_node, to_socket: which is the "downstream" in the relation

So for instance:

import bpy

obj = bpy.context.object

mat = obj.material_slots['Material'].material #Get the material from the material slot you want

if mat and mat.use_nodes: #if it is using nodes

    dif = mat.node_tree.nodes['Diffuse BSDF'] #Or your group's name

    socket = dif.inputs[0] #It's first input socket

    try:
        #Get the link that input to 'dif' and 'socket'
        link = next( link for link in mat.node_tree.links if link.to_node == dif and link.to_socket == socket )

        imageNode = link.from_node #The node this link is coming from

        if imageNode.type == 'TEX_IMAGE': #Check if it is an image texture node

            image = imageNode.image #Get the image

            print( "result", image.name, image.filepath )

    except:
        print( "no link" )
$\endgroup$
2
$\begingroup$

This is done with searching the node links for one that connects into the node input. The image node is on the other end of that link:

import bpy

mat = bpy.data.objects["Suzanne"].data.materials[0]

# get node input (socket)
socket = mat.node_tree.nodes.get("MyNodeGroup").inputs[0]

# get node link that connects into the socket
link = next(link for link in mat.node_tree.links if link.to_socket == socket)
# get the other node of that link
node = link.from_node

# get the image from node
image = node.image
$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .