Sub topic 12
Automating the Workflow with Python
This chapter turns the manual steps from earlier chapters into a script you can rerun on any mesh. It assumes you can already do the workflow by hand: mark seams, unwrap, check a test grid, pack islands, and connect an Image Texture node to the Principled BSDF. It also assumes you can run a script from the Scripting workspace's Text Editor and read basic Python (functions, loops, imports). The code targets the Blender 3.x and 4.x Python API (bpy).
Two layers of the API: data and operators
Blender's Python API offers two ways to change a scene.
| Layer | Example | Depends on context | Typical use |
|---|---|---|---|
| Data API (`bpy.data`, `obj.data`, `bmesh`) | `mesh.uv_layers.new()`, `edge.seam = True` | No | Reading and writing stored values |
| Operators (`bpy.ops`) | `bpy.ops.uv.unwrap()` | Yes: mode, selection, active object | Running the same commands the menus run |
Unwrapping and packing are algorithms, and Blender exposes them only as operators. So the script uses the data API to create UV maps, mark seams, and build materials. It uses operators only for unwrap and pack_islands. Because operators read the current context, the script must first put Blender into the state the operator expects. That means the right active object, Edit Mode, and the right elements selected.
UV data lives on face corners
A UV pair belongs to a face corner (a loop), not to a vertex. A vertex shared by four faces can have four different UV positions. This is why seams work: a seam lets the same vertex have different UV positions on each side of the cut.
import bpy
obj = bpy.context.active_object
uv_layer = obj.data.uv_layers.active
# Print the UV coordinate of the first few face corners (loops).
for i, loop_uv in enumerate(uv_layer.data[:6]):
print(i, tuple(loop_uv.uv))uv_layer.data has one entry per loop, so its length equals len(obj.data.loops). It does not equal the vertex count. If uv_layers.active is None, the mesh has no UV map yet. Primitive meshes added from the Add menu have one, but meshes created from raw data with from_pydata do not.
The script below ensures a map exists before doing anything else:
if not mesh.uv_layers:
mesh.uv_layers.new(name="UVMap")Marking seams from a script
The seam flag is stored on edges, and bmesh is the clean way to change it while the mesh is in Edit Mode. Changes made through bmesh.from_edit_mesh apply to the live edit mesh, so call bmesh.update_edit_mesh afterwards to refresh the display.
import bpy
import bmesh
obj = bpy.context.active_object
bpy.ops.object.mode_set(mode='EDIT')
bm = bmesh.from_edit_mesh(obj.data)
for edge in bm.edges:
if edge.select:
edge.seam = True
bmesh.update_edit_mesh(obj.data)
bpy.ops.object.mode_set(mode='OBJECT')This marks whatever edges you selected by hand, which is often the right split. A script can also choose edges by rule, for example every edge whose two faces meet at a sharp angle. Use edge.calc_face_angle(None), which returns None for boundary edges. The two-line rule angle is not None and angle > radians(60) is a reasonable start for hard-surface models. Organic shapes usually need seams chosen by a person.
Unwrapping and packing with operators
Here is the unwrap step from the spine, which honors seams already on the mesh:
import bpy
obj = bpy.context.active_object
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='SELECT')
bpy.ops.uv.unwrap(method='ANGLE_BASED', margin=0.001)
bpy.ops.object.mode_set(mode='OBJECT')Three details decide whether this works:
- Mode.
bpy.ops.uv.unwrapruns only in Edit Mode. In Object Mode it raisesRuntimeError: Operator bpy.ops.uv.unwrap.poll() failed, context is incorrect. - Selection. The operator unwraps only selected faces. If nothing is selected, it finishes without an error and changes nothing, which is easy to miss.
- Method.
'ANGLE_BASED'is the default and works well for most meshes.'CONFORMAL'preserves local angles and can handle some shapes differently. Compare them on a test grid, as in the distortion chapter.
Packing is a separate operator. It works on the selected UVs, not the selected faces. Depending on your version and the UV Sync Selection setting, select the UVs explicitly before packing:
bpy.ops.uv.select_all(action='SELECT')
bpy.ops.uv.pack_islands(margin=0.01)Choose the margin as a fraction of the image. A margin of 0.01 on a 1024 pixel image leaves about 10 pixels between islands. That is enough for typical mipmapped use, and a larger margin avoids color bleeding between islands. If your textures will be viewed at a distance, increase it.
The alternative bpy.ops.uv.smart_project(angle_limit=radians(66), island_margin=0.01) ignores your seams. It cuts the mesh by angle and packs it in one step. That is fast for quick previews, but the islands are fragmented. Use unwrap when you have placed seams on purpose.
Building the material from data
Creating the material needs no operators, so it works in any mode. Use bpy.path.abspath to resolve paths that start with //. This matters because // means "next to the .blend file", and an unsaved file has no location. Then images.load fails or loads from the wrong place.
The example below looks up the Principled BSDF by node type, not by name. Node names can differ between Blender language settings and versions.
import bpy
obj = bpy.context.active_object
mat = bpy.data.materials.new("TexturedMaterial")
mat.use_nodes = True
nodes = mat.node_tree.nodes
links = mat.node_tree.links
bsdf = next(n for n in nodes if n.type == 'BSDF_PRINCIPLED')
tex = nodes.new("ShaderNodeTexImage")
tex.image = bpy.data.images.load("//textures/brick_color.png")
tex.image.colorspace_settings.name = "sRGB"
links.new(tex.outputs["Color"], bsdf.inputs["Base Color"])
obj.data.materials.append(mat)The spine's version loads the path directly. That is fine once the file is saved and the image exists. If the image file is missing, images.load raises a RuntimeError that contains Cannot read. Adding check_existing=True to images.load reuses an image that is already in the file instead of creating a second copy named brick_color.png.001.
Color space and the node settings
Set the color space on the image datablock, not on the node. Use "sRGB" for color images such as albedo. Use "Non-Color" for data images such as roughness, metallic, and normal maps. If you set the wrong space, the render looks wrong but raises no error, so make it an explicit line in every helper you write.
The Image Texture node itself carries the mapping options from the settings chapter:
tex.interpolation = 'Linear' # 'Closest' for pixel art
tex.extension = 'REPEAT' # 'EXTEND' or 'CLIP' also exist
tex.projection = 'FLAT'The node reads the mesh's active UV map by default, because its Vector input is unconnected. To use a different map, add a ShaderNodeUVMap node, set its uv_map to the map's name, and link its UV output to tex.inputs["Vector"].
> Note: In recent Blender releases the use_nodes property is deprecated, because materials always use nodes. Setting it is harmless, and it keeps the script working on older versions.
Creating a test grid in code
A generated grid helps you inspect the unwrap before you commit to a real image:
import bpy
img = bpy.data.images.new("UVTestGrid", width=1024, height=1024)
img.generated_type = 'UV_GRID'You can assign it to a node with tex.image = img. Look for squares that stay square and lines of even spacing. Stretched squares mean distortion, and squares of different sizes on different islands mean uneven texel density.
Saving or packing the image
The image file management chapter covered the two options. Both can be scripted:
img = bpy.data.images["UVTestGrid"]
# Option A: store the pixels inside the .blend file.
img.pack()
# Option B: write a file next to the .blend file.
img.filepath_raw = "//textures/uv_test_grid.png"
img.file_format = 'PNG'
img.save()Packing makes the .blend larger but self-contained. Saving to disk keeps the file small, and the image path must remain valid when you move the project. Call bpy.ops.file.make_paths_relative() to convert absolute paths before sharing a project folder.
A complete script
This version combines the steps into one function with checks. It runs on the active mesh object. It marks no seams, because a script cannot decide where your seams belong, so mark them first or add the bmesh loop above.
import bpy
def unwrap_and_texture(obj, image_path, margin=0.01):
if obj is None or obj.type != 'MESH':
raise ValueError("Select a mesh object first.")
mesh = obj.data
if not mesh.uv_layers:
mesh.uv_layers.new(name="UVMap")
# Operators need the object to be active and selected.
bpy.context.view_layer.objects.active = obj
obj.select_set(True)
bpy.ops.object.mode_set(mode='EDIT')
try:
bpy.ops.mesh.select_all(action='SELECT')
bpy.ops.uv.unwrap(method='ANGLE_BASED', margin=margin)
bpy.ops.uv.select_all(action='SELECT')
bpy.ops.uv.pack_islands(margin=margin)
finally:
bpy.ops.object.mode_set(mode='OBJECT')
mat = bpy.data.materials.new(obj.name + "_Material")
mat.use_nodes = True
nodes = mat.node_tree.nodes
links = mat.node_tree.links
bsdf = next(n for n in nodes if n.type == 'BSDF_PRINCIPLED')
tex = nodes.new("ShaderNodeTexImage")
tex.image = bpy.data.images.load(
bpy.path.abspath(image_path), check_existing=True
)
tex.image.colorspace_settings.name = "sRGB"
tex.image.pack()
links.new(tex.outputs["Color"], bsdf.inputs["Base Color"])
mesh.materials.append(mat)
return mat
unwrap_and_texture(bpy.context.active_object, "//textures/brick_color.png")The try/finally block returns the object to Object Mode even if an operator fails. Without it, a failure leaves Blender in Edit Mode, and the next run of the script fails differently.
Common errors
context is incorrect. The operator's mode or area requirements are not met. Check the mode and the active object first.- Nothing happens, no error. Nothing was selected, or the UVs were not selected when packing.
- Texture shows pink or black. The image path is wrong or the file was not found. Open the Image Texture node and check the image datablock.
- Washed-out or too dark result. The color space is wrong for the image type.
- Duplicate
.001images and materials. The script was run repeatedly. Usecheck_existing=Trueand look up materials by name before creating new ones.
Exercise
A script calls bpy.ops.uv.unwrap(method='ANGLE_BASED') while the object is in Object Mode. What happens, and what two steps must the script perform before the call so that the whole mesh is unwrapped?
Show answer
The call raises a RuntimeError saying the operator's poll failed because the context is incorrect, since unwrap runs only in Edit Mode. The script must first switch to Edit Mode with bpy.ops.object.modeset(mode='EDIT') and then select all faces with bpy.ops.mesh.selectall(action='SELECT'). Without the selection, the call would run but leave the mesh unchanged.
Exercise
Why does the complete script look up the Principled BSDF with n.type == 'BSDF_PRINCIPLED' instead of nodes["Principled BSDF"], and which color space would you set on a roughness map?
Show answer
The type string stays the same across language settings and versions, while the node name may change, so the type lookup is more reliable. A roughness map holds data and not color, so you set its color space to "Non-Color".