To get the mesh vertex weights as they are distributed among its vertex groups with the Blender Python API, we need to correlate the vertex group indices with the group indices of the current vertex.
First, we need to loop through all the vertex groups of the mesh:
1 |
for group in bpy.context.object.vertex_groups: |
The index of the current group can be obtained through the “index” property
1 |
group_index = group.index |
Define the list of vertices that are included in the vertex group with the current index:
1 2 |
vert_in_group = [vert for vert in bpy.context.object.data.vertices \ if group_index in [i.group for i in vert.groups]] |
Here, for each vertex of the current active object, we check whether the index of the current vertex group is included in the list of groups of this vertex.
As a result, we got lists of vertices for each vertex group:
1 2 3 4 5 6 |
# Group, group index: 0 # [bpy.data.meshes['Suzanne'].vertices[3], bpy.data.meshes['Suzanne'].vertices[9],... # Group.001. group index: 1 # [bpy.data.meshes['Suzanne'].vertices[2], bpy.data.meshes['Suzanne'].vertices[8],... # Group.002, group index: 2 # [bpy.data.meshes['Suzanne'].vertices[51], bpy.data.meshes['Suzanne'].vertices[60],... |
One vertex can belong to several groups.
We can see which groups the vertex belongs to as follows:
1 2 3 4 5 6 7 8 9 10 |
vg = [[group.group for group in vert.groups] for vert in vert_in_group] print(vg) # Group , group index: 0 # [[0], [0], [0], [0], [0, 2], [0], ... # Group.001 , group index: 1 # [[1], [1], [1], [1], [1], [1], [1] ... # Group.002 , group index: 2 # [[0, 2], [1, 2], [0, 2], [0, 1, 2], [0, 1, 2], [2]... |
To compare the vertex group indices with the index of each group of the vertex, we need to take the location of the desired vertex group index in vertex list of groups and get weights from this group:
1 2 3 |
gr = [v.groups[[g.group for g in v.groups].index(group_index)].weight for v in vert_in_group] print(gr) |
As a result, we get a list of vertex weights according to the mesh’s vertex groups:
1 2 3 4 5 6 |
# Group , group index: 0 # [1.0, 0.9997303485870361, 0.9992071390151978, 1.0, 1.0, 1.0, 1.0, ... # Group.001 , group index: 1 # [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, # Group.002 , group index: 2 # [1.0, 0.09085874259471893, 0.7725147604942322, 1.0, ... |