python - 曼哈顿距离的距离变换 - 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]
]
几乎数字从零开始左右分布。该矩阵允许查看任何点到最近零的距离。我认为这个矩阵很常见,但我在网上找不到任何东西,甚至它的名字。如果您有代码可以有效地生成这样的矩阵,或者至少知道它是如何调用的,请告诉我。
谢谢
解决方案
这是一个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]])
推荐阅读
- windows - 在 Windows Server 2016 上卸载 WebDav 后,它会在一天后恢复活力
- javascript - 视频时长有时为 NaN
- kotlin - 如何在 kotlin 中验证 json
- javascript - 如何在 d3.js 中的旭日形图中心写入文本
- c - 如何在 C 中逐个字符地“刷新”退格?
- javascript - 如何仅使用 2 个 if 语句检查 3 种可能性
- opencv - OpenCV expm() 函数
- java - 如何使时钟在固定位置递增?
- java - 如何在 apache poi 中使用韩语文档从文档文件中打印 pdf 文件。我尝试使用 pdfOptions.fontEncoding("UTF-8")
- react-native - 如何使用 Agora Io 和 react native 实现通话录音。可能吗?