曼哈顿距离的距离变换-Python/NumPy/SciPy [英] Distance transform with Manhattan distance - Python / NumPy / SciPy
问题描述
我想使用Python和Numpy生成一个2d数组:
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.
谢谢
推荐答案
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
在MATLAB中,它称为 Distance transform of binary image
,因此是派生的名字在这里给出.
In MATLAB, it's called Distance transform of binary image
, hence a derivative name is given here.
样品运行-
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]])
这篇关于曼哈顿距离的距离变换-Python/NumPy/SciPy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!