【问题标题】:Distance transform with Manhattan distance - Python / NumPy / SciPy曼哈顿距离的距离变换 - Python / NumPy / SciPy
【发布时间】:2020-01-31 05:31:24
【问题描述】:

我想使用 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]
]

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

谢谢

【问题讨论】:

  • 你想到了什么?
  • 你试过什么?您可以从某个零点的索引位置开始,并使用索引值构建到所有其他点的距离。如果你能做到零,那就对所有的人都做,然后在每个位置取最小值......这将是一个建议的算法
  • 这里你会找到一个基于 BFS 的算法:google.com/amp/s/www.geeksforgeeks.org/…。它比蛮力快得多
  • @BNilsou 您的评论与 OP 无关!删除它。
  • 感谢@BNilsou 提供的链接。似乎相当快。谢谢大家的cmets。

标签: python numpy scipy distance


【解决方案1】:

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

【讨论】:

  • 非常感谢您提供的代码和信息,完美运行!
猜你喜欢
  • 1970-01-01
  • 2012-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-08
相关资源
最近更新 更多