In numpy I have a 2d array of 1s and 0s. I need to calculate a new array (same dimensions) where each element contains the distance to the nearest 1 from the corresponding point in the mask array.
e.g.
a=np.array(
[[1,1,0],
[1,0,0],
[1,0,0]])
I need b to look like this:
array([[0,0,1],
[0,1,1.41],
[0,1,2]])
PS. I'll be doing this over very large arrays, so the more efficient the better! Thanks!
Method 2: Using dot() and sqrt() methods We can leverage the NumPy dot() method for finding the dot product of the difference of points, and by doing the square root of the output returned by the dot() method, we will be getting the Euclidean distance.
The math. dist() method returns the Euclidean distance between two points (p and q), where p and q are the coordinates of that point. Note: The two points (p and q) must be of the same dimensions.
In this method, we first initialize two numpy arrays. Then, we take the difference of the two arrays, compute the dot product of the result, and transpose of the result. Then we take the square root of the answer. This is another way to implement Euclidean distance.
You're looking for the equivalent of MATLAB's bwdist
; check out this SO question for more details. The short answer is to use scipy.ndimage.morphology.distance_transform_edt
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With