# numpy array center of mass

I'm wondering how does ndimage.measurements.center_of_mass calculate the center of mass values for a two dimensional numpy array.

For example let's say we have an array m:

m = numpy.array([[1,2,3,1],[4,4,4,1],[5,6,7,2]])


Then one would get the following for the coordinates of the center of mass (x, y):

x, y = ndimage.measurements.center_of_mass(m)

x = 1.325  and  y = 1.3


So, how are those values of x and y mathematically derived (actual derivation)?

When I follow the steps in the function definition center_of_mass, I don't get that result.

• Can you show us your attempts where you implement their method?
– WBM
Mar 4 at 13:52

If you go to the source page for this method you can find the function:

def center_of_mass(input, labels=None, index=None):
"""
Calculate the center of mass of the values of an array at labels.
Parameters
----------
input : ndarray
Data from which to calculate center-of-mass.
labels : ndarray, optional
Labels for objects in input, as generated by ndimage.label.
Only used with index.  Dimensions must be the same as input.
index : int or sequence of ints, optional
Labels for which to calculate centers-of-mass. If not specified,
all labels greater than zero are used.  Only used with labels.
Returns
-------
center_of_mass : tuple, or list of tuples
Coordinates of centers-of-mass.
"""
normalizer = sum(input, labels, index)
grids = numpy.ogrid[[slice(0, i) for i in input.shape]]

results = [sum(input * grids[dir].astype(float), labels, index) / normalizer
for dir in range(input.ndim)]

if numpy.isscalar(results):
return tuple(results)

return [tuple(v) for v in numpy.array(results).T]


Whereby sum is (sum - centre)^2 of the input labels

• I hadn't seen that they define a function "sum". The first element of grids or grids  is "0". Does that imply that in calculating "input * grids[dir]" the first element in the array has no effect in calculating the center of mass? Mar 4 at 20:35
• Not quite following. What do you mean grids[:2] = 0? Have you implemented sum yourself? Is this for your input data?
– WBM
Mar 4 at 20:59
• Let me know if you have any questions otherwise please accept the answer
– WBM
Mar 14 at 18:02