Distance transform with Manhattan distance - Python / NumPy / SciPy

帅比萌擦擦* 提交于 2020-03-20 07:59:50

问题


I would like to generate a 2d Array like this using Python and 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]
]

Pretty much the the numbers spread left and right starting from the zeros. This matrix allows to see the distance of any point to the closest zero. I thought this matrix was common, but I couldn't found anything on the web, even its name. If you have a code to efficiently generate such a matrix or know at least how it's called, please let me know.

Thank you


回答1:


Here's one with 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

In MATLAB, it's called Distance transform of binary image, hence a derivative name is given here.

Sample run -

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


来源:https://stackoverflow.com/questions/59998392/distance-transform-with-manhattan-distance-python-numpy-scipy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!