Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow Pickle in detect_face #1022

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion contributed/batch_represent.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,8 @@
import facenet
import numpy as np
from sklearn.datasets import load_files
import tensorflow as tf
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
from six.moves import xrange

def main(args):
Expand Down
3 changes: 2 additions & 1 deletion contributed/cluster.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@
from __future__ import print_function

from scipy import misc
import tensorflow as tf
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import numpy as np
import os
import sys
Expand Down
19 changes: 10 additions & 9 deletions contributed/clustering.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
""" Face Cluster """
import tensorflow as tf
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import numpy as np
import importlib
import argparse
Expand Down Expand Up @@ -190,8 +191,8 @@ def get_onedir(paths):
for x in image_paths:
if os.path.getsize(x)>0:
dataset.append(x)
return dataset

return dataset


def main(args):
Expand All @@ -216,22 +217,22 @@ def main(args):
#image_list, label_list = facenet.get_image_paths_and_labels(train_set)

meta_file, ckpt_file = facenet.get_model_filenames(os.path.expanduser(args.model_dir))

print('Metagraph file: %s' % meta_file)
print('Checkpoint file: %s' % ckpt_file)
load_model(args.model_dir, meta_file, ckpt_file)

# Get input and output tensors
images_placeholder = tf.get_default_graph().get_tensor_by_name("input:0")
embeddings = tf.get_default_graph().get_tensor_by_name("embeddings:0")
phase_train_placeholder = tf.get_default_graph().get_tensor_by_name("phase_train:0")

image_size = images_placeholder.get_shape()[1]
print("image_size:",image_size)
embedding_size = embeddings.get_shape()[1]

# Run forward pass to calculate embeddings
print('Runnning forward pass on images')
print('Runnning forward pass on images')

nrof_images = len(image_paths)
nrof_batches = int(math.ceil(1.0*nrof_images / args.batch_size))
Expand All @@ -240,7 +241,7 @@ def main(args):
embedding_size,nrof_images,nrof_batches,emb_array,args.batch_size,image_paths)
sorted_clusters = cluster_facial_encodings(facial_encodings)
num_cluster = len(sorted_clusters)

# Copy image files to cluster folders
for idx, cluster in enumerate(sorted_clusters):
#save all the cluster
Expand Down
3 changes: 2 additions & 1 deletion contributed/export_embeddings.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@

import time
from scipy import misc
import tensorflow as tf
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import numpy as np
import sys
import os
Expand Down
3 changes: 2 additions & 1 deletion contributed/face.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@

import cv2
import numpy as np
import tensorflow as tf
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
from scipy import misc

import align.detect_face
Expand Down
29 changes: 15 additions & 14 deletions contributed/predict.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@
#----------------------------------------------------


import tensorflow as tf
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import numpy as np
import argparse
import facenet
Expand All @@ -43,12 +44,12 @@
from six.moves import xrange

def main(args):

images, cout_per_image, nrof_samples = load_and_align_data(args.image_files,args.image_size, args.margin, args.gpu_memory_fraction)
with tf.Graph().as_default():

with tf.Session() as sess:

# Load the model
facenet.load_model(args.model)
# Get input and output tensors
Expand All @@ -66,36 +67,36 @@ def main(args):
predictions = model.predict_proba(emb)
best_class_indices = np.argmax(predictions, axis=1)
best_class_probabilities = predictions[np.arange(len(best_class_indices)), best_class_indices]
k=0
#print predictions
k=0
#print predictions
for i in range(nrof_samples):
print("\npeople in image %s :" %(args.image_files[i]))
for j in range(cout_per_image[i]):
print('%s: %.3f' % (class_names[best_class_indices[k]], best_class_probabilities[k]))
k+=1

def load_and_align_data(image_paths, image_size, margin, gpu_memory_fraction):

minsize = 20 # minimum size of face
threshold = [ 0.6, 0.7, 0.7 ] # three steps's threshold
factor = 0.709 # scale factor

print('Creating networks and loading parameters')
with tf.Graph().as_default():
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_memory_fraction)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))
with sess.as_default():
pnet, rnet, onet = align.detect_face.create_mtcnn(sess, None)

nrof_samples = len(image_paths)
img_list = []
img_list = []
count_per_image = []
for i in xrange(nrof_samples):
img = misc.imread(os.path.expanduser(image_paths[i]))
img_size = np.asarray(img.shape)[0:2]
bounding_boxes, _ = align.detect_face.detect_face(img, minsize, pnet, rnet, onet, threshold, factor)
count_per_image.append(len(bounding_boxes))
for j in range(len(bounding_boxes)):
for j in range(len(bounding_boxes)):
det = np.squeeze(bounding_boxes[j,0:4])
bb = np.zeros(4, dtype=np.int32)
bb[0] = np.maximum(det[0]-margin/2, 0)
Expand All @@ -105,17 +106,17 @@ def load_and_align_data(image_paths, image_size, margin, gpu_memory_fraction):
cropped = img[bb[1]:bb[3],bb[0]:bb[2],:]
aligned = misc.imresize(cropped, (image_size, image_size), interp='bilinear')
prewhitened = facenet.prewhiten(aligned)
img_list.append(prewhitened)
img_list.append(prewhitened)
images = np.stack(img_list)
return images, count_per_image, nrof_samples

def parse_arguments(argv):
parser = argparse.ArgumentParser()
parser.add_argument('image_files', type=str, nargs='+', help='Path(s) of the image(s)')
parser.add_argument('model', type=str,
parser.add_argument('model', type=str,
help='Could be either a directory containing the meta_file and ckpt_file or a model protobuf (.pb) file')
parser.add_argument('classifier_filename',
help='Classifier model file name as a pickle (.pkl) file. ' +
parser.add_argument('classifier_filename',
help='Classifier model file name as a pickle (.pkl) file. ' +
'For training this is the output and for classification this is an input.')
parser.add_argument('--image_size', type=int,
help='Image size (height, width) in pixels.', default=160)
Expand Down
6 changes: 3 additions & 3 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
tensorflow==1.7
scipy
tensorflow-gpu == 2.2.3
scipy == 1.2.0
scikit-learn
opencv-python
opencv-python-headless == 3.4.14.53
h5py
matplotlib
Pillow
Expand Down
29 changes: 15 additions & 14 deletions src/align/align_dataset_mtcnn.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
"""Performs face alignment and stores face thumbnails in the output directory."""
# MIT License
#
#
# Copyright (c) 2016 David Sandberg
#
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
Expand All @@ -29,7 +29,8 @@
import sys
import os
import argparse
import tensorflow as tf
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import numpy as np
import facenet
import align.detect_face
Expand All @@ -45,23 +46,23 @@ def main(args):
src_path,_ = os.path.split(os.path.realpath(__file__))
facenet.store_revision_info(src_path, output_dir, ' '.join(sys.argv))
dataset = facenet.get_dataset(args.input_dir)

print('Creating networks and loading parameters')

with tf.Graph().as_default():
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=args.gpu_memory_fraction)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))
with sess.as_default():
pnet, rnet, onet = align.detect_face.create_mtcnn(sess, None)

minsize = 20 # minimum size of face
threshold = [ 0.6, 0.7, 0.7 ] # three steps's threshold
factor = 0.709 # scale factor

# Add a random key to the filename to allow alignment using multiple processes
random_key = np.random.randint(0, high=99999)
bounding_boxes_filename = os.path.join(output_dir, 'bounding_boxes_%05d.txt' % random_key)

with open(bounding_boxes_filename, "w") as text_file:
nrof_images_total = 0
nrof_successfully_aligned = 0
Expand Down Expand Up @@ -92,7 +93,7 @@ def main(args):
if img.ndim == 2:
img = facenet.to_rgb(img)
img = img[:,:,0:3]

bounding_boxes, _ = align.detect_face.detect_face(img, minsize, pnet, rnet, onet, threshold, factor)
nrof_faces = bounding_boxes.shape[0]
if nrof_faces>0:
Expand Down Expand Up @@ -133,21 +134,21 @@ def main(args):
else:
print('Unable to align "%s"' % image_path)
text_file.write('%s\n' % (output_filename))

print('Total number of images: %d' % nrof_images_total)
print('Number of successfully aligned images: %d' % nrof_successfully_aligned)


def parse_arguments(argv):
parser = argparse.ArgumentParser()

parser.add_argument('input_dir', type=str, help='Directory with unaligned images.')
parser.add_argument('output_dir', type=str, help='Directory with aligned face thumbnails.')
parser.add_argument('--image_size', type=int,
help='Image size (height, width) in pixels.', default=182)
parser.add_argument('--margin', type=int,
help='Margin for the crop around the bounding box (height, width) in pixels.', default=44)
parser.add_argument('--random_order',
parser.add_argument('--random_order',
help='Shuffles the order of images to enable alignment using multiple processes.', action='store_true')
parser.add_argument('--gpu_memory_fraction', type=float,
help='Upper bound on the amount of GPU memory that will be used by the process.', default=1.0)
Expand Down
Loading