I've been looking for a way to (efficiently) compute a distance matrix from a target value and an input matrix.
If you consider an input array as:
[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]
Ho do you compute the spatial distance matrix associated to the target value 0?
i.e. what is the distance from each pixel to the closest 0 value?
Thanks in advance
You are looking for
scipy.ndimage.morphology.distance_transform_edt
. It operates on a binary array and computes euclidean distances on eachTRUE
position to the nearest backgroundFALSE
position. In our case, since we want to find out distances from nearest 0s, so the background is0
. Now, under the hoods, it converts the input to a binary array assuming 0 as the background, so we can just use it with the default parameters. Hence, it would be as simple as -Solving for generic case
Now, let's say we want to find out distances from nearest
1s
, then it would be -