Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to efficiently calculate distance to nearest 1 in mask in numpy?

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!

like image 472
Pete W Avatar asked Mar 12 '12 15:03

Pete W


People also ask

How does Numpy calculate distance?

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.

How do you find the distance from one point to another in python?

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.

How will you measure the Euclidean distance between the two arrays in Numpy?

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.


1 Answers

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.

like image 153
Jacob Avatar answered Sep 21 '22 19:09

Jacob