face_auth.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. from scipy import spatial
  2. # Feature embedding vector of enrolled faces
  3. enrolled_faces = []
  4. # The minimum distance between two faces
  5. # to be called unique
  6. authentication_threshold = 0.30
  7. def enroll_face(embeddings):
  8. """
  9. This function adds the feature embedding
  10. for given face to the list of enrolled faces.
  11. This entire process is equivalent to
  12. face enrolment.
  13. """
  14. # Get feature embedding vector
  15. for embedding in embeddings:
  16. # Add feature embedding to list of
  17. # enrolled faces
  18. enrolled_faces.append(embedding)
  19. def delist_face(embeddings):
  20. """
  21. This function removes a face from the list
  22. of enrolled faces.
  23. """
  24. # Get feature embedding vector for input images
  25. global enrolled_faces
  26. if len(embeddings) > 0:
  27. for embedding in embeddings:
  28. # List of faces remaining after delisting
  29. remaining_faces = []
  30. # Iterate over the enrolled faces
  31. for idx, face_emb in enumerate(enrolled_faces):
  32. # Compute distance between feature embedding
  33. # for input images and the current face's
  34. # feature embedding
  35. dist = spatial.distance.cosine(embedding, face_emb)
  36. # If the above distance is more than or equal to
  37. # threshold, then add the face to remaining faces list
  38. # Distance between feature embeddings
  39. # is equivalent to the difference between
  40. # two faces
  41. if dist >= authentication_threshold:
  42. remaining_faces.append(face_emb)
  43. # Update the list of enrolled faces
  44. enrolled_faces = remaining_faces
  45. def authenticate_emb(embedding):
  46. """
  47. This function checks if a similar face
  48. embedding is present in the list of
  49. enrolled faces or not.
  50. """
  51. # Set authentication to False by default
  52. authentication = False
  53. if embedding is not None:
  54. # Iterate over all the enrolled faces
  55. for face_emb in enrolled_faces:
  56. # Compute the distance between the enrolled face's
  57. # embedding vector and the input image's
  58. # embedding vector
  59. dist = spatial.distance.cosine(embedding, face_emb)
  60. # If above distance is less the threshold
  61. if dist < authentication_threshold:
  62. # Set the authenatication to True
  63. # meaning that the input face has been matched
  64. # to the current enrolled face
  65. authentication = True
  66. if authentication:
  67. # If the face was authenticated
  68. return True
  69. else:
  70. # If the face was not authenticated
  71. return False
  72. # Default
  73. return None