face_recognition_svm.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import face_recognition
  2. from sklearn import svm
  3. import joblib
  4. import os
  5. import concurrent.futures
  6. import numpy as np
  7. import time
  8. # Training the SVC classifier
  9. # The training data would be all the face encodings from all the known images and the labels are their names
  10. encodings = []
  11. names = []
  12. tuples = []
  13. train_list = []
  14. lock = None
  15. is_train = False
  16. if not is_train:
  17. try:
  18. clf = joblib.load('saved_model.pkl')
  19. except:
  20. clf = None
  21. if clf is None:
  22. is_train = True
  23. def train_image(image, person):
  24. face = face_recognition.load_image_file(image)
  25. face_bounding_boxes = face_recognition.face_locations(face)
  26. # If training image contains exactly one face
  27. if len(face_bounding_boxes) == 1:
  28. face_enc = face_recognition.face_encodings(face)[0]
  29. # Add face encoding for current image with corresponding label (name) to the training data
  30. tuples.append((face_enc, person))
  31. else:
  32. print(image + " was skipped and can't be used for training")
  33. if is_train:
  34. # Training directory
  35. train_str = os.path.join('data', 'peeps', 'anchor')
  36. train_dir = os.listdir(os.path.join('data', 'peeps', 'anchor'))
  37. # Loop through each person in the training directory
  38. with concurrent.futures.ThreadPoolExecutor() as executor:
  39. for person in train_dir:
  40. pix_str = os.path.join(train_str, person)
  41. pix = os.listdir(os.path.join(train_str, person))
  42. # Loop through each training image for the current person
  43. for person_img in pix:
  44. # Get the face encodings for the face in each image file
  45. image = os.path.join(pix_str, person_img)
  46. executor.submit(train_image, image, person)
  47. # Create and train the SVC classifier
  48. encodings = [x for x, _ in tuples]
  49. names = [y for _, y in tuples]
  50. clf = svm.SVC(gamma='scale', probability=True)
  51. clf.fit(encodings, names)
  52. joblib.dump(clf, 'saved_model.pkl')
  53. # Load the test image with unknown faces into a numpy array
  54. test_image = face_recognition.load_image_file(os.path.join('application_data', 'input_image', 'input_image3.jpg'))
  55. # Find all the faces in the test image using the default HOG-based model
  56. face_locations = face_recognition.face_locations(test_image)
  57. no = len(face_locations)
  58. print("Number of faces detected: ", no)
  59. # Predict all the faces in the test image using the trained classifier
  60. print("Found:")
  61. for i in range(no):
  62. test_image_enc = face_recognition.face_encodings(test_image)[i]
  63. start_time = time.perf_counter_ns()
  64. proba = clf.predict_proba([test_image_enc])
  65. end_time = time.perf_counter_ns()
  66. process_time = end_time - start_time
  67. classes = clf.classes_
  68. i = np.argmax(proba)
  69. proba = list(*proba)
  70. name = classes[i]
  71. print(name, "{:.2f}".format(proba[i]), proba, process_time)