Untitled

 avatar
user_2381398
plain_text
a year ago
1.9 kB
8
Indexable
Never
import face_recognition
import cv2
import os
from keras.models import Sequential
from keras.layers import Dense
from sklearn.preprocessing import LabelEncoder
from keras.utils import np_utils

# Step 1: Prepare the data
image_paths = os.listdir('path_to_your_dataset')

face_encodings = []
face_names = []

for image_path in image_paths:
    image = face_recognition.load_image_file(image_path)
    face_locations = face_recognition.face_locations(image)
    encoding = face_recognition.face_encodings(image, face_locations)[0]
    face_encodings.append(encoding)
    face_names.append(image_path.split('/')[1])

# convert labels to integers then one-hot encode
encoder = LabelEncoder()
encoder.fit(face_names)
encoded_Y = encoder.transform(face_names)
# convert integers to dummy variables (i.e. one hot encoded)
face_names = np_utils.to_categorical(encoded_Y)

# Step 2: Train the model
model = Sequential()
model.add(Dense(128, input_dim=128, activation='relu'))
model.add(Dense(64, activation='relu'))
model.add(Dense(len(set(face_names)), activation='softmax'))

model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

model.fit(face_encodings, face_names, epochs=10, batch_size=32)

# Step 3: Test and evaluate the model
test_image_paths = os.listdir('path_to_your_testset')

for test_image_path in test_image_paths:
    test_image = face_recognition.load_image_file(test_image_path)
    test_face_locations = face_recognition.face_locations(test_image)
    test_face_encodings = face_recognition.face_encodings(test_image, test_face_locations)
    
    predictions = model.predict(test_face_encodings)
    predicted_name = encoder.classes_[np.argmax(predictions)]
    print(f"Predicted: {predicted_name}, Actual: {test_image_path.split('/')[1]}")