Ejemplo n.º 1
0
def main(args):
    with tf.Graph().as_default():
        with tf.Session() as sess:
            # Load the model metagraph and checkpoint
            print('Model directory: %s' % args.model_dir)
            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)

            model_dir_exp = os.path.expanduser(args.model_dir)
            saver = tf.train.import_meta_graph(os.path.join(
                model_dir_exp, meta_file),
                                               clear_devices=True)
            tf.get_default_session().run(tf.global_variables_initializer())
            tf.get_default_session().run(tf.local_variables_initializer())
            saver.restore(tf.get_default_session(),
                          os.path.join(model_dir_exp, ckpt_file))

            # Retrieve the protobuf graph definition and fix the batch norm nodes
            input_graph_def = sess.graph.as_graph_def()

            # Freeze the graph def
            output_graph_def = freeze_graph_def(sess, input_graph_def,
                                                'embeddings')

        # Serialize and dump the output graph to the filesystem
        with tf.gfile.GFile(args.output_file, 'wb') as f:
            f.write(output_graph_def.SerializeToString())
        print("%d ops in the final graph: %s" %
              (len(output_graph_def.node), args.output_file))
Ejemplo n.º 2
0
def main(args):

    with tf.Graph().as_default():

        with tf.Session() as sess:

            # Get the paths for the images
            paths = []
            for imagePath in os.listdir(args.face_dir):
                imagePath = os.path.join(args.face_dir, imagePath)
                if os.path.isfile(imagePath):
                    print(imagePath)
                    paths.append(imagePath)

            # Load the model
            print('Model directory: %s' % args.model_dir)
            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)
            facenet.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]
            embedding_size = embeddings.get_shape()[1]

            # Run forward pass to calculate embeddings
            print('Runnning forward pass on images')
            batch_size = args.batch_size
            nrof_images = len(paths)
            nrof_batches = int(math.ceil(1.0 * nrof_images / batch_size))
            emb_array = np.zeros((nrof_images, embedding_size))
            for i in range(nrof_batches):
                start_index = i * batch_size
                end_index = min((i + 1) * batch_size, nrof_images)
                paths_batch = paths[start_index:end_index]
                images = facenet.load_data(paths_batch, True, True, image_size)
                feed_dict = {
                    images_placeholder: images,
                    phase_train_placeholder: False
                }
                emb_array[start_index:end_index, :] = sess.run(
                    embeddings, feed_dict=feed_dict)

            # Save embeddings to disk
            for i in range(nrof_images):
                np.save(paths[i], emb_array[i, :], allow_pickle=False)
Ejemplo n.º 3
0
    def load_model_facenet(self):
        """Loads the facenet model"""

        print("Classifier: loading model facenet ...")

        self.model_facenet_g = tf.Graph()
        self.model_facenet_g.as_default().__enter__()
        self.model_facenet_session_tf = tf.Session()
        self.model_facenet_session_tf.__enter__()

        # Load the model
        print('Model directory: %s' % configuration.FACEEMBEDDING_MODEL_DIR)

        meta_file, ckpt_file = facenet.get_model_filenames(
            os.path.expanduser(configuration.FACEEMBEDDING_MODEL_DIR))

        print('Metagraph file: %s' % meta_file)
        print('Checkpoint file: %s' % ckpt_file)
        facenet.load_model(configuration.FACEEMBEDDING_MODEL_DIR, meta_file,
                           ckpt_file)

        # Get input and output tensors

        self.model_facenet_images_placeholder = tf.get_default_graph(
        ).get_tensor_by_name("input:0")
        self.model_facenet_embeddings = tf.get_default_graph(
        ).get_tensor_by_name("embeddings:0")
        self.model_facenet_phase_train_placeholder = tf.get_default_graph(
        ).get_tensor_by_name("phase_train:0")

        self.model_facenet_image_size = self.model_facenet_images_placeholder.get_shape(
        )[1]
        self.model_facenet_embedding_size = self.model_facenet_embeddings.get_shape(
        )[1]

        print("Classifier: loading model facenet ... OK")
Ejemplo n.º 4
0
import os
import time
import argparse
import src.facenet as facenet
from src.align import detect_face
import csv
from os.path import isdir, isfile
import random
import logging
from settings import MODEL_DIR, IMG_PATH
from util.logger import create_logger

logger = create_logger('model', logging.DEBUG, 'model.log')

logger.info('Model directory: %s' % MODEL_DIR)
meta_file, ckpt_file = facenet.get_model_filenames(
    os.path.expanduser(MODEL_DIR))
logger.info('Metagraph file: %s' % meta_file)
logger.info('Checkpoint file: %s' % ckpt_file)

time_check_1 = time.time()
# set a facenet session
facenet_session = tf.Session()
facenet.load_model_with_session(facenet_session, MODEL_DIR, meta_file,
                                ckpt_file)
time_check_2 = time.time()
logger.info("Loading facenet taken {} seconds".format(time_check_2 -
                                                      time_check_1))

# set a session for mtcnn face detection neural network
logger.info(
    'Creating Multi-task Cascaded Convolutional Neural Networks and loading parameters'
Ejemplo n.º 5
0
def main(args):
    """ Main

    Given a list of images, save out facial encoding data files and copy
    images into folders of face clusters.

    """
    from os.path import join, basename, exists
    from os import makedirs
    import numpy as np
    import shutil
    import sys

    if not exists(args.output):
        makedirs(args.output)

    with tf.Graph().as_default():
        with tf.Session() as sess:
            image_paths = get_onedir(args.input)
            #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')

            nrof_images = len(image_paths)
            nrof_batches = int(math.ceil(1.0 * nrof_images / args.batch_size))
            emb_array = np.zeros((nrof_images, embedding_size))
            facial_encodings = compute_facial_encodings(
                sess, images_placeholder, embeddings, phase_train_placeholder,
                image_size, 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
                cluster_dir = join(args.output, str(idx))
                if not exists(cluster_dir):
                    makedirs(cluster_dir)
                for path in cluster:
                    shutil.copy(path, join(cluster_dir, basename(path)))