首页 > 解决方案 > 曼哈顿距离的距离变换 - Python / NumPy / SciPy

问题描述

我想使用 Python 和 Numpy 生成这样的二维数组:

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

几乎数字从零开始左右分布。该矩阵允许查看任何点到最近零的距离。我认为这个矩阵很常见,但我在网上找不到任何东西,甚至它的名字。如果您有代码可以有效地生成这样的矩阵,或者至少知道它是如何调用的,请告诉我。

谢谢

标签: pythonnumpyscipydistance

解决方案


这是一个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]])

推荐阅读