对于没有for循环的等距元素的矩阵计算

use*_*592 5 python numpy matrix

我有2D numpy数组和一个坐标(i,j)(坐标意味着行和列)的中心.对于从0到图像边缘的每个可能距离,我需要将距离中心相同距离的所有数组元素(简单的euklidean距离)相加,即结果是1D数组,其中第0个元素给出距离中像素的总和0从中心(即仅中心),第一个元素是距离1像素的所有像素的总和,依此类推.

我的感觉是,这应该可以在没有for循环的情况下完成,但不幸的是我不知道足够的矩阵python技巧来解决这个问题.

非常感谢你!

seb*_*erg 2

您可以使用np.bincount...

a = np.random.random((20, 22))

def distance(array, xpos, ypos):
    # probably a gazillion methods to create the actual distances...
    # if you array is large and you are only interested to a certain size
    # you sould probably slice out a smaller one first of course.
    dists = np.sqrt(np.arange(-xpos, array.shape [0]-xpos, dtype=float)[:,None]**2
          + np.arange(-ypos, array.shape [1]-ypos, dtype=float)[None,:]**2)
    return dists

# Prepare which bins to use:
dists = distance(a, 10, 11).astype(int)

# Do a bincount with weights.
result = np.bincount(dists.flat, weights=a.flat)
# and add them up:
result = np.add.accumulate(result)
Run Code Online (Sandbox Code Playgroud)

Andresult是一个数组,result[distance]给出所有距离更小或相等的值的总和。