face.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. # coding=utf-8
  2. """Face Detection and Recognition"""
  3. # MIT License
  4. #
  5. # Copyright (c) 2017 François Gervais
  6. #
  7. # This is the work of David Sandberg and shanren7 remodelled into a
  8. # high level container. It's an attempt to simplify the use of such
  9. # technology and provide an easy to use facial recognition package.
  10. #
  11. # https://github.com/davidsandberg/facenet
  12. # https://github.com/shanren7/real_time_face_recognition
  13. #
  14. # Permission is hereby granted, free of charge, to any person obtaining a copy
  15. # of this software and associated documentation files (the "Software"), to deal
  16. # in the Software without restriction, including without limitation the rights
  17. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  18. # copies of the Software, and to permit persons to whom the Software is
  19. # furnished to do so, subject to the following conditions:
  20. #
  21. # The above copyright notice and this permission notice shall be included in all
  22. # copies or substantial portions of the Software.
  23. #
  24. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  25. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  26. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  27. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  28. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  29. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  30. # SOFTWARE.
  31. import pickle
  32. import os
  33. import cv2
  34. import numpy as np
  35. import tensorflow as tf
  36. from scipy import misc
  37. import align.detect_face
  38. import facenet
  39. gpu_memory_fraction = 0.3
  40. facenet_model_checkpoint = os.path.dirname(__file__) + "/../model_checkpoints/20170512-110547"
  41. classifier_model = os.path.dirname(__file__) + "/../model_checkpoints/my_classifier_1.pkl"
  42. debug = False
  43. class Face:
  44. def __init__(self):
  45. self.name = None
  46. self.bounding_box = None
  47. self.image = None
  48. self.container_image = None
  49. self.embedding = None
  50. class Recognition:
  51. def __init__(self):
  52. self.detect = Detection()
  53. self.encoder = Encoder()
  54. self.identifier = Identifier()
  55. def add_identity(self, image, person_name):
  56. faces = self.detect.find_faces(image)
  57. if len(faces) == 1:
  58. face = faces[0]
  59. face.name = person_name
  60. face.embedding = self.encoder.generate_embedding(face)
  61. return faces
  62. def identify(self, image):
  63. faces = self.detect.find_faces(image)
  64. for i, face in enumerate(faces):
  65. if debug:
  66. cv2.imshow("Face: " + str(i), face.image)
  67. face.embedding = self.encoder.generate_embedding(face)
  68. face.name = self.identifier.identify(face)
  69. return faces
  70. class Identifier:
  71. def __init__(self):
  72. with open(classifier_model, 'rb') as infile:
  73. self.model, self.class_names = pickle.load(infile)
  74. def identify(self, face):
  75. if face.embedding is not None:
  76. predictions = self.model.predict_proba([face.embedding])
  77. best_class_indices = np.argmax(predictions, axis=1)
  78. return self.class_names[best_class_indices[0]]
  79. class Encoder:
  80. def __init__(self):
  81. self.sess = tf.Session()
  82. with self.sess.as_default():
  83. facenet.load_model(facenet_model_checkpoint)
  84. def generate_embedding(self, face):
  85. # Get input and output tensors
  86. images_placeholder = tf.get_default_graph().get_tensor_by_name("input:0")
  87. embeddings = tf.get_default_graph().get_tensor_by_name("embeddings:0")
  88. phase_train_placeholder = tf.get_default_graph().get_tensor_by_name("phase_train:0")
  89. prewhiten_face = facenet.prewhiten(face.image)
  90. # Run forward pass to calculate embeddings
  91. feed_dict = {images_placeholder: [prewhiten_face], phase_train_placeholder: False}
  92. return self.sess.run(embeddings, feed_dict=feed_dict)[0]
  93. class Detection:
  94. # face detection parameters
  95. minsize = 20 # minimum size of face
  96. threshold = [0.6, 0.7, 0.7] # three steps's threshold
  97. factor = 0.709 # scale factor
  98. def __init__(self, face_crop_size=160, face_crop_margin=32):
  99. self.pnet, self.rnet, self.onet = self._setup_mtcnn()
  100. self.face_crop_size = face_crop_size
  101. self.face_crop_margin = face_crop_margin
  102. def _setup_mtcnn(self):
  103. with tf.Graph().as_default():
  104. gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_memory_fraction)
  105. sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))
  106. with sess.as_default():
  107. return align.detect_face.create_mtcnn(sess, None)
  108. def find_faces(self, image):
  109. faces = []
  110. bounding_boxes, _ = align.detect_face.detect_face(image, self.minsize,
  111. self.pnet, self.rnet, self.onet,
  112. self.threshold, self.factor)
  113. for bb in bounding_boxes:
  114. face = Face()
  115. face.container_image = image
  116. face.bounding_box = np.zeros(4, dtype=np.int32)
  117. img_size = np.asarray(image.shape)[0:2]
  118. face.bounding_box[0] = np.maximum(bb[0] - self.face_crop_margin / 2, 0)
  119. face.bounding_box[1] = np.maximum(bb[1] - self.face_crop_margin / 2, 0)
  120. face.bounding_box[2] = np.minimum(bb[2] + self.face_crop_margin / 2, img_size[1])
  121. face.bounding_box[3] = np.minimum(bb[3] + self.face_crop_margin / 2, img_size[0])
  122. cropped = image[face.bounding_box[1]:face.bounding_box[3], face.bounding_box[0]:face.bounding_box[2], :]
  123. face.image = misc.imresize(cropped, (self.face_crop_size, self.face_crop_size), interp='bilinear')
  124. faces.append(face)
  125. return faces