cluster.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. # MIT License
  2. #
  3. # Copyright (c) 2017 PXL University College
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a copy
  6. # of this software and associated documentation files (the "Software"), to deal
  7. # in the Software without restriction, including without limitation the rights
  8. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. # copies of the Software, and to permit persons to whom the Software is
  10. # furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in all
  13. # copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. # SOFTWARE.
  22. # Clusters similar faces from input folder together in folders based on euclidean distance matrix
  23. from __future__ import absolute_import
  24. from __future__ import division
  25. from __future__ import print_function
  26. from scipy import misc
  27. import tensorflow as tf
  28. import numpy as np
  29. import os
  30. import sys
  31. import argparse
  32. import facenet
  33. import align.detect_face
  34. from sklearn.cluster import DBSCAN
  35. def main(args):
  36. pnet, rnet, onet = create_network_face_detection(args.gpu_memory_fraction)
  37. with tf.Graph().as_default():
  38. with tf.Session() as sess:
  39. facenet.load_model(args.model)
  40. image_list = load_images_from_folder(args.data_dir)
  41. images = align_data(image_list, args.image_size, args.margin, pnet, rnet, onet)
  42. images_placeholder = sess.graph.get_tensor_by_name("input:0")
  43. embeddings = sess.graph.get_tensor_by_name("embeddings:0")
  44. phase_train_placeholder = sess.graph.get_tensor_by_name("phase_train:0")
  45. feed_dict = {images_placeholder: images, phase_train_placeholder: False}
  46. emb = sess.run(embeddings, feed_dict=feed_dict)
  47. nrof_images = len(images)
  48. matrix = np.zeros((nrof_images, nrof_images))
  49. print('')
  50. # Print distance matrix
  51. print('Distance matrix')
  52. print(' ', end='')
  53. for i in range(nrof_images):
  54. print(' %1d ' % i, end='')
  55. print('')
  56. for i in range(nrof_images):
  57. print('%1d ' % i, end='')
  58. for j in range(nrof_images):
  59. dist = np.sqrt(np.sum(np.square(np.subtract(emb[i, :], emb[j, :]))))
  60. matrix[i][j] = dist
  61. print(' %1.4f ' % dist, end='')
  62. print('')
  63. print('')
  64. # DBSCAN is the only algorithm that doesn't require the number of clusters to be defined.
  65. db = DBSCAN(eps=args.cluster_threshold, min_samples=args.min_cluster_size, metric='precomputed')
  66. db.fit(matrix)
  67. labels = db.labels_
  68. # get number of clusters
  69. no_clusters = len(set(labels)) - (1 if -1 in labels else 0)
  70. print('No of clusters:', no_clusters)
  71. if no_clusters > 0:
  72. if args.largest_cluster_only:
  73. largest_cluster = 0
  74. for i in range(no_clusters):
  75. print('Cluster {}: {}'.format(i, np.nonzero(labels == i)[0]))
  76. if len(np.nonzero(labels == i)[0]) > len(np.nonzero(labels == largest_cluster)[0]):
  77. largest_cluster = i
  78. print('Saving largest cluster (Cluster: {})'.format(largest_cluster))
  79. cnt = 1
  80. for i in np.nonzero(labels == largest_cluster)[0]:
  81. misc.imsave(os.path.join(args.out_dir, str(cnt) + '.png'), images[i])
  82. cnt += 1
  83. else:
  84. print('Saving all clusters')
  85. for i in range(no_clusters):
  86. cnt = 1
  87. print('Cluster {}: {}'.format(i, np.nonzero(labels == i)[0]))
  88. path = os.path.join(args.out_dir, str(i))
  89. if not os.path.exists(path):
  90. os.makedirs(path)
  91. for j in np.nonzero(labels == i)[0]:
  92. misc.imsave(os.path.join(path, str(cnt) + '.png'), images[j])
  93. cnt += 1
  94. else:
  95. for j in np.nonzero(labels == i)[0]:
  96. misc.imsave(os.path.join(path, str(cnt) + '.png'), images[j])
  97. cnt += 1
  98. def align_data(image_list, image_size, margin, pnet, rnet, onet):
  99. minsize = 20 # minimum size of face
  100. threshold = [0.6, 0.7, 0.7] # three steps's threshold
  101. factor = 0.709 # scale factor
  102. img_list = []
  103. for x in xrange(len(image_list)):
  104. img_size = np.asarray(image_list[x].shape)[0:2]
  105. bounding_boxes, _ = align.detect_face.detect_face(image_list[x], minsize, pnet, rnet, onet, threshold, factor)
  106. nrof_samples = len(bounding_boxes)
  107. if nrof_samples > 0:
  108. for i in xrange(nrof_samples):
  109. if bounding_boxes[i][4] > 0.95:
  110. det = np.squeeze(bounding_boxes[i, 0:4])
  111. bb = np.zeros(4, dtype=np.int32)
  112. bb[0] = np.maximum(det[0] - margin / 2, 0)
  113. bb[1] = np.maximum(det[1] - margin / 2, 0)
  114. bb[2] = np.minimum(det[2] + margin / 2, img_size[1])
  115. bb[3] = np.minimum(det[3] + margin / 2, img_size[0])
  116. cropped = image_list[x][bb[1]:bb[3], bb[0]:bb[2], :]
  117. aligned = misc.imresize(cropped, (image_size, image_size), interp='bilinear')
  118. prewhitened = facenet.prewhiten(aligned)
  119. img_list.append(prewhitened)
  120. if len(img_list) > 0:
  121. images = np.stack(img_list)
  122. return images
  123. else:
  124. return None
  125. def create_network_face_detection(gpu_memory_fraction):
  126. with tf.Graph().as_default():
  127. gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_memory_fraction)
  128. sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))
  129. with sess.as_default():
  130. pnet, rnet, onet = align.detect_face.create_mtcnn(sess, None)
  131. return pnet, rnet, onet
  132. def load_images_from_folder(folder):
  133. images = []
  134. for filename in os.listdir(folder):
  135. img = misc.imread(os.path.join(folder, filename))
  136. if img is not None:
  137. images.append(img)
  138. return images
  139. def parse_arguments(argv):
  140. parser = argparse.ArgumentParser()
  141. parser.add_argument('model', type=str,
  142. help='Either a directory containing the meta_file and ckpt_file or a model protobuf (.pb) file')
  143. parser.add_argument('data_dir', type=str,
  144. help='The directory containing the images to cluster into folders.')
  145. parser.add_argument('out_dir', type=str,
  146. help='The output directory where the image clusters will be saved.')
  147. parser.add_argument('--image_size', type=int,
  148. help='Image size (height, width) in pixels.', default=160)
  149. parser.add_argument('--margin', type=int,
  150. help='Margin for the crop around the bounding box (height, width) in pixels.', default=44)
  151. parser.add_argument('--min_cluster_size', type=int,
  152. help='The minimum amount of pictures required for a cluster.', default=1)
  153. parser.add_argument('--cluster_threshold', type=float,
  154. help='The minimum distance for faces to be in the same cluster', default=1.0)
  155. parser.add_argument('--largest_cluster_only', action='store_true',
  156. help='This argument will make that only the biggest cluster is saved.')
  157. parser.add_argument('--gpu_memory_fraction', type=float,
  158. help='Upper bound on the amount of GPU memory that will be used by the process.', default=1.0)
  159. return parser.parse_args(argv)
  160. if __name__ == '__main__':
  161. main(parse_arguments(sys.argv[1:]))