Skip to content

Instantly share code, notes, and snippets.

@BindiChen
Last active March 8, 2020 19:16
Show Gist options
  • Save BindiChen/eba5532a0bd68b8effed426cf0adc4b0 to your computer and use it in GitHub Desktop.
Save BindiChen/eba5532a0bd68b8effed426cf0adc4b0 to your computer and use it in GitHub Desktop.
Recognising Face using the "face_recognition" library
import face_recognition
# Number of known persons
n = 2
# Create a list of all known face encodings
known_face_encodings = []
for num in range(1, n + 1):
image_file = f"known_person_{num}.jpg"
# Load each known image
image_of_person = face_recognition.load_image_file(image_file)
# Get the face encoding of each person. This can fail if no one is found in the photo
face_encoding = face_recognition.face_encodings(image_of_person)[0]
# Create a list of all known face encodings
known_face_encodings.append(face_encoding)
# Load the image we want to check
unknown_image = face_recognition.load_image_file(
"test_image.jpg"
)
# Get face encodings for any people in the picture
unknown_face_encodings = face_recognition.face_encodings(
unknown_image
)
# There might be more than one person in the photo, so we need to loop over each face we found
for unknown_face_encoding in unknown_face_encodings:
face_distances = face_recognition.face_distance(
known_face_encodings,
unknown_face_encoding
)
print(f"Distance between unknown image and each known image: {face_distances}")
# Test if this unknown face encoding matches any of the n people we know
results = face_recognition.compare_faces(
known_face_encodings,
unknown_face_encoding,
tolerance=0.6
)
for num in range(0, n):
if results[num]:
print(f"Found Person {num + 1} in the photo!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment