gpt4 book ai didi

Python:二进制掩码中从索引到1的距离

转载 作者:行者123 更新时间:2023-12-03 20:26:27 27 4
gpt4 key购买 nike

我有一个这样的二进制掩码:

X = [[0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 1, 1],
[0, 0, 0, 1, 1, 1],
[0, 0, 1, 1, 1, 1],
[0, 0, 1, 1, 1, 1],
[0, 0, 0, 1, 1, 1]]

我在这个数组中有一个特定的索引,想计算从该索引到最近的 1 的距离在面具中。如果已经有 1在该索引处,距离应为零。
示例(假设曼哈顿距离):
distance(X, idx=(0, 5)) == 0 # already is a 1 -> distance is zero
distance(X, idx=(1, 2)) == 2 # second row, third column
distance(X, idx=(0, 0)) == 5 # upper left corner

Python/NumPy/SciPy 中是否已经存在这样的功能?欧几里得距离和曼哈顿距离都可以。
我宁愿避免计算整个矩阵的距离(因为这在我的情况下非常大),而只获取我的一个索引的距离。

最佳答案

您可以使用 scipy.ndimage.morphology.distance_transform_cdt 计算“出租车”(曼哈顿)距离变换:

import numpy as np
import scipy.ndimage.morphology

x = np.array([[0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 1, 1],
[0, 0, 0, 1, 1, 1],
[0, 0, 1, 1, 1, 1],
[0, 0, 1, 1, 1, 1],
[0, 0, 0, 1, 1, 1]])
d = scipy.ndimage.morphology.distance_transform_cdt(1 - x, 'taxicab')
print(d[0, 5])
# 0
print(d[1, 2])
# 2
print(d[0, 0])
# 5

关于Python:二进制掩码中从索引到1的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60338266/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com