Created
May 21, 2020 09:09
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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