如何根据给定值计算空间距离矩阵

时间:2018-10-09 11:30:19

标签: python numpy scipy distance scipy-spatial

我一直在寻找一种从目标值和输入矩阵(有效地)计算距离矩阵的方法。

如果您将输入数组视为:

[0 0 1 2 5 2 1]  
[0 0 2 3 5 2 1]  
[0 1 1 2 5 4 1]  
[1 1 1 2 5 4 0]

您如何计算与目标值0相关的空间距离矩阵?

即每个像素到最接近的0值的距离是多少?

预先感谢

1 个答案:

答案 0 :(得分:1)

您正在寻找scipy.ndimage.morphology.distance_transform_edt。它对二进制数组进行操作,并计算每个TRUE位置到最近的背景FALSE位置的欧几里得距离。在我们的例子中,由于我们想找出最接近0的距离,因此背景为0。现在,在幕后,它将输入转换为以0为背景的二进制数组,因此我们可以将其与默认参数一起使用。因此,它就像-

In [179]: a
Out[179]: 
array([[0, 0, 1, 2, 5, 2, 1],
       [0, 0, 2, 3, 5, 2, 1],
       [0, 1, 1, 2, 5, 4, 1],
       [1, 1, 1, 2, 5, 4, 0]])

In [180]: from scipy import ndimage

In [181]: ndimage.distance_transform_edt(a)
Out[181]: 
array([[0.  , 0.  , 1.  , 2.  , 3.  , 3.16, 3.  ],
       [0.  , 0.  , 1.  , 2.  , 2.83, 2.24, 2.  ],
       [0.  , 1.  , 1.41, 2.24, 2.24, 1.41, 1.  ],
       [1.  , 1.41, 2.24, 2.83, 2.  , 1.  , 0.  ]])

解决通用案例

现在,假设我们要找出到最近的1s的距离,那么它应该是-

In [183]: background = 1 # element from which distances are to be computed

# compare this with original array, a to verify
In [184]: ndimage.distance_transform_edt(a!=background)
Out[184]: 
array([[2.  , 1.  , 0.  , 1.  , 2.  , 1.  , 0.  ],
       [1.41, 1.  , 1.  , 1.41, 2.  , 1.  , 0.  ],
       [1.  , 0.  , 0.  , 1.  , 2.  , 1.  , 0.  ],
       [0.  , 0.  , 0.  , 1.  , 2.  , 1.41, 1.  ]])
相关问题