瞄准质心 - scipy / numpy
targeting center of mass - scipy / numpy
鉴于以下情况:
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]])
鉴于以下情况:
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]])