曼哈顿距离的距离变换-Python / NumPy / SciPy

时间:2020-01-31 05:31:24

标签: python numpy scipy distance

我想使用Python和Numpy生成一个2d数组:

[
  [0, 1, 2, 3, 4, 4, 3, 4],
  [1, 2, 3, 4, 4, 3, 2, 3],
  [2, 3, 4, 4, 3, 2, 1, 2],
  [3, 4, 4, 3, 2, 1, 0, 1],
  [4, 5, 5, 4, 3, 2, 1, 2]
]

几乎所有的数字从零开始向左和向右传播。该矩阵允许查看任何点到最接近零的距离。我以为这个矩阵很普通,但是我在网上找不到任何东西,甚至连名字都没有。如果您有代码可以有效地生成此类矩阵,或者至少知道其调用方式,请告诉我。

谢谢

1 个答案:

答案 0 :(得分:5)

这里是Scipy cdist-

from scipy.spatial.distance import cdist

def bwdist_manhattan(a, seedval=1):
    seed_mask = a==seedval
    z = np.argwhere(seed_mask)
    nz = np.argwhere(~seed_mask)

    out = np.zeros(a.shape, dtype=int)
    out[tuple(nz.T)] = cdist(z, nz, 'cityblock').min(0).astype(int)
    return out

在MATLAB中,它称为Distance transform of binary image,因此在此处给出了派生名称。

样品运行-

In [60]: a # input binary image with 1s at "seed" positions
Out[60]: 
array([[1, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 1, 0],
       [0, 0, 0, 0, 0, 0, 0, 0]])

In [61]: bwdist_manhattan(a)
Out[61]: 
array([[0, 1, 2, 3, 4, 4, 3, 4],
       [1, 2, 3, 4, 4, 3, 2, 3],
       [2, 3, 4, 4, 3, 2, 1, 2],
       [3, 4, 4, 3, 2, 1, 0, 1],
       [4, 5, 5, 4, 3, 2, 1, 2]])
相关问题