111

# -*- coding: utf-8 -*-
# CLASSWORLDS
# 2018/11/25

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import copy
import os

import numpy as np
import tensorflow as tf
from facenet.src import align
from facenet.src import facenet
from facenet.src.align import detect_face
from scipy import misc

tf.Graph().as_default()
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=1.0)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))
facenet.load_model("model/20180408-102900.pb")
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")

pnet, rnet, onet = align.detect_face.create_mtcnn(sess, None)

print("model loaded successfully.")



def compute(image_files,image_size=160,margin=44):
    images = load_and_align_data(image_files, image_size, margin)
    feed_dict = {images_placeholder: images, phase_train_placeholder: False}
    emb = sess.run(embeddings, feed_dict=feed_dict)
    return emb[0,:]




def load_and_align_data(image_paths, image_size, margin):
    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')

    tmp_image_paths = copy.copy(image_paths)
    img_list = []
    for image in tmp_image_paths:
        img = misc.imread(os.path.expanduser(image), mode='RGB')
        img_size = np.asarray(img.shape)[0:2]
        bounding_boxes, _ = align.detect_face.detect_face(img, minsize, pnet, rnet, onet, threshold, factor)
        if len(bounding_boxes) < 1:
            image_paths.remove(image)
            print("can't detect face, remove ", image)
            continue
        det = np.squeeze(bounding_boxes[0, 0:4])
        bb = np.zeros(4, dtype=np.int32)
        bb[0] = np.maximum(det[0] - margin / 2, 0)
        bb[1] = np.maximum(det[1] - margin / 2, 0)
        bb[2] = np.minimum(det[2] + margin / 2, img_size[1])
        bb[3] = np.minimum(det[3] + margin / 2, img_size[0])
        cropped = img[bb[1]:bb[3], bb[0]:bb[2], :]
        aligned = misc.imresize(cropped, (image_size, image_size), interp='bilinear')
        # misc.imsave("oops", aligned)
        prewhitened = facenet.prewhiten(aligned)
        img_list.append(prewhitened)
    images = np.stack(img_list)
    return images





def bulk_detect_face(image_paths, image_size=160, margin=16):
    minsize = 0.01  # minimum size of face
    threshold = [0.6, 0.7, 0.7]  # three steps's threshold
    factor = 0.3  # scale factor

    print('Creating networks and loading parameters')

    tmp_image_paths = copy.copy(image_paths)
    img_list = []

    for index,image in enumerate(tmp_image_paths):
        img = misc.imread(os.path.expanduser(image), mode='RGB')
        img_size = np.asarray(img.shape)[0:2]
        for (bounding_boxes, _) in align.detect_face.bulk_detect_face([img], minsize, pnet, rnet, onet, threshold, factor):
        #bounding_boxes, _ = align.detect_face.bulk_detect_face(img, minsize, pnet, rnet, onet, threshold, factor)
            if len(bounding_boxes) < 1:
                image_paths.remove(image)
                print("can't detect face, remove ", image)
                continue
            det = np.squeeze(bounding_boxes[0, 0:4])
            bb = np.zeros(4, dtype=np.int32)
            bb[0] = np.maximum(det[0] - margin / 2, 0)
            bb[1] = np.maximum(det[1] - margin / 2, 0)
            bb[2] = np.minimum(det[2] + margin / 2, img_size[1])
            bb[3] = np.minimum(det[3] + margin / 2, img_size[0])
            cropped = img[bb[1]:bb[3], bb[0]:bb[2], :]
            aligned = misc.imresize(cropped, (image_size, image_size), interp='bilinear')
            misc.imsave("oops"+str(index)+".png", aligned)
            prewhitened = facenet.prewhiten(aligned)
            img_list.append(prewhitened)
    images = np.stack(img_list)
    return images


def transform(faceImagePath):
    return compute([faceImagePath])

 

posted on 2018-12-15 18:33  michaelchan  阅读(68)  评论(0编辑  收藏  举报

导航