How to load and assign a texture to an object in Blender with a Python Script?

Hello everyone, I am a student and I am new to Blender and its API for Python.

I have created an object to which I must assign a texture, I have made a script for this and if the texture is loaded but not assigned to the object. It is worth mentioning that I applied a displacement modifier to the object and that modifier is to which I want to add the texture but as I said it is not assigned.

Can someone help me tell me what I am doing wrong, or what I need to do so that the texture is assigned?

The script I carry out is the following:

#Añadir heightmap
bpy.ops.object.modifier_add(type = ‘DISPLACE’)
tex = bpy.data.textures.new(name = “Tex_Altura”, type = “IMAGE”)
img = bpy.data.images.load("/home/orlando/Documentos/ProyectosBlender/TextureforSTL/heighmap.png") tex.image = img
bpy.context.object.modifiers[“Displace”].strength = 0.100 bpy.context.object.modifiers[‘Displace’].mid_level = 0

bpy.data.textures[“Tex_Altura”].extension = ‘EXTEND’

someone help me please.

import bpy

ob = bpy.context.active_object

tex = bpy.data.textures.new(name="Tex_Altura", type="IMAGE")
img = bpy.data.images.load("/home/orlando/Documentos/ProyectosBlender/TextureforSTL/heighmap.png")
tex.image = img
tex.extension = 'EXTEND'

mod = ob.modifiers.new("", 'DISPLACE')
mod.strength = 0.1
mod.mid_level = 0
mod.texture = tex

I replaced the operator call to create the displacement modifier as I believe it’s best to avoid calling operators within your scripts whenever possible, especially within loops, as Blender I believe has to perform a complete update each time an operator is called. Also doing it the way I have means you get a reference returned to the newly created modifier.

3 Likes

Thank you very much @Walker … It was just what I needed, now my model runs correctly and the texture is also assigned without problems. I really appreciate your help friend.