This is a pre-release version (2.0.0.dev0+git20260907.41eeb59).Go to latest (1.18.0)
{ } Raw JSON

bundles / scipy 2.0.0.dev0+git20260907.41eeb59 / scipy / ndimage / _measurements / center_of_mass

function

scipy.ndimage._measurements:center_of_mass

source: build-install/usr/lib/python3.14/site-packages/scipy/ndimage/_measurements.py:1485

Signature

def center_of_mass(input, labels = None, index = None)

Summary

Calculate the center of mass of the values of an array at labels.

Parameters

input : ndarray

Data from which to calculate center-of-mass. The masses can either be positive or negative.

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, the combined center of mass of all labels greater than zero will be calculated. Only used with labels.

Returns

center_of_mass : tuple, or list of tuples

Coordinates of centers-of-mass.

Examples

import numpy as np
a = np.array(([0,0,0,0],
              [0,1,1,0],
              [0,1,1,0],
              [0,1,1,0]))
from scipy import ndimage
✓
ndimage.center_of_mass(a)
✗
(np.float64(2.0), np.float64(1.5))
Calculation of multiple objects in an image
b = np.array(([0,1,1,0],
              [0,1,0,0],
              [0,0,0,0],
              [0,0,1,1],
              [0,0,1,1]))
lbl = ndimage.label(b)[0]
✓
ndimage.center_of_mass(b, lbl, [1,2])
✗
[(np.float64(0.3333333333333333), np.float64(1.3333333333333333)), (np.float64(3.5), np.float64(2.5))]
Negative masses are also accepted, which can occur for example when bias is removed from measured data due to random noise.
c = np.array(([-1,0,0,0],
              [0,-1,-1,0],
              [0,1,-1,0],
              [0,1,1,0]))
✓
ndimage.center_of_mass(c)
✗
(np.float64(-4.0), np.float64(1.0))
If there are division by zero issues, the function does not raise an error but rather issues a RuntimeWarning before returning inf and/or NaN.
d = np.array([-1, 1])
✓
ndimage.center_of_mass(d)
✗
(np.float64(inf),)

Aliases

  • scipy.ndimage.center_of_mass