# How can I copy vertex groups from one mesh to another in Python?

I have an two mesh objects parented to the same parent, and I'd like to copy all the vertex groups from one object to the other (like using Transfer Weights with the Source being the "By Name"). This code fails with an "not correct context" or something (so I've got something wrongly selected):

ob = bpy.data.objects['New Mesh']
object = bpy.data.objects['CC_Base_Body']
for group in object.vertex_groups:
bpy.ops.object.vertex_group_set_active(group=str(group.name))
vg = ob.vertex_groups.new(group.name)


Okay, I found some more information (and code) and it most likely will help a lot, but it does not do all the Transfer Mesh Data rollout does, which is to create the data by vertex mapping to the nearest vertex. Indeed, it immediately bails if the vertex counts aren't the same (which won't do at all). Here's the post with the code: https://stackoverflow.com/questions/40969164/how-to-add-vertex-groups-from-one-object-to-another-without-replacing-them

So, now I'm at the point of trying to figure out, from that code, how I can do that Vertex mapping to the nearest vertex, as the Transfer Mesh Data rollout allows (I will be on safe ground for the rest. as there are no vertex groups in the second mesh, so in creating them they will be brand new and empty).

Writing to vertex groups is fairly straightforward. The API is documented at https://docs.blender.org/api/2.79/bpy.types.VertexGroup.html#bpy.types.VertexGroup

vg.remove( vertex_index_list )


removes vertices from the group (which is different than having a zero weight). To set a weight for a vertex:

vg.add( vertex_index_list, weight, operation )


Usually you're using operation = 'REPLACE'.

Getting values from a vertex group is a little stickier. The vg.weight(idx) call will throw an exception if idx is not in the group. Checking if a vertex belongs to a vertex group in python has a couple of techniques for working around that (wrap it in a try block, or access the vertex group through the v.groups field on the vertex).

What remains is how you decide what weight to assign to each vertex on the destination and the relationship between the vertices in the two meshes.

One technique that might be useful is choosing the closest vertex. The brute force way would be to calculate ( src.data.vertices[i].co - dst_vert.co).length for all the source vertices and use the one with the minimum value (which should give you the closest vertex to the dst_vert).

• I'll give this a shot - I was sure hoping there would be some way to access the source code for this but apparently it's one of the things NOT written in Python in Blender. Sigh. – Mike Kelley Mar 15 '18 at 18:35