2

I have a numpy array of the shape 512x512 and a center point within this range. Now i want to fill the array with the euclidean distance of the center point to the array elements.

For example: Center=[10,10] -> array[0,0]=sqrt((0-10)^2+(0-10)^2)...

I already have working code:

def calc_euclidean_distance(center, point):
   return np.sqrt((center[0] - point[0]) ** 2 + (center[1] - point[1]) ** 2)

target = np.zeros([512, 512])
center = np.array([10, 376]) #example

for iterrow, row in enumerate(target):
   for itercol, i in enumerate(row):
      target[iterrow, itercol] = self.calc_euclidean_distance(center, [iterrow, itercol])

But this is really slow and also probably very "un-pythonic". I can not come up with a better way and now asking for education.

1 Answer 1

4

I believe that this does what you want:

w, h = (512, 512)
cx, cy = (10, 376)
xcoords, ycoords = np.meshgrid(np.arange(w), np.arange(h))
target = np.sqrt((xcoords - cx)**2 + (ycoords - cy)**2)
Sign up to request clarification or add additional context in comments.

1 Comment

Works great and is (obviously) a great speed up. Did not know about np.meshgrid. Very helpful thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.