face_recognition_svm.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import face_recognition
  2. from sklearn import svm
  3. import joblib
  4. import os
  5. # Training the SVC classifier
  6. # The training data would be all the face encodings from all the known images and the labels are their names
  7. encodings = []
  8. names = []
  9. train_list = []
  10. is_train = False
  11. if not is_train:
  12. try:
  13. clf = joblib.load('saved_model.pkl')
  14. except:
  15. clf = None
  16. if clf is None:
  17. is_train = True
  18. if is_train:
  19. # Training directory
  20. train_str = os.path.join('data', 'peeps', 'anchor')
  21. train_dir = os.listdir(os.path.join('data', 'peeps', 'anchor'))
  22. # Loop through each person in the training directory
  23. for person in train_dir:
  24. pix_str = os.path.join(train_str, person)
  25. pix = os.listdir(os.path.join(train_str, person))
  26. # Loop through each training image for the current person
  27. for person_img in pix:
  28. # Get the face encodings for the face in each image file
  29. face = face_recognition.load_image_file(pix_str + "/" + person_img)
  30. face_bounding_boxes = face_recognition.face_locations(face)
  31. # If training image contains exactly one face
  32. if len(face_bounding_boxes) == 1:
  33. face_enc = face_recognition.face_encodings(face)[0]
  34. # Add face encoding for current image with corresponding label (name) to the training data
  35. encodings.append(face_enc)
  36. names.append(person)
  37. else:
  38. print(person + "/" + person_img + " was skipped and can't be used for training")
  39. # Create and train the SVC classifier
  40. clf = svm.SVC(gamma='scale', probability=True)
  41. clf.fit(encodings, names)
  42. joblib.dump(clf, 'saved_model.pkl')
  43. # Load the test image with unknown faces into a numpy array
  44. test_image = face_recognition.load_image_file(os.path.join('application_data', 'input_image', 'input_image.jpg'))
  45. # Find all the faces in the test image using the default HOG-based model
  46. face_locations = face_recognition.face_locations(test_image)
  47. no = len(face_locations)
  48. print("Number of faces detected: ", no)
  49. # Predict all the faces in the test image using the trained classifier
  50. print("Found:")
  51. for i in range(no):
  52. test_image_enc = face_recognition.face_encodings(test_image)[i]
  53. name = clf.predict([test_image_enc])
  54. print(*name)