0
$\begingroup$

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.

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

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[0]):
        return tuple(results)

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

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

$\endgroup$
3
  • $\begingroup$ I hadn't seen that they define a function "sum". The first element of grids[0] or grids [1] 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? $\endgroup$ Mar 4 at 20:35
  • $\begingroup$ Not quite following. What do you mean grids[:2] = 0? Have you implemented sum yourself? Is this for your input data? $\endgroup$
    – WBM
    Mar 4 at 20:59
  • $\begingroup$ Let me know if you have any questions otherwise please accept the answer $\endgroup$
    – WBM
    Mar 14 at 18:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.