Computing the centroid of a Vertex Group?

I’m not sure if I am asking the right question here, but I would like to find out if there is a straightforward means to compute a centroid of all the members of a vertex Group based upon their weights? I would like to use this centroid to place a set of ‘collision spheres’ at their approximately correct bone locations in the case where I do not have the original armature. Does anybody know? Thank you.

Can’t you just do a weighted average of each vertex position based on the total weight of the group and the weight for the individual vertex?

That’s what I was planning to do, yes. Just need to figure out how to loop through the list of weights and vertices within each group. It’s probably not hard; I was just hoping there was an already existing code call I could use.

Here’s a possible solution, but I worry it’s not giving the desired results:

import bpy
from mathutils import Vector
from collections import defaultdict
from functools import reduce

ob = bpy.context.object
me = ob.data
scene = bpy.context.scene

vgroups = {i: vgroup.name for i, vgroup in enumerate(ob.vertex_groups)}
vec_list = defaultdict(list)

for v in me.vertices:
    for group in v.groups:
        print("Group", group.group)
        vec_list[group.group].append(v.co * group.weight)

centroids = {vgroups[i]: reduce(Vector.__add__, l) / len(l) for i, l in vec_list.items()}

for vgroup_name, centroid in centroids.items():
    print("%s = %s" % (vgroup_name, centroid))
    
vgroup_active = ob.vertex_groups.active
if centroids and vgroup_active is not None:
    scene.cursor_location = ob.matrix_world * centroids[vgroup_active.name]

If there’s one vertex with 1.0 weight, and all others have 0.0, shouldn’t the centroid be exactly at that vertex with 1.0 weight?

Yes, that’s correct. But there would be a problem if all of the weights are zero, so I’ll have to check for that case.

Thank you.

Maybe I need to divide by number of vertices instead of number of vertices in groups? I’m not sure…

I didn’t consider the case of all Vectors being 0, but funnily there’s no ZeroDivisionError if all weights are zero? My formula might be way off, oh well…