Skip to content

How do I save face encodings to a file?

Adam Geitgey edited this page Apr 2, 2018 · 1 revision

Python has a built-in way to save and load objects to a file called pickle.

import face_recognition
import pickle

all_face_encodings = {}

img1 = face_recognition.load_image_file("obama.jpg")
all_face_encodings["obama"] = face_recognition.face_encodings(img1)[0]

img2 = face_recognition.load_image_file("biden.jpg")
all_face_encodings["biden"] = face_recognition.face_encodings(img2)[0]

# ... etc ...

with open('dataset_faces.dat', 'wb') as f:
    pickle.dump(all_face_encodings, f)

That creates the file. Then later you could do this to use it:

import face_recognition
import pickle
import numpy as np

# Load face encodings
with open('dataset_faces.dat', 'rb') as f:
	all_face_encodings = pickle.load(f)

# Grab the list of names and the list of encodings
face_names = list(all_face_encodings.keys())
face_encodings = np.array(list(all_face_encodings.values()))

# Try comparing an unknown image
unknown_image = face_recognition.load_image_file("obama_small.jpg")
unknown_face = face_recognition.face_encodings(unknown_image)
result = face_recognition.compare_faces(face_encodings, unknown_face)

# Print the result as a list of names with True/False
names_with_result = list(zip(face_names, result))
print(names_with_result)

Which should print:

[('obama', True), ('biden', False)]