This repository has been archived by the owner on Mar 2, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
test_lfw.py
206 lines (185 loc) · 8.14 KB
/
test_lfw.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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 17/5/16 上午10:27
# @Author : irmo
import tensorflow as tf
import numpy as np
import cv2
import os.path
import time
import pickle
import transform
from tensorflow.contrib.slim.nets import vgg, resnet_v1
from numpy import dot
from numpy.linalg import norm
from functools import reduce
slim = tf.contrib.slim
tf.app.flags.DEFINE_string('lfw_data_dir', 'dataset/lfw_funneled/', """""")
tf.app.flags.DEFINE_integer('num_classes', 10575, """""")
FLAGS = tf.app.flags.FLAGS
net = 'vgg_16'
restore_model = net + '.ckpt'
restore_step = 113000
choose_feature = 'fc7'
size = 6000
image_output_dir = 'images/lfw_align/'
lfw_landmark_file = 'txt/lfw_landmark.txt'
pair_list_file = 'txt/pairs.txt'
model_dir = 'train_data/casia_' + net + '/'
restore_file = restore_model + '-' + str(restore_step)
features_dict = {
'fc6': 'vgg_16/fc6',
'fc7': 'vgg_16/fc7',
'fc8': 'vgg_16/fc8',
'res_block': net + '/block4',
'res_logits': net + '/logits'
}
extract_feature = features_dict[choose_feature]
features_dir = 'features'
output_feature_path = os.path.join(features_dir,'_'.join(('lfw', net, 'step' + str(restore_step), choose_feature)) + '.txt')
class TestLFW():
def __init__(self):
self.dic = {}
self.sess = tf.Session()
self.end_points = None
self.images = tf.placeholder(tf.float32, shape=(None, 224, 224, 3))
def load_lfw_landmark(self):
with open(lfw_landmark_file, 'r') as f:
for line in f:
info = line.split()
filename = info[0]
self.dic[filename] = [int(x) for x in info[-10:]]
def def_net(self):
if net == 'vgg_16':
with slim.arg_scope(vgg.vgg_arg_scope()):
_, end_points = vgg.vgg_16(self.images, num_classes=FLAGS.num_classes,
dropout_keep_prob=1.0, is_training=False)
elif net == 'resnet_v1_101':
with slim.arg_scope(resnet_v1.resnet_arg_scope()):
_, end_points = resnet_v1.resnet_v1_101(self.images, num_classes=FLAGS.num_classes)
elif net == 'resnet_v1_50':
with slim.arg_scope(resnet_v1.resnet_arg_scope(is_training=True)):
_, end_points = resnet_v1.resnet_v1_50(self.images, num_classes=FLAGS.num_classes)
else:
raise Exception('No network matched with net %s' % net)
self.end_points = end_points
def restore_model(self):
self.sess.run(tf.global_variables_initializer())
saver = tf.train.Saver()
saver.restore(self.sess, model_dir + restore_file)
def get_features(self, image_0, image_1):
images_0 = np.expand_dims(image_0, axis=0)
images_1 = np.expand_dims(image_1, axis=0)
images = np.concatenate((images_0, images_1), axis=0)
end_point = self.sess.run([self.end_points], feed_dict={self.images: images})[0]
features = end_point[extract_feature]
num_features = reduce((lambda x, y: x * y), features.shape[1:])
feature_0 = features[0].reshape(num_features)
feature_1 = features[1].reshape(num_features)
return feature_0, feature_1
def test_one_pair(self, image_file_pair):
image_file_0, image_file_1 = image_file_pair
image_0 = cv2.imread(FLAGS.lfw_data_dir + image_file_0)
image_1 = cv2.imread(FLAGS.lfw_data_dir + image_file_1)
assert image_0 is not None
assert image_1 is not None
if image_file_0 in self.dic.keys():
landmark_0 = self.dic[image_file_0]
else:
landmark_0 = None
crop_image_0 = transform.img_process(image_0, landmark_0)
assert crop_image_0.shape == (224, 224, 3)
if image_file_1 in self.dic.keys():
landmark_1 = self.dic[image_file_1]
else:
landmark_1 = None
crop_image_1 = transform.img_process(image_1, landmark_1)
assert crop_image_1.shape == (224, 224, 3)
feature_0, feature_1 = self.get_features(crop_image_0, crop_image_1)
assert feature_0.ndim == 1
assert feature_1.ndim == 1
# feature_0 = feature_0 / norm(feature_0)
# feature_1 = feature_1 / norm(feature_1)
# similarity = norm(feature_0-feature_1)
similarity = dot(feature_0, feature_1) / (norm(feature_0) * norm(feature_1))
# cv2.imwrite(image_output_dir + image_file_0.split('/')[1], image_0)
# cv2.imwrite(image_output_dir + image_file_1.split('/')[1], image_1)
# cv2.imwrite(image_output_dir + image_file_0.split('/')[1][:-4] + '_crop.jpg', crop_image_0)
# cv2.imwrite(image_output_dir + image_file_1.split('/')[1][:-4] + '_crop.jpg', crop_image_1)
return feature_0, feature_1, similarity
def generate_image_pairs(self):
image_pairs = []
with open(pair_list_file) as f:
for line in f:
info = line.split()
same = None
image_pair = {}
if len(info) == 3:
same = True
first = '/'.join([info[0], info[0] + '_' + '%04d' % int(info[1]) + '.jpg'])
second = '/'.join([info[0], info[0] + '_' + '%04d' % int(info[2]) + '.jpg'])
elif len(info) == 4:
same = False
first = '/'.join([info[0], info[0] + '_' + '%04d' % int(info[1]) + '.jpg'])
second = '/'.join([info[2], info[2] + '_' + '%04d' % int(info[3]) + '.jpg'])
else:
print('Line in the list error:')
print(line)
continue
image_pair['files'] = [first, second]
image_pair['ground_truth'] = same
image_pairs.append(image_pair)
return image_pairs
def search_threshold(self, sorted_pairs):
correct = size / 2
t_t = size / 2
f_f = 0
best_correct = correct
best_threshold = 0.0
best_t_t = t_t
best_f_f = f_f
for image_pair in sorted_pairs:
if image_pair['ground_truth'] is True:
correct -= 1
t_t -= 1
else:
correct += 1
f_f += 1
if correct > best_correct:
best_correct = correct
best_threshold = image_pair['similarity']
best_t_t, best_f_f = t_t, f_f
return best_correct, best_threshold, best_t_t, best_f_f
def test(self):
self.load_lfw_landmark()
self.def_net()
self.restore_model()
image_pairs = self.generate_image_pairs()
assert len(image_pairs) == size
start_time = time.time()
print('Begin test...')
for idx, image_pair in enumerate(image_pairs):
feature_0, feature_1, similarity = self.test_one_pair(image_pair['files'])
# print(image_pair['ground_truth'], similarity)
image_pair['features'] = [feature_0, feature_1]
image_pair['similarity'] = similarity
# print(image_pair['ground_truth'], image_pair['similarity'])
if (idx + 1) % 500 == 0:
print('Tested %4d/%4d pairs' % (idx + 1, size))
duration = int(time.time() - start_time)
print('Test completed, use %d seconds.' % duration)
sorted_pairs = sorted(image_pairs, key=lambda x: x['similarity'])
print('Searching for best threshold...')
best_correct, best_threshold, best_t_t, best_f_f = self.search_threshold(sorted_pairs)
print('Choose threshold: %.4f' % best_threshold)
print('Size = %d, Correct = %4d, rate = %s' % (size, best_correct, format(best_correct / float(size), '6.2%')))
print('True, guess True = %4d, rate = %s' % (best_t_t, format(best_t_t / float(size), '6.2%')))
print('False, guess False = %4d, rate = %s' % (best_f_f, format(best_f_f / float(size), '6.2%')))
print('Storing features...')
pickle.dump(image_pairs, open(output_feature_path, 'w'))
print('Features stored at %s' % output_feature_path)
if __name__ == "__main__":
if not tf.gfile.Exists(features_dir):
tf.gfile.MakeDirs(features_dir)
t = TestLFW()
t.test()