项目作者: chanddu

项目描述 :
Face Recognition library
高级语言: Python
项目地址: git://github.com/chanddu/Face-Recognition.git
创建时间: 2018-02-16T22:35:52Z
项目社区:https://github.com/chanddu/Face-Recognition

开源协议:

下载


Face Recognition

face_rec_webcam.py is an example program that uses the Face Recognition class in Yoda.py

The Face Recognition class shows how to find frontal human faces in an image and estimate their pose. The pose takes the form of 68 landmarks. These are points on the face such as the corners of the mouth, along the eyebrows, on the eyes, and so forth.

The face detector we use is made using the classic Histogram of Oriented Gradients (HOG) feature combined with a linear classifier, an image pyramid, and sliding window detection scheme. The pose estimator was created by using dlib’s implementation of the paper: One Millisecond Face Alignment with an Ensemble of Regression Trees by Vahid Kazemi and Josephine Sullivan, CVPR 2014 and was trained on the iBUG 300-W face landmark dataset (see https://ibug.doc.ic.ac.uk/resources/facial-point-annotations/): C. Sagonas, E. Antonakos, G, Tzimiropoulos, S. Zafeiriou, M. Pantic. 300 faces In-the-wild challenge: Database and results. Image and Vision Computing (IMAVIS), Special Issue on Facial Landmark Localisation "In-The-Wild". 2016.

You can get the trained model file from: http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2.

Note that the license for the iBUG 300-W dataset excludes commercial use. So you should contact Imperial College London to find out if it’s OK for you to use this model file in a commercial product.

The program maps an image of a human face to a 128 dimensional vector space where images of the same person are near to each other and images from different people are far apart. Therefore, you can perform face recognition by mapping faces to the 128D space and then checking if their Euclidean distance is small enough.

When using a distance threshold of 0.6, the dlib model obtains an accuracy of 99.38% on the standard LFW face recognition benchmark, which is comparable to other state-of-the-art methods for face recognition as of February 2017. This accuracy means that, when presented with a pair of face images, the tool will correctly identify if the pair belongs to the same person or is from different people 99.38% of the time.

Sample Face recognition program that uses the Yoda Face Recognition library:

  1. from Yoda import FaceRecognition
  2. import cv2
  3. video_capture = cv2.VideoCapture(0)
  4. model = FaceRecognition()
  5. obama_image = model.load_image_file('obama.jpg')
  6. obama_face_encoding = model.face_embeddings(obama_image)[0]
  7. biden_image = model.load_image_file('biden.jpg')
  8. biden_face_encoding = model.face_embeddings(biden_image)[0]
  9. # Create arrays of known face encodings and their names
  10. known_face_encodings = [
  11. obama_face_encoding,
  12. biden_face_encoding
  13. ]
  14. known_face_names = [
  15. "Barack Obama",
  16. "Joe Biden"
  17. ]
  18. # Initialize some variables
  19. face_locations = []
  20. face_encodings = []
  21. face_names = []
  22. process_this_frame = True
  23. while True:
  24. # Grab a single frame of video
  25. ret, frame = video_capture.read()
  26. # Resize frame of video to 1/4 size for faster face recognition processing
  27. small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
  28. # Convert the image from BGR color (which OpenCV uses) to RGB color (which FaceRecognition uses)
  29. rgb_small_frame = small_frame[:, :, ::-1]
  30. # Only process every other frame of video to save time
  31. if process_this_frame:
  32. # Find all the faces and face encodings in the current frame of video
  33. face_locations = model.find_face_locations(rgb_small_frame)
  34. face_encodings = model.face_embeddings(rgb_small_frame, face_locations)
  35. face_names = []
  36. for face_encoding in face_encodings:
  37. # See if the face is a match for the known face(s)
  38. matches = model.compare_faces(known_face_encodings, face_encoding)
  39. name = "Unknown"
  40. # If a match was found in known_face_encodings, just use the first one.
  41. if True in matches:
  42. first_match_index = matches.index(True)
  43. name = known_face_names[first_match_index]
  44. face_names.append(name)
  45. process_this_frame = not process_this_frame
  46. # Display the results
  47. for d, name in zip(face_locations, face_names):
  48. # Scale back up face locations since the frame we detected in was scaled to 1/4 size
  49. top = d.top() * 4
  50. right = d.right() * 4
  51. bottom = d.bottom() * 4
  52. left = d.left() * 4
  53. # Draw a box around the face
  54. cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
  55. # Draw a label with a name below the face
  56. cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
  57. font = cv2.FONT_HERSHEY_DUPLEX
  58. cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)
  59. # Display the resulting image
  60. cv2.imshow('Video', frame)
  61. # Hit 'q' on the keyboard to quit!
  62. if cv2.waitKey(1) & 0xFF == ord('q'):
  63. break
  64. # Release handle to the webcam
  65. video_capture.release()
  66. cv2.destroyAllWindows()

Face Recognition - Step by step

Step - 1

The first step in our pipeline is face detection. We’re going to use a method called Histogram of Oriented Gradients — or just HOG for short.

The original image is turned into a HOG representation that captures the major features of the image regardless of image brightnesss.

To find faces in this HOG image, all we have to do is find the part of our image that looks the most similar to a known HOG pattern that was extracted from a bunch of other training faces:

This example program shows how to find frontal human faces in an image.

  1. import sys
  2. import dlib
  3. from skimage import io
  4. detector = dlib.get_frontal_face_detector()
  5. win = dlib.image_window()
  6. for f in sys.argv[1:]:
  7. print("Processing file: {}".format(f))
  8. img = io.imread(f)
  9. # The 1 in the second argument indicates that we should upsample the image
  10. # 1 time. This will make everything bigger and allow us to detect more
  11. # faces.
  12. dets = detector(img, 1)
  13. print("Number of faces detected: {}".format(len(dets)))
  14. for i, d in enumerate(dets):
  15. print("Detection {}: Left: {} Top: {} Right: {} Bottom: {}".format(
  16. i, d.left(), d.top(), d.right(), d.bottom()))
  17. win.clear_overlay()
  18. win.set_image(img)
  19. win.add_overlay(dets)
  20. dlib.hit_enter_to_continue()

Step - 2 Posing and projecting faces

We use a face landmark estimation algorithm to come up with 68 specific points (called landmarks) that exist on every face — the top of the chin, the outside edge of each eye, the inner edge of each eyebrow, etc.

The 68 landmarks we will locate on every face. This image was created by Brandon Amos of CMU who works on OpenFace.

This example program shows how to do face landmark detection.

  1. import sys
  2. import dlib
  3. from skimage import io
  4. # You can download the required pre-trained face detection model here:
  5. # http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2
  6. predictor_model = "shape_predictor_68_face_landmarks.dat"
  7. # Take the image file name from the command line
  8. file_name = sys.argv[1]
  9. # Create a HOG face detector using the built-in dlib class
  10. face_detector = dlib.get_frontal_face_detector()
  11. face_pose_predictor = dlib.shape_predictor(predictor_model)
  12. win = dlib.image_window()
  13. # Take the image file name from the command line
  14. file_name = sys.argv[1]
  15. # Load the image
  16. image = io.imread(file_name)
  17. # Run the HOG face detector on the image data
  18. detected_faces = face_detector(image, 1)
  19. print("Found {} faces in the image file {}".format(len(detected_faces), file_name))
  20. # Show the desktop window with the image
  21. win.set_image(image)
  22. # Loop through each face we found in the image
  23. for i, face_rect in enumerate(detected_faces):
  24. # Detected faces are returned as an object with the coordinates
  25. # of the top, left, right and bottom edges
  26. print("- Face #{} found at Left: {} Top: {} Right: {} Bottom: {}".format(i, face_rect.left(), face_rect.top(), face_rect.right(), face_rect.bottom()))
  27. # Draw a box around each face we found
  28. win.add_overlay(face_rect)
  29. # Get the the face's pose
  30. pose_landmarks = face_pose_predictor(image, face_rect)
  31. # Draw the face landmarks on the screen.
  32. win.add_overlay(pose_landmarks)
  33. dlib.hit_enter_to_continue()

Here’s the result of locating the 68 face landmarks on my image:

Step - 3 Encoding faces

It is the process of learning a mapping from face images to a compact Euclidean space where distances directly correspond to a measure of face similarity. Once this space has been produced, tasks such as face recognition, verification and clustering can be easily implemented using standard techniques with FaceNet embeddings as feature vectors.

The neural network learns to reliably generate 128 measurements for each person. Any ten different pictures of the same person should give roughly the same measurements.

The exact approach for faces we are using was invented in 2015 by researchers at Google, called Facenet

Step 4: Finding the person’s name from the encoding

Find the person in our database of known people who has the closest measurements to our test image.

You can do that by using any basic machine learning classification algorithm. As of now, Yoda.py doesn’t implement any classification algorithm yet.