粗大メモ置き場

個人用,たまーに来訪者を意識する雑記メモ

Numpy Center of Mass,行列の重心点を求める

簡単なプログラムですがこれがなかなか見つからないので残しておきます。
重心点は中心からの距離を測っています。

中心点から見た重心

def CenterOfGravity(mat):
    hei,wid = mat.shape
    Tile=np.arange(wid,dtype=float)-(wid-1.0)/2.0
    Tx = np.tile(Tile,[hei,1]) # Ty = Tx.T
    Sum = np.sum(mat)
    Ax = np.sum(mat*Tx)/Sum
    Ay = np.sum(mat*Tx.T)/Sum
    return [Ay,Ax]

端からみた重心(0スタート)

def CenterOfGravity(mat):
    hei,wid = mat.shape
    Tile=np.arange(wid,dtype=float)
    Tx = np.tile(Tile,[hei,1]) # Ty = Tx.T
    Sum = np.sum(mat)
    Ax = np.sum(mat*Tx)/Sum
    Ay = np.sum(mat*Tx.T)/Sum
    return [Ay,Ax]

メモ

np.arrangeで0,1,2,,,みたいな行列を作成。
np.tileで並べる。

補足

コメントより。
2値の場合の重心なら以下のようによりシンプルに求めることができます。

def getCenter(binimg):
    ys, xs= np.where(binimg == 255)
    x = np.average(xs)
    y = np.average(ys)
    return [x, y]