鉴于以下情况:
from scipy.ndimage import center_of_mass
from numpy import array
A = array([
[ 255, 255, 0, 0 ]
[ 255, 255, 0, 0 ],
[ 0 , 0, 0, 0 ],
[ 0 , 0, 0, 0 ]
])
cm = center_of_mass(A)
# cm = (0.5, 0.5)
centered = ???
cmc = center_of_mass(centered)
# cmc ~= (1.5,1.5)
我们如何移动这个 ndarray/图像,使其基于其质心居中?
我们的目标结果如下:
centered = array([
[ 0, 0, 0, 0 ],
[ 0, 255, 255, 0 ],
[ 0, 255, 255, 0 ],
[ 0, 0, 0, 0 ]
])
最佳答案
很简单:
求几何中心
import numpy as np c1 = center_of_mass(np.ones_like(A)) #or : c1 = [A.shape[0]/2.,A.shape[1]/2.]
按差值平移矩阵
S = np.roll(A, c1[0]-cm[0] , axis=0) S = np.roll(S, c1[0]-cm[0] , axis=1)
答案是:
Out[18]:
array([[ 0, 0, 0, 0],
[ 0, 255, 255, 0],
[ 0, 255, 255, 0],
[ 0, 0, 0, 0]])
关于python - 瞄准质心 - scipy/numpy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46842154/