You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
2.0 KiB

4 years ago
  1. # USAGE
  2. # python encode_faces.py --dataset dataset --encodings encodings.pickle
  3. # import the necessary packages
  4. from imutils import paths
  5. import face_recognition
  6. import argparse
  7. import pickle
  8. import cv2
  9. import os
  10. # construct the argument parser and parse the arguments
  11. ap = argparse.ArgumentParser()
  12. ap.add_argument("-i", "--dataset", required=True,
  13. help="path to input directory of faces + images")
  14. ap.add_argument("-e", "--encodings", required=True,
  15. help="path to serialized db of facial encodings")
  16. ap.add_argument("-d", "--detection-method", type=str, default="cnn",
  17. help="face detection model to use: either `hog` or `cnn`")
  18. args = vars(ap.parse_args())
  19. # grab the paths to the input images in our dataset
  20. print("[INFO] quantifying faces...")
  21. imagePaths = list(paths.list_images(args["dataset"]))
  22. # initialize the list of known encodings and known names
  23. knownEncodings = []
  24. knownNames = []
  25. # loop over the image paths
  26. for (i, imagePath) in enumerate(imagePaths):
  27. # extract the person name from the image path
  28. print("[INFO] processing image {}/{}".format(i + 1,
  29. len(imagePaths)))
  30. name = imagePath.split(os.path.sep)[-2]
  31. # load the input image and convert it from RGB (OpenCV ordering)
  32. # to dlib ordering (RGB)
  33. image = cv2.imread(imagePath)
  34. rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
  35. # detect the (x, y)-coordinates of the bounding boxes
  36. # corresponding to each face in the input image
  37. boxes = face_recognition.face_locations(rgb,
  38. model=args["detection_method"])
  39. # compute the facial embedding for the face
  40. encodings = face_recognition.face_encodings(rgb, boxes)
  41. # loop over the encodings
  42. for encoding in encodings:
  43. # add each encoding + name to our set of known names and
  44. # encodings
  45. knownEncodings.append(encoding)
  46. knownNames.append(name)
  47. # dump the facial encodings + names to disk
  48. print("[INFO] serializing encodings...")
  49. data = {"encodings": knownEncodings, "names": knownNames}
  50. f = open(args["encodings"], "wb")
  51. f.write(pickle.dumps(data))
  52. f.close()