align_dataset.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. """Performs face alignment and stores face thumbnails in the output directory."""
  2. # MIT License
  3. #
  4. # Copyright (c) 2016 David Sandberg
  5. #
  6. # Permission is hereby granted, free of charge, to any person obtaining a copy
  7. # of this software and associated documentation files (the "Software"), to deal
  8. # in the Software without restriction, including without limitation the rights
  9. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. # copies of the Software, and to permit persons to whom the Software is
  11. # furnished to do so, subject to the following conditions:
  12. #
  13. # The above copyright notice and this permission notice shall be included in all
  14. # copies or substantial portions of the Software.
  15. #
  16. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  22. # SOFTWARE.
  23. from __future__ import absolute_import
  24. from __future__ import division
  25. from __future__ import print_function
  26. from scipy import misc
  27. import sys
  28. import os
  29. import argparse
  30. import random
  31. import align_dlib # @UnresolvedImport
  32. import facenet
  33. def main(args):
  34. align = align_dlib.AlignDlib(os.path.expanduser(args.dlib_face_predictor))
  35. landmarkIndices = align_dlib.AlignDlib.OUTER_EYES_AND_NOSE
  36. output_dir = os.path.expanduser(args.output_dir)
  37. if not os.path.exists(output_dir):
  38. os.makedirs(output_dir)
  39. # Store some git revision info in a text file in the log directory
  40. src_path,_ = os.path.split(os.path.realpath(__file__))
  41. facenet.store_revision_info(src_path, output_dir, ' '.join(sys.argv))
  42. dataset = facenet.get_dataset(args.input_dir)
  43. random.shuffle(dataset)
  44. # Scale the image such that the face fills the frame when cropped to crop_size
  45. scale = float(args.face_size) / args.image_size
  46. nrof_images_total = 0
  47. nrof_prealigned_images = 0
  48. nrof_successfully_aligned = 0
  49. for cls in dataset:
  50. output_class_dir = os.path.join(output_dir, cls.name)
  51. if not os.path.exists(output_class_dir):
  52. os.makedirs(output_class_dir)
  53. random.shuffle(cls.image_paths)
  54. for image_path in cls.image_paths:
  55. nrof_images_total += 1
  56. filename = os.path.splitext(os.path.split(image_path)[1])[0]
  57. output_filename = os.path.join(output_class_dir, filename+'.png')
  58. if not os.path.exists(output_filename):
  59. try:
  60. img = misc.imread(image_path)
  61. except (IOError, ValueError, IndexError) as e:
  62. errorMessage = '{}: {}'.format(image_path, e)
  63. print(errorMessage)
  64. else:
  65. if img.ndim == 2:
  66. img = facenet.to_rgb(img)
  67. if args.use_center_crop:
  68. scaled = misc.imresize(img, args.prealigned_scale, interp='bilinear')
  69. sz1 = scaled.shape[1]/2
  70. sz2 = args.image_size/2
  71. aligned = scaled[(sz1-sz2):(sz1+sz2),(sz1-sz2):(sz1+sz2),:]
  72. else:
  73. aligned = align.align(args.image_size, img, landmarkIndices=landmarkIndices,
  74. skipMulti=False, scale=scale)
  75. if aligned is not None:
  76. print(image_path)
  77. nrof_successfully_aligned += 1
  78. misc.imsave(output_filename, aligned)
  79. elif args.prealigned_dir:
  80. # Face detection failed. Use center crop from pre-aligned dataset
  81. class_name = os.path.split(output_class_dir)[1]
  82. image_path_without_ext = os.path.join(os.path.expanduser(args.prealigned_dir),
  83. class_name, filename)
  84. # Find the extension of the image
  85. exts = ('jpg', 'png')
  86. for ext in exts:
  87. temp_path = image_path_without_ext + '.' + ext
  88. image_path = ''
  89. if os.path.exists(temp_path):
  90. image_path = temp_path
  91. break
  92. try:
  93. img = misc.imread(image_path)
  94. except (IOError, ValueError, IndexError) as e:
  95. errorMessage = '{}: {}'.format(image_path, e)
  96. print(errorMessage)
  97. else:
  98. scaled = misc.imresize(img, args.prealigned_scale, interp='bilinear')
  99. sz1 = scaled.shape[1]/2
  100. sz2 = args.image_size/2
  101. cropped = scaled[(sz1-sz2):(sz1+sz2),(sz1-sz2):(sz1+sz2),:]
  102. print(image_path)
  103. nrof_prealigned_images += 1
  104. misc.imsave(output_filename, cropped)
  105. else:
  106. print('Unable to align "%s"' % image_path)
  107. print('Total number of images: %d' % nrof_images_total)
  108. print('Number of successfully aligned images: %d' % nrof_successfully_aligned)
  109. print('Number of pre-aligned images: %d' % nrof_prealigned_images)
  110. def parse_arguments(argv):
  111. parser = argparse.ArgumentParser()
  112. parser.add_argument('input_dir', type=str, help='Directory with unaligned images.')
  113. parser.add_argument('output_dir', type=str, help='Directory with aligned face thumbnails.')
  114. parser.add_argument('--dlib_face_predictor', type=str,
  115. help='File containing the dlib face predictor.', default='../data/shape_predictor_68_face_landmarks.dat')
  116. parser.add_argument('--image_size', type=int,
  117. help='Image size (height, width) in pixels.', default=110)
  118. parser.add_argument('--face_size', type=int,
  119. help='Size of the face thumbnail (height, width) in pixels.', default=96)
  120. parser.add_argument('--use_center_crop',
  121. help='Use the center crop of the original image after scaling the image using prealigned_scale.', action='store_true')
  122. parser.add_argument('--prealigned_dir', type=str,
  123. help='Replace image with a pre-aligned version when face detection fails.', default='')
  124. parser.add_argument('--prealigned_scale', type=float,
  125. help='The amount of scaling to apply to prealigned images before taking the center crop.', default=0.87)
  126. return parser.parse_args(argv)
  127. if __name__ == '__main__':
  128. main(parse_arguments(sys.argv[1:]))