Use the face_recognition library to encode faces from the dataset. This step creates unique numerical representations for each face.
import os
import face_recognition
import cv2
import pickle
# Path to dataset
DATASET_PATH = "dataset"
ENCODINGS_FILE = "encodings.pickle"
def encode_faces():
known_encodings = []
known_names = []
# Iterate through each person's folder
for person in os.listdir(DATASET_PATH):
person_path = os.path.join(DATASET_PATH, person)
if not os.path.isdir(person_path):
continue
# Process each image
for img_file in os.listdir(person_path):
img_path = os.path.join(person_path, img_file)
image = face_recognition.load_image_file(img_path)
face_encodings = face_recognition.face_encodings(image)
if face_encodings:
known_encodings.append(face_encodings[0])
known_names.append(person)
# Save encodings to a file
with open(ENCODINGS_FILE, "wb") as f:
pickle.dump({"encodings": known_encodings, "names": known_names}, f)
print("Encodings saved!")
encode_faces()