1
\$\begingroup\$

I'm working on some facial recognition scripts in python using the dlib library. dlib takes in a face and returns a tuple with floating point values representing the values for key points in the face. If the Euclidean distance between two faces data sets is less that .6 they are likely the same.

So, I had to implement the Euclidean distance calculation on my own. I found an SO post here that said to use numpy but I couldn't make the subtraction operation work between my tuples. Because this is facial recognition speed is important. If anyone can see a way to improve, please let me know.

Yes, it works :)

def euclidean_dist(data_x, data_y):
    if len(data_x) != len(data_y):
        raise Exception('Data sets must be the same dimension')
    dimensions = len(data_x)
    sum_dims = 0
    for dim in range(0, dimensions):
        sum_dims += (data_x[dim] - data_y[dim])**2

    return sqrt(sum_dims)
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

You can collapse the summation using sum():

sum_dims = sum((data_x[dim] - data_y[dim]) ** 2
               for dim in range(dimensions))

Or, what if you would "zip" the x and y:

sum_dims = sum((x - y) ** 2 for x, y in zip(data_x, data_y))
\$\endgroup\$
3
  • \$\begingroup\$ Great solutions, I will research but do you have any idea which implementation would be faster? \$\endgroup\$
    – rayepps
    Commented Nov 28, 2017 at 3:39
  • \$\begingroup\$ @raykrow I would make a safe bet on the "numpy" one :) \$\endgroup\$
    – alecxe
    Commented Nov 28, 2017 at 3:41
  • \$\begingroup\$ Ha, ya I'm sure....I will use this for now and possibly open an SO question to figure out how to make numpy work with the tuples \$\endgroup\$
    – rayepps
    Commented Nov 28, 2017 at 3:42

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.