距离阵列中心的数字平均距离



我有一个数组的中心点,

center_point = (array.shape[0]/2.,array.shape[1]/2.)

i具有二进制图像数组array,其形状将相关像素设置为0(所有其他像素为255)。


我需要所有设置为零的像素的平均距离阵列中心的平均距离,并且我需要将其进行矢量化(无法在Python级别解释 - 慢速)。

这是我所拥有的,现在我被卡住了,因为我发现的其他答案指向Scipy,但是服务器仅支持支持numpy。

centerpoint = array_center_point(shape_array)
distance_shape = np.zeros(size=shape_array.shape,dtype=float)
distance_shape[shape==0] = ...???
avg_distance = np.sum(distance_shape) / len(np.where(shape_array == 0)[0])

我不知道如何在不打电话给NP的情况下进行此操作,并用python进行循环的形状索引迭代。必须有一种方法可以在Numpy代码中完成此操作... ??


这是有效的非矢量化版本:

def avg_distance_from_center(shape_array):
    center_point = array_center_point(shape_array)
    distance_shape = np.zeros(shape=shape_array.shape, dtype=float)
    shape_pixels = np.where(shape_array == 0)
    total_distance = 0.
    for i in range(len(shape_pixels[0])):
        i_ind = float(shape_pixels[0][i])
        j_ind = float(shape_pixels[1][i])
        total_distance += ((i_ind - center_point[0])**2.0 + (j_ind - center_point[1])**2.0)**0.5
    avg_distance = total_distance / len(shape_pixels[0])
    return avg_distance

方法1: with NumPy broadcasting-

np.sqrt(((np.argwhere(shape_array==0) - center_point)**2).sum(1)).mean()

方法#2:使用np.einsum-

subs = (np.argwhere(a==0) - center_point)
out = np.sqrt(np.einsum('ij,ij->i',subs,subs)).mean()

仅用于插图我使用一个随机数组:

>>> import numpy as np
>>> arr = (np.random.random((5, 5)) > 0.5).astype(int)
>>> arr
array([[0, 0, 0, 1, 0],
       [0, 0, 1, 1, 1],
       [0, 1, 0, 0, 1],
       [1, 0, 0, 1, 0],
       [1, 0, 1, 0, 1]])
>>> center = (2, 2)  # use your center here

要获得距离,我将使用网格格里德:

>>> grid_x, grid_y = np.mgrid[0:arr.shape[0], 0:arr.shape[1]]
>>> grid_x
array([[0, 0, 0, 0, 0],
       [1, 1, 1, 1, 1],
       [2, 2, 2, 2, 2],
       [3, 3, 3, 3, 3],
       [4, 4, 4, 4, 4]])
>>> grid_y
array([[0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4]])

我们将网格转移到中心的坐标:

>>> grid_x = grid_x - center[0]
>>> grid_y = grid_y - center[1]

最后,我们使用np.hypot函数计算距离(几乎与np.sqrt(x**2 + y**2)相同),但仅使用arr == 0

的点
>>> distances = np.hypot(grid_x[arr == 0], grid_y[arr == 0])

现在是时候计算距离的平均/平均值:

>>> np.mean(distances)
2.767080465988093

最新更新