predict.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. from __future__ import absolute_import
  2. from __future__ import division
  3. from __future__ import print_function
  4. #----------------------------------------------------
  5. # MIT License
  6. #
  7. # Copyright (c) 2017 Rishi Rai
  8. #
  9. # Permission is hereby granted, free of charge, to any person obtaining a copy
  10. # of this software and associated documentation files (the "Software"), to deal
  11. # in the Software without restriction, including without limitation the rights
  12. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. # copies of the Software, and to permit persons to whom the Software is
  14. # furnished to do so, subject to the following conditions:
  15. #
  16. # The above copyright notice and this permission notice shall be included in all
  17. # copies or substantial portions of the Software.
  18. #
  19. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  25. # SOFTWARE.
  26. #----------------------------------------------------
  27. import tensorflow as tf
  28. import numpy as np
  29. import argparse
  30. import facenet
  31. import os
  32. import sys
  33. import math
  34. import pickle
  35. from sklearn.svm import SVC
  36. from scipy import misc
  37. import align.detect_face
  38. from six.moves import xrange
  39. def main(args):
  40. images, cout_per_image, nrof_samples = load_and_align_data(args.image_files,args.image_size, args.margin, args.gpu_memory_fraction)
  41. with tf.Graph().as_default():
  42. with tf.Session() as sess:
  43. # Load the model
  44. facenet.load_model(args.model)
  45. # Get input and output tensors
  46. images_placeholder = tf.get_default_graph().get_tensor_by_name("input:0")
  47. embeddings = tf.get_default_graph().get_tensor_by_name("embeddings:0")
  48. phase_train_placeholder = tf.get_default_graph().get_tensor_by_name("phase_train:0")
  49. # Run forward pass to calculate embeddings
  50. feed_dict = { images_placeholder: images , phase_train_placeholder:False}
  51. emb = sess.run(embeddings, feed_dict=feed_dict)
  52. classifier_filename_exp = os.path.expanduser(args.classifier_filename)
  53. with open(classifier_filename_exp, 'rb') as infile:
  54. (model, class_names) = pickle.load(infile)
  55. print('Loaded classifier model from file "%s"\n' % classifier_filename_exp)
  56. predictions = model.predict_proba(emb)
  57. best_class_indices = np.argmax(predictions, axis=1)
  58. best_class_probabilities = predictions[np.arange(len(best_class_indices)), best_class_indices]
  59. k=0
  60. #print predictions
  61. for i in range(nrof_samples):
  62. print("\npeople in image %s :" %(args.image_files[i]))
  63. for j in range(cout_per_image[i]):
  64. print('%s: %.3f' % (class_names[best_class_indices[k]], best_class_probabilities[k]))
  65. k+=1
  66. def load_and_align_data(image_paths, image_size, margin, gpu_memory_fraction):
  67. minsize = 20 # minimum size of face
  68. threshold = [ 0.6, 0.7, 0.7 ] # three steps's threshold
  69. factor = 0.709 # scale factor
  70. print('Creating networks and loading parameters')
  71. with tf.Graph().as_default():
  72. gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_memory_fraction)
  73. sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))
  74. with sess.as_default():
  75. pnet, rnet, onet = align.detect_face.create_mtcnn(sess, None)
  76. nrof_samples = len(image_paths)
  77. img_list = []
  78. count_per_image = []
  79. for i in xrange(nrof_samples):
  80. img = misc.imread(os.path.expanduser(image_paths[i]))
  81. img_size = np.asarray(img.shape)[0:2]
  82. bounding_boxes, _ = align.detect_face.detect_face(img, minsize, pnet, rnet, onet, threshold, factor)
  83. count_per_image.append(len(bounding_boxes))
  84. for j in range(len(bounding_boxes)):
  85. det = np.squeeze(bounding_boxes[j,0:4])
  86. bb = np.zeros(4, dtype=np.int32)
  87. bb[0] = np.maximum(det[0]-margin/2, 0)
  88. bb[1] = np.maximum(det[1]-margin/2, 0)
  89. bb[2] = np.minimum(det[2]+margin/2, img_size[1])
  90. bb[3] = np.minimum(det[3]+margin/2, img_size[0])
  91. cropped = img[bb[1]:bb[3],bb[0]:bb[2],:]
  92. aligned = misc.imresize(cropped, (image_size, image_size), interp='bilinear')
  93. prewhitened = facenet.prewhiten(aligned)
  94. img_list.append(prewhitened)
  95. images = np.stack(img_list)
  96. return images, count_per_image, nrof_samples
  97. def parse_arguments(argv):
  98. parser = argparse.ArgumentParser()
  99. parser.add_argument('image_files', type=str, nargs='+', help='Path(s) of the image(s)')
  100. parser.add_argument('model', type=str,
  101. help='Could be either a directory containing the meta_file and ckpt_file or a model protobuf (.pb) file')
  102. parser.add_argument('classifier_filename',
  103. help='Classifier model file name as a pickle (.pkl) file. ' +
  104. 'For training this is the output and for classification this is an input.')
  105. parser.add_argument('--image_size', type=int,
  106. help='Image size (height, width) in pixels.', default=160)
  107. parser.add_argument('--seed', type=int,
  108. help='Random seed.', default=666)
  109. parser.add_argument('--margin', type=int,
  110. help='Margin for the crop around the bounding box (height, width) in pixels.', default=44)
  111. parser.add_argument('--gpu_memory_fraction', type=float,
  112. help='Upper bound on the amount of GPU memory that will be used by the process.', default=1.0)
  113. return parser.parse_args(argv)
  114. if __name__ == '__main__':
  115. main(parse_arguments(sys.argv[1:]))