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)
asked Nov 28, 2017 at 3:24
\$\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))
answered Nov 28, 2017 at 3:32
\$\endgroup\$
3
  • \$\begingroup\$ Great solutions, I will research but do you have any idea which implementation would be faster? \$\endgroup\$ Commented Nov 28, 2017 at 3:39
  • \$\begingroup\$ @raykrow I would make a safe bet on the "numpy" one :) \$\endgroup\$ 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\$ Commented Nov 28, 2017 at 3:42

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.