-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_model.py
160 lines (131 loc) · 6.8 KB
/
test_model.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from scipy import misc
import sys
import os
import argparse
import tensorflow as tf
import numpy as np
import facenet
from align import detect_face
import random
from time import sleep
import math
import pickle
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from sklearn.svm import SVC
count_rightpic=0
def main(args):
dataset = facenet.get_dataset(args.input_dir)
paths, labels = facenet.get_image_paths_and_labels(dataset)
print('Number of classes: %d' % len(dataset))
print('Number of images: %d' % len(paths))
classifier_filename_exp = os.path.expanduser(args.classifier_filename)
with open(classifier_filename_exp, 'rb') as infile:
(model, class_names) = pickle.load(infile)
wrong_imagepaths=[]
for cls in dataset:
for image_path in cls.image_paths:
print(image_path)
img = mpimg.imread(image_path) #得到人脸框
images ,bounding_boxes= load_and_align_data(image_path, args.image_size, args.margin, args.gpu_memory_fraction)
# Get input and output tensors
with tf.Graph().as_default():
with tf.Session() as sess:
# Load the model
facenet.load_model(args.model)
# 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")
predictions=[]
# Run forward pass to calculate embeddings
for image in images:
feed_dict = {images_placeholder: [np.array(image)], phase_train_placeholder: False}
emb_datas = sess.run(embeddings, feed_dict=feed_dict) #每个人脸框向量化为128维
print('Testing classifier')
prediction = model.predict(emb_datas) #预测结果
print(prediction)
predictions.append(class_names[prediction[0]]) #直接预测,总会得到最大的可能值
for prediction in predictions: #每张图所有预测人脸结果
print("prediction:%s"%prediction)
nrof_faces = bounding_boxes.shape[0] # 每张图像检测的人脸框数量
print("nrof_faces:%d"%nrof_faces)
image_label=os.path.basename(os.path.dirname(image_path))
print("image_label:%s"%image_label)
if image_label in predictions: #计算识别出人物的图像数量
global count_rightpic
count_rightpic=count_rightpic+1
print(count_rightpic)
else:
wrong_imagepaths.append(image_path)
print("can't recongised image path")
print(image_path)
print(wrong_imagepaths) #输出识别错的图像路径
#计算召回率
print("count_rightpic:%d"%count_rightpic)
print("len(paths):%d"%len(paths))
print("recall:")
print(format(float(count_rightpic)/float(len(paths)),'.3f'))
def load_and_align_data(image_path, 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 = detect_face.create_mtcnn(sess, None)
img_list = []
img = misc.imread(os.path.expanduser(image_path), mode='RGB')
print("os.path.expanduser(image_path)")
print(os.path.expanduser(image_path))
img_size = np.asarray(img.shape)[0:2]
bounding_boxes, _ = 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)
else:
for bounding_box in bounding_boxes:
print("bounding_box")
print(bounding_box)
det = np.squeeze(bounding_box)
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')
prewhitened = facenet.prewhiten(aligned)
img_list.append(prewhitened)
return img_list,bounding_boxes
def parse_arguments(argv):
parser = argparse.ArgumentParser()
parser.add_argument('--input_dir', type=str, help='Directory with unaligned images.',default='./images/test/policy')
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',
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)
parser.add_argument('--detect_multiple_faces', type=bool,
help='Detect and align multiple faces per image.', default=True)
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',default='models/policy/embedding.pb')
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.',default='models/policy/svm_classifier.pkl')
parser.add_argument('--batch_size', type=int,
help='Number of images to process in a batch.', default=90)
parser.add_argument('--facenet_image_size', type=int,
help='Image size (height, width) in pixels.', default=160)
return parser.parse_args(argv)
if __name__ == '__main__':
main(parse_arguments(sys.argv[1:]))