Skip to content

Instantly share code, notes, and snippets.

@NISH1001
Created December 8, 2018 04:01
Show Gist options
  • Save NISH1001/1a9fdecca0b3a370ded8da4dfe3b5ba9 to your computer and use it in GitHub Desktop.
Save NISH1001/1a9fdecca0b3a370ded8da4dfe3b5ba9 to your computer and use it in GitHub Desktop.
Compute voronoi diagram for given list of points
# coords => List of tuple => [(x1, y1), ....(xn, yn)]
def voronoi(coords, width=800, height=800, use_max=False):
coord_matrix = np.array(coords)
X, Y = zip(*coords)
if use_max:
w, h = max(X) + 2, max(Y) + 2
else:
w, h = width, height
print("Computing voronoi diagram of size :: {}, {}".format(w, h))
minx, miny = min(X), min(Y)
xx = list(range(w))
yy = list(range(h))
mat = np.array(list(itertools.product(xx, yy)))
distances = manhattan_distances(mat, coord_matrix)
dist_min_idx = np.argmin(distances, axis=1)
dist_min = np.min(distances, axis=1)
arr = np.zeros((w, h))
for i, p in enumerate(mat):
r, c = p
idx = dist_min_idx[i]
dist = distances[i]
mn = np.min(dist)
count = (dist == mn).sum()
val = dist_min_idx[i] if count == 1 else -1
arr[r, c] = val
return arr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment