face_distance.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import face_recognition
  2. # Often instead of just checking if two faces match or not (True or False), it's helpful to see how similar they are.
  3. # You can do that by using the face_distance function.
  4. # The model was trained in a way that faces with a distance of 0.6 or less should be a match. But if you want to
  5. # be more strict, you can look for a smaller face distance. For example, using a 0.55 cutoff would reduce false
  6. # positive matches at the risk of more false negatives.
  7. # Note: This isn't exactly the same as a "percent match". The scale isn't linear. But you can assume that images with a
  8. # smaller distance are more similar to each other than ones with a larger distance.
  9. # Load some images to compare against
  10. known_obama_image = face_recognition.load_image_file("obama.jpg")
  11. known_biden_image = face_recognition.load_image_file("biden.jpg")
  12. # Get the face encodings for the known images
  13. obama_face_encoding = face_recognition.face_encodings(known_obama_image)[0]
  14. biden_face_encoding = face_recognition.face_encodings(known_biden_image)[0]
  15. known_encodings = [
  16. obama_face_encoding,
  17. biden_face_encoding
  18. ]
  19. # Load a test image and get encondings for it
  20. image_to_test = face_recognition.load_image_file("obama2.jpg")
  21. image_to_test_encoding = face_recognition.face_encodings(image_to_test)[0]
  22. # See how far apart the test image is from the known faces
  23. face_distances = face_recognition.face_distance(known_encodings, image_to_test_encoding)
  24. for i, face_distance in enumerate(face_distances):
  25. print("The test image has a distance of {:.2} from known image #{}".format(face_distance, i))
  26. print("- With a normal cutoff of 0.6, would the test image match the known image? {}".format(face_distance < 0.6))
  27. print("- With a very strict cutoff of 0.5, would the test image match the known image? {}".format(face_distance < 0.5))
  28. print()