Finding a material index from a material name?

I am muddling my way through a script. I am converting each pixel of a .jpg into a material and I am assigning the RGB values of the pixel as the material name. I have some code which ensures that the same material is not produced twice. So now what I need to do is for a given RGB value I want to know what the material index is so that I can assign it to a face. Anyone got a way of converting a material name back into the material index?

Sorry I am a total noob at python but I am slowly picking it up through experimentation.

Create a lookup-dict for the object materials:

mat_dict = {mat.name: i for i, mat in enumerate(ob.data.materials)}

then map names to indices:

print(mat_dict["Material"]) # 0

sweet. I will try that.

Many thanks.

OK, I am still struggling with my script. It is starting to drive me mad. I think that I must be so close to the answer but I just can’t see it.

Ok, here is the situation. My script generates materials for each pixel. It generates these as just materials, they are not assigned to any mesh (bpy.data.materials.new(color_name)). I am then using bmesh to generate faces (face1 = bm.faces.new( (vertex1, vertex2, vertex3, vertex4) )) and then what I am trying to do is assign the material to the face. I am now sure that I am assigning the right index but the material doesn’t get assigned to the face (face1.material_index = mat_num). I am assuming that the problem is because the materials are not assigned to the mesh, they are just floating materials. For the life of me I can’t find out how to assign the material to the mesh, if that even is the problem?

Once again sorry for the lack of python knowledge. I am sure that how I have just described that is just nonsense.

I can supply the .blend if it helps to explain the problem.

Well I finally got the script working. PHEW!


I’m sorry I know this is an old post, but the posted result is amazing! Could we see the script?