Skip to content

Instantly share code, notes, and snippets.

@marmakoide
Created May 21, 2020 09:09
Show Gist options
  • Save marmakoide/c4719e175183ebe6faa1af87227ccd9c to your computer and use it in GitHub Desktop.
Save marmakoide/c4719e175183ebe6faa1af87227ccd9c to your computer and use it in GitHub Desktop.
SIMD implementation of 2d euclidean distance. For each non-zero input pixel, returns the exact squared distance to the closest zero input pixel.
import numpy
def euclidean_distance_transform(F):
ret = numpy.empty_like(F, dtype = int)
def get_parabola_matrix(N):
X = numpy.arange(N, dtype = int)
G = numpy.empty((N, N), dtype = int)
G[:] = X
G -= X[:, None]
G *= G
return G
# Horizontal pass
G = get_parabola_matrix(F.shape[1])
for i in range(F.shape[0]):
numpy.amin(G + (F.shape[1] ** 2) * (F[i][:, None] != 0), axis = 0, out = ret[i, :])
# Vertical pass
G = get_parabola_matrix(F.shape[0])
for i in range(F.shape[1]):
numpy.amin(G + ret[:,i][:, None], axis = 0, out = ret[:, i])
# Job done
return ret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment