python - 瞄准质心 - scipy/numpy

标签 python numpy image-processing scipy linear-algebra

鉴于以下情况:

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 ]
])

最佳答案

很简单:

  1. 求几何中心

    import numpy as np
    
    c1 = center_of_mass(np.ones_like(A))
    #or : c1 = [A.shape[0]/2.,A.shape[1]/2.]
    
  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/

相关文章:

image-processing - 24x24 窗口中类似 haar 的特征数

python - 读取文件时不转换换行符

python - Py2neo (V4) - CypherSyntaxError : Variable `$x` not defined

python - 使用 LinearNDInterpolator 进行外推

python - Python TypeError:需要一个整数(元组类型元组)-(OpenCV/Numpy)

python - 索引错误 : too many indices for array for numpy in Python

image-processing - 使用miniflann时发生OpenCV错误

python - Jupyter 中的 Numpy 函数文档

python - 删除多级索引的名称

matlab - 使用 detectorMSERFeatures 时出错