Skip to content

Instantly share code, notes, and snippets.

@debboutr
Last active October 18, 2018 03:59
Show Gist options
  • Save debboutr/bec5f22ef778e73b5d3c9592fa70da62 to your computer and use it in GitHub Desktop.
Save debboutr/bec5f22ef778e73b5d3c9592fa70da62 to your computer and use it in GitHub Desktop.
euclidean distance tool
import math
import numpy as np
def get_index_distance(index1, index2 ) :
home_x, home_y = index1
afar_x, afar_y = index2
squares = abs(home_x-afar_x)**2 + abs(home_y-afar_y)**2
return math.sqrt(squares)
def get_closest_index(array, index) :
r,c = np.nonzero(array)
min_idx = ((r - index[0])**2 + (c - index[1])**2).argmin()
return r[min_idx], c[min_idx]
def euclidean_distance(arr, nodata=0):
out = -np.ones(arr.shape)
finders = np.where(arr == nodata)
b = arr != nodata
for finder in zip(*finders):
nearest = get_closest_index(b.astype(int), finder)
out[finder] = get_index_distance(finder,nearest)
out[out<0] = 0
return out
if __name__ == '__main__':
esri = np.zeros((6,6), dtype=int)
esri[(0,0,1),(1,2,2)] = 1
esri[(5,0)] = 4
euclidean_distance(esri)
l = np.zeros((7,7), dtype=int)
l[(3,3)] = 1
euclidean_distance(l)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment