scipy.ndimage.

center_of_mass#

scipy.ndimage.center_of_mass(input, labels=None, index=None)[原始碼]#

計算標籤陣列值的質心。

參數:
inputndarray

用於計算質心的資料。質量可以是正數或負數。

labelsndarray, optional

物件在 input 中的標籤,由 ndimage.label 產生。僅與 index 一起使用。維度必須與 input 相同。

indexint 或 int 序列, optional

要計算質心的標籤。如果未指定,將計算所有大於零的標籤的組合質心。僅與 labels 一起使用。

回傳值:
center_of_masstuple,或 tuple 列表

質心的座標。

範例

>>> 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)
(2.0, 1.5)

影像中多個物件的計算

>>> 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])
[(0.33333333333333331, 1.3333333333333333), (3.5, 2.5)]

也接受負質量,例如,當從測量資料中移除因隨機雜訊引起的偏差時,可能會發生負質量。

>>> c = np.array(([-1,0,0,0],
...               [0,-1,-1,0],
...               [0,1,-1,0],
...               [0,1,1,0]))
>>> ndimage.center_of_mass(c)
(-4.0, 1.0)

如果存在除以零的問題,此函數不會引發錯誤,而是在返回 inf 和/或 NaN 之前發出 RuntimeWarning。

>>> d = np.array([-1, 1])
>>> ndimage.center_of_mass(d)
(inf,)