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