Sub topic 14
Inspecting and assigning weights with Python
Earlier chapters worked in the viewport. Here you do the same jobs from a script: bind a mesh, create vertex groups, set weights, read them back, and enforce influence limits. Scripts are useful for checking many characters, repeating a setup, and finding problems that are hard to see in Weight Paint mode.
Prerequisites
This chapter assumes you have:
- Read the earlier chapters on vertex groups, the Armature modifier, automatic weights, normalization and Limit Total.
- Run a script from Blender's Text Editor (Scripting workspace, then Run Script).
- Basic Python: loops, lists, and dictionaries.
The examples assume a mesh object named Body and an armature object named Armature. Change these names to match your scene.
The data model
Weights are stored in two places that you need to keep apart.
- The object holds the list of vertex groups:
obj.vertex_groups. Each group has a name and an index. - The mesh holds the weights:
obj.data.vertices[i].groups. Each entry is aVertexGroupElementwith agroup(the index into the object's group list) and aweight.
A vertex only lists the groups it belongs to. A vertex with no entry for a group is not the same as a vertex with weight 0.0 in that group. The entry exists in the second case, and it does not exist in the first.
The Armature modifier connects the pieces. For each bone with Deform enabled, it looks for a vertex group with the same name and uses that group's weights to decide how far the bone moves each vertex.
Binding with automatic weights
The script below does what Ctrl+P, With Automatic Weights does. The order of selection matters. The mesh is selected, and the armature is the active object.
import bpy
# Select the mesh first, then make the armature the active object.
mesh_obj = bpy.data.objects["Body"]
arm_obj = bpy.data.objects["Armature"]
bpy.ops.object.select_all(action='DESELECT')
mesh_obj.select_set(True)
arm_obj.select_set(True)
bpy.context.view_layer.objects.active = arm_obj
# Equivalent to Ctrl+P > With Automatic Weights
bpy.ops.object.parent_set(type='ARMATURE_AUTO')This is an operator, so it depends on context. It must run in Object Mode, and both objects must be visible and selectable. If the operator reports that it cannot run, check the mode and the selection first.
Automatic weights can fail when the mesh has loose parts, overlapping geometry, or an unapplied scale. The chapter on troubleshooting covers these causes. A common symptom is that the bind runs but every vertex gets zero weight.
Building the setup by hand
Parenting with an armature does two things. It adds an Armature modifier, and it creates vertex groups. You can do the modifier part yourself:
import bpy
mesh_obj = bpy.data.objects["Body"]
arm_obj = bpy.data.objects["Armature"]
# Manual setup: the modifier deforms the mesh using vertex groups named after bones.
mod = mesh_obj.modifiers.new(name="Armature", type='ARMATURE')
mod.object = arm_objThis gives you a modifier but no weights. Until the mesh has vertex groups with bone names, nothing deforms. Also note that this does not set mesh_obj.parent. The modifier works without parenting, but most pipelines expect the mesh to be parented to the armature so the two move together in Object Mode.
Creating a group and assigning weights
VertexGroup.add() takes a list of vertex indices, a weight, and a mode. This script creates a group named Bone and gives every vertex a weight of 1.0:
import bpy
obj = bpy.context.active_object
# The group name must match the bone name for the Armature modifier to use it.
vg = obj.vertex_groups.new(name="Bone")
# Give every vertex a weight of 1.0 in this group.
vg.add([v.index for v in obj.data.vertices], 1.0, 'REPLACE')The third argument controls what happens when a vertex already has a weight in the group.
| Mode | Effect on an existing weight |
|---|---|
| `'REPLACE'` | Sets the weight to the given value. |
| `'ADD'` | Adds the given value to the current weight (the result is capped at 1.0). |
| `'SUBTRACT'` | Subtracts the given value from the current weight (the result is floored at 0.0). |
Weights are limited to the range 0.0 to 1.0. For a vertex that is not yet in the group, 'REPLACE' and 'ADD' both create the entry, and 'SUBTRACT' does nothing useful.
To take vertices out of a group completely, use vg.remove(indices). Removing a vertex deletes the entry. This is different from setting the weight to 0.0, which keeps the entry.
Setting different weights per vertex
add() applies one weight to all indices in the call. To give vertices different weights, call it once per weight value or once per vertex. For a smooth gradient along the Z axis, this is straightforward:
import bpy
obj = bpy.context.active_object
vg = obj.vertex_groups.get("Bone") or obj.vertex_groups.new(name="Bone")
zs = [v.co.z for v in obj.data.vertices]
lo, hi = min(zs), max(zs)
span = (hi - lo) or 1.0
for v in obj.data.vertices:
w = (v.co.z - lo) / span
vg.add([v.index], w, 'REPLACE')This uses local coordinates (v.co). If the object is rotated, local Z and world Z differ, so decide which you want.
Reading weights back
To verify a bind, loop over each vertex and read its group entries:
import bpy
obj = bpy.context.active_object
# Print each vertex's non-zero group weights.
for v in obj.data.vertices:
for g in v.groups:
name = obj.vertex_groups[g.group].name
print(v.index, name, round(g.weight, 3))For large meshes, the printout is long. Instead, collect statistics. This script reports vertices with no weights at all and vertices whose weights do not sum to 1.0:
import bpy
obj = bpy.context.active_object
unweighted = []
not_normalized = []
for v in obj.data.vertices:
total = sum(g.weight for g in v.groups)
if total == 0.0:
unweighted.append(v.index)
elif abs(total - 1.0) > 0.001:
not_normalized.append(v.index)
print("Unweighted vertices:", len(unweighted))
print("Not normalized:", len(not_normalized))An unweighted vertex stays at its rest position while its neighbors move. This is the cause of the "stuck" vertices you may see in a pose. Weights that do not sum to 1.0 are not always an error, because the Armature modifier does not require normalized weights. Unnormalized weights can still produce stretched or shrunken geometry, so reporting them is useful.
Checking names against bones
The most common reason a group does nothing is a name mismatch. Blender compares names exactly, including case and any .L or .R suffix. This script lists every group that has no working bone:
import bpy
mesh_obj = bpy.data.objects["Body"]
arm_obj = bpy.data.objects["Armature"]
bones = arm_obj.data.bones
for vg in mesh_obj.vertex_groups:
bone = bones.get(vg.name)
if bone is None:
print("No bone named:", vg.name)
elif not bone.use_deform:
print("Deform is off for:", vg.name)Use arm_obj.data.bones here, not arm_obj.pose.bones. The use_deform property is on the bone data. Run this before you start debugging in the viewport.
Limiting influences and normalizing
Many game engines allow only four bone influences per vertex. Two operators handle this: first cut the extra influences, then normalize so the remaining weights sum to 1.
import bpy
# Run with the mesh as the active object (Object Mode or Weight Paint mode).
# Keep at most 4 bone influences per vertex, then make weights sum to 1.
bpy.ops.object.vertex_group_limit_total(group_select_mode='ALL', limit=4)
bpy.ops.object.vertex_group_normalize_all(group_select_mode='ALL', lock_active=False)Do the limit first. Removing influences changes the total, so normalizing before the limit would leave the sums wrong. group_select_mode='ALL' includes every group. Use 'BONE_DEFORM' to include only groups that match deform bones, which avoids touching helper groups such as masks.
Common errors
RuntimeError: Error: Vertex not in group. You calledvg.weight(index)for a vertex with no entry. Catch the error, or loop overv.groupsas shown above.- Nothing deforms after a script bind. Check the group names against the bones, check that Deform is enabled, and confirm that the modifier's object is set.
- Weights change but the viewport looks the same. Switch modes or call
obj.data.update()to refresh the display. - Index confusion.
g.groupis an index intoobj.vertex_groups, not a vertex index. Deleting a group renumbers the groups after it.
Exercise
A script creates a group named "upperarm.L" and assigns weights, but the arm does not move in Pose Mode. The armature has a bone called "upperarm.L". Name two things you would check with Python, and the property you would read for each.
Show answer
First, whether the bone allows deformation: read arm_obj.data.bones["upper_arm.L"].use_deform and confirm it is True. Second, whether the mesh has an Armature modifier pointing at the armature: check mesh_obj.modifiers for a modifier of type 'ARMATURE' and read its object property. You could also confirm that the vertices actually have weights by reading v.groups and that the group name matches the bone name exactly, including case.