test_invariance_on_lfw.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. """Test invariance to translation, scaling and rotation on the "Labeled Faces in the Wild" dataset (http://vis-www.cs.umass.edu/lfw/).
  2. This requires test images to be cropped a bit wider than the normal to give some room for the transformations.
  3. """
  4. # MIT License
  5. #
  6. # Copyright (c) 2016 David Sandberg
  7. #
  8. # Permission is hereby granted, free of charge, to any person obtaining a copy
  9. # of this software and associated documentation files (the "Software"), to deal
  10. # in the Software without restriction, including without limitation the rights
  11. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. # copies of the Software, and to permit persons to whom the Software is
  13. # furnished to do so, subject to the following conditions:
  14. #
  15. # The above copyright notice and this permission notice shall be included in all
  16. # copies or substantial portions of the Software.
  17. #
  18. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  24. # SOFTWARE.
  25. from __future__ import absolute_import
  26. from __future__ import division
  27. from __future__ import print_function
  28. import tensorflow as tf
  29. import numpy as np
  30. import argparse
  31. import facenet
  32. import lfw
  33. import matplotlib.pyplot as plt
  34. from scipy import misc
  35. import os
  36. import sys
  37. import math
  38. def main(args):
  39. pairs = lfw.read_pairs(os.path.expanduser(args.lfw_pairs))
  40. paths, actual_issame = lfw.get_paths(os.path.expanduser(args.lfw_dir), pairs)
  41. result_dir = '../data/'
  42. plt.ioff() # Disable interactive plotting mode
  43. with tf.Graph().as_default():
  44. with tf.Session() as sess:
  45. # Load the model
  46. print('Loading model "%s"' % args.model_file)
  47. facenet.load_model(args.model_file)
  48. # Get input and output tensors
  49. images_placeholder = tf.get_default_graph().get_tensor_by_name("input:0")
  50. phase_train_placeholder = tf.get_default_graph().get_tensor_by_name("phase_train:0")
  51. embeddings = tf.get_default_graph().get_tensor_by_name("embeddings:0")
  52. image_size = int(images_placeholder.get_shape()[1])
  53. # Run test on LFW to check accuracy for different horizontal/vertical translations of input images
  54. if args.nrof_offsets>0:
  55. step = 3
  56. offsets = np.asarray([x*step for x in range(-args.nrof_offsets//2+1, args.nrof_offsets//2+1)])
  57. horizontal_offset_accuracy = [None] * len(offsets)
  58. for idx, offset in enumerate(offsets):
  59. accuracy = evaluate_accuracy(sess, images_placeholder, phase_train_placeholder, image_size, embeddings,
  60. paths, actual_issame, translate_images, (offset,0), 60, args.orig_image_size, args.seed)
  61. print('Hoffset: %1.3f Accuracy: %1.3f+-%1.3f' % (offset, np.mean(accuracy), np.std(accuracy)))
  62. horizontal_offset_accuracy[idx] = np.mean(accuracy)
  63. vertical_offset_accuracy = [None] * len(offsets)
  64. for idx, offset in enumerate(offsets):
  65. accuracy = evaluate_accuracy(sess, images_placeholder, phase_train_placeholder, image_size, embeddings,
  66. paths, actual_issame, translate_images, (0,offset), 60, args.orig_image_size, args.seed)
  67. print('Voffset: %1.3f Accuracy: %1.3f+-%1.3f' % (offset, np.mean(accuracy), np.std(accuracy)))
  68. vertical_offset_accuracy[idx] = np.mean(accuracy)
  69. fig = plt.figure(1)
  70. plt.plot(offsets, horizontal_offset_accuracy, label='Horizontal')
  71. plt.plot(offsets, vertical_offset_accuracy, label='Vertical')
  72. plt.legend()
  73. plt.grid(True)
  74. plt.title('Translation invariance on LFW')
  75. plt.xlabel('Offset [pixels]')
  76. plt.ylabel('Accuracy')
  77. # plt.show()
  78. print('Saving results in %s' % result_dir)
  79. fig.savefig(os.path.join(result_dir, 'invariance_translation.png'))
  80. save_result(offsets, horizontal_offset_accuracy, os.path.join(result_dir, 'invariance_translation_horizontal.txt'))
  81. save_result(offsets, vertical_offset_accuracy, os.path.join(result_dir, 'invariance_translation_vertical.txt'))
  82. # Run test on LFW to check accuracy for different rotation of input images
  83. if args.nrof_angles>0:
  84. step = 3
  85. angles = np.asarray([x*step for x in range(-args.nrof_offsets//2+1, args.nrof_offsets//2+1)])
  86. rotation_accuracy = [None] * len(angles)
  87. for idx, angle in enumerate(angles):
  88. accuracy = evaluate_accuracy(sess, images_placeholder, phase_train_placeholder, image_size, embeddings,
  89. paths, actual_issame, rotate_images, angle, 60, args.orig_image_size, args.seed)
  90. print('Angle: %1.3f Accuracy: %1.3f+-%1.3f' % (angle, np.mean(accuracy), np.std(accuracy)))
  91. rotation_accuracy[idx] = np.mean(accuracy)
  92. fig = plt.figure(2)
  93. plt.plot(angles, rotation_accuracy)
  94. plt.grid(True)
  95. plt.title('Rotation invariance on LFW')
  96. plt.xlabel('Angle [deg]')
  97. plt.ylabel('Accuracy')
  98. # plt.show()
  99. print('Saving results in %s' % result_dir)
  100. fig.savefig(os.path.join(result_dir, 'invariance_rotation.png'))
  101. save_result(angles, rotation_accuracy, os.path.join(result_dir, 'invariance_rotation.txt'))
  102. # Run test on LFW to check accuracy for different scaling of input images
  103. if args.nrof_scales>0:
  104. step = 0.05
  105. scales = np.asarray([x*step+1 for x in range(-args.nrof_offsets//2+1, args.nrof_offsets//2+1)])
  106. scale_accuracy = [None] * len(scales)
  107. for scale_idx, scale in enumerate(scales):
  108. accuracy = evaluate_accuracy(sess, images_placeholder, phase_train_placeholder, image_size, embeddings,
  109. paths, actual_issame, scale_images, scale, 60, args.orig_image_size, args.seed)
  110. print('Scale: %1.3f Accuracy: %1.3f+-%1.3f' % (scale, np.mean(accuracy), np.std(accuracy)))
  111. scale_accuracy[scale_idx] = np.mean(accuracy)
  112. fig = plt.figure(3)
  113. plt.plot(scales, scale_accuracy)
  114. plt.grid(True)
  115. plt.title('Scale invariance on LFW')
  116. plt.xlabel('Scale')
  117. plt.ylabel('Accuracy')
  118. # plt.show()
  119. print('Saving results in %s' % result_dir)
  120. fig.savefig(os.path.join(result_dir, 'invariance_scale.png'))
  121. save_result(scales, scale_accuracy, os.path.join(result_dir, 'invariance_scale.txt'))
  122. def save_result(aug, acc, filename):
  123. with open(filename, "w") as f:
  124. for i in range(aug.size):
  125. f.write('%6.4f %6.4f\n' % (aug[i], acc[i]))
  126. def evaluate_accuracy(sess, images_placeholder, phase_train_placeholder, image_size, embeddings,
  127. paths, actual_issame, augment_images, aug_value, batch_size, orig_image_size, seed):
  128. nrof_images = len(paths)
  129. nrof_batches = int(math.ceil(1.0*nrof_images / batch_size))
  130. emb_list = []
  131. for i in range(nrof_batches):
  132. start_index = i*batch_size
  133. end_index = min((i+1)*batch_size, nrof_images)
  134. paths_batch = paths[start_index:end_index]
  135. images = facenet.load_data(paths_batch, False, False, orig_image_size)
  136. images_aug = augment_images(images, aug_value, image_size)
  137. feed_dict = { images_placeholder: images_aug, phase_train_placeholder: False }
  138. emb_list += sess.run([embeddings], feed_dict=feed_dict)
  139. emb_array = np.vstack(emb_list) # Stack the embeddings to a nrof_examples_per_epoch x 128 matrix
  140. thresholds = np.arange(0, 4, 0.01)
  141. embeddings1 = emb_array[0::2]
  142. embeddings2 = emb_array[1::2]
  143. _, _, accuracy = facenet.calculate_roc(thresholds, embeddings1, embeddings2, np.asarray(actual_issame), seed)
  144. return accuracy
  145. def scale_images(images, scale, image_size):
  146. images_scale_list = [None] * images.shape[0]
  147. for i in range(images.shape[0]):
  148. images_scale_list[i] = misc.imresize(images[i,:,:,:], scale)
  149. images_scale = np.stack(images_scale_list,axis=0)
  150. sz1 = images_scale.shape[1]/2
  151. sz2 = image_size/2
  152. images_crop = images_scale[:,(sz1-sz2):(sz1+sz2),(sz1-sz2):(sz1+sz2),:]
  153. return images_crop
  154. def rotate_images(images, angle, image_size):
  155. images_list = [None] * images.shape[0]
  156. for i in range(images.shape[0]):
  157. images_list[i] = misc.imrotate(images[i,:,:,:], angle)
  158. images_rot = np.stack(images_list,axis=0)
  159. sz1 = images_rot.shape[1]/2
  160. sz2 = image_size/2
  161. images_crop = images_rot[:,(sz1-sz2):(sz1+sz2),(sz1-sz2):(sz1+sz2),:]
  162. return images_crop
  163. def translate_images(images, offset, image_size):
  164. h, v = offset
  165. sz1 = images.shape[1]/2
  166. sz2 = image_size/2
  167. images_crop = images[:,(sz1-sz2+v):(sz1+sz2+v),(sz1-sz2+h):(sz1+sz2+h),:]
  168. return images_crop
  169. def parse_arguments(argv):
  170. parser = argparse.ArgumentParser()
  171. parser.add_argument('--model_file', type=str,
  172. help='File containing the model parameters as well as the model metagraph (with extension ".meta")',
  173. default='~/models/facenet/20160514-234418/model.ckpt-500000')
  174. parser.add_argument('--nrof_offsets', type=int,
  175. help='Number of horizontal and vertical offsets to evaluate.', default=21)
  176. parser.add_argument('--nrof_angles', type=int,
  177. help='Number of angles to evaluate.', default=21)
  178. parser.add_argument('--nrof_scales', type=int,
  179. help='Number of scales to evaluate.', default=21)
  180. parser.add_argument('--lfw_pairs', type=str,
  181. help='The file containing the pairs to use for validation.', default='../data/pairs.txt')
  182. parser.add_argument('--lfw_dir', type=str,
  183. help='Path to the data directory containing aligned face patches.', default='~/datasets/lfw/lfw_realigned/')
  184. parser.add_argument('--orig_image_size', type=int,
  185. help='Image size (height, width) in pixels of the original (uncropped/unscaled) images.', default=224)
  186. parser.add_argument('--lfw_nrof_folds', type=int,
  187. help='Number of folds to use for cross validation. Mainly used for testing.', default=10)
  188. parser.add_argument('--seed', type=int,
  189. help='Random seed.', default=666)
  190. return parser.parse_args(argv)
  191. if __name__ == '__main__':
  192. main(parse_arguments(sys.argv[1:]))