-
-
Notifications
You must be signed in to change notification settings - Fork 466
Expand file tree
/
Copy pathFaceProcessing.py
More file actions
244 lines (207 loc) · 7.72 KB
/
Copy pathFaceProcessing.py
File metadata and controls
244 lines (207 loc) · 7.72 KB
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import base64
from StringIO import StringIO
from PIL import Image
import numpy as np
import argparse
import facenet
import align.detect_face
import cv2
import os
import sys
import time
import math
from scipy import misc
from sklearn import metrics
from scipy.optimize import brentq
from scipy import interpolate
from scipy.misc import imread, imresize
import sklearn.preprocessing
import mxnet as mx
global globGraph
globGraph = None
global mod
global mod2
mod2 = None
global mod3
mod3 = None
DEBUG = False
DATA_RUNTIME_FOLDER = os.getenv('DATA_RUNTIME_FOLDER', '/data/runtime')
HAS_OPENCL = os.getenv('HAS_OPENCL', 'false')
def load_graph(frozen_graph_filename):
return None
def crop(image, random_crop, image_size):
if image.shape[1]>image_size:
sz1 = int(image.shape[1]//2)
sz2 = int(image_size//2)
if random_crop:
diff = sz1-sz2
(h, v) = (np.random.randint(-diff, diff+1), np.random.randint(-diff, diff+1))
else:
(h, v) = (0,0)
image = image[(sz1-sz2+v):(sz1+sz2+v),(sz1-sz2+h):(sz1+sz2+h),:]
return image
def flip(image, random_flip):
if random_flip and np.random.choice([True, False]):
image = np.fliplr(image)
return image
def to_rgb(img):
w, h = img.shape
ret = np.empty((w, h, 3), dtype=np.uint8)
ret[:, :, 0] = ret[:, :, 1] = ret[:, :, 2] = img
return ret
def load_image(image_path):
img_list = [None] * 1
img = misc.imread(os.path.expanduser(image_path))
img_size = np.asarray(img.shape)[0:2]
prewhitened = facenet.prewhiten(img)
img_list[0] = prewhitened
image = np.stack(img_list)
return image
def init_FaceProcessing(model_path):
global globGraph
if globGraph != None:
return globGraph
globGraph = load_graph(model_path)
previous = 'no'
for op in globGraph.get_operations():
try:
firstLevel = op.name.split("/")[1]
if firstLevel.startswith(previous) is not True:
print(op.name)
previous = firstLevel
except:
print(op.name)
return globGraph
def InitialFaceProcessor(model_path):
return None , None
def get_model(ctx, image_size, model_str, layer):
_vec = model_str.split(',')
assert len(_vec)==2
prefix = _vec[0]
epoch = int(_vec[1])
print('loading',prefix, epoch)
sym, arg_params, aux_params = mx.model.load_checkpoint(prefix, epoch)
all_layers = sym.get_internals()
sym = all_layers[layer+'_output']
model = mx.mod.Module(symbol=sym, context=ctx, label_names = None)
#model.bind(data_shapes=[('data', (args.batch_size, 3, image_size[0], image_size[1]))], label_shapes=[('softmax_label', (args.batch_size,))])
model.bind(data_shapes=[('data', (1, 3, 112, 112))])
model.set_params(arg_params, aux_params)
return model
def init_embedding_processor():
global mod2
global mod3
if HAS_OPENCL == 'false':
mod2 = None
if os.path.isfile(DATA_RUNTIME_FOLDER+'/model-0000.params'):
ctx = mx.cpu(0)
mod3 = get_model(ctx, [112,112], DATA_RUNTIME_FOLDER+'/model,0', 'fc1')
print('backup model loaded')
return mod3
else:
print('cant get model '+DATA_RUNTIME_FOLDER+'/model-0000.params')
else:
print('has opencl supporting')
if os.path.isfile(DATA_RUNTIME_FOLDER+'/net2'):
global __t
global graph_runtime
try:
import tvm as __t
from tvm.contrib import graph_runtime
loaded_lib = None
if os.path.isfile(DATA_RUNTIME_FOLDER+'/net2.tar.so'):
loaded_lib = __t.module.load(DATA_RUNTIME_FOLDER+'/net2.tar.so')
else:
loaded_lib = __t.module.load(DATA_RUNTIME_FOLDER+'/net2.tar')
loaded_json = open(DATA_RUNTIME_FOLDER+"/net2").read()
loaded_params = bytearray(open(DATA_RUNTIME_FOLDER+"/net2.params", "rb").read())
ctx = __t.cl(0)
mod2 = graph_runtime.create(loaded_json, loaded_lib, ctx)
mod2.load_params(loaded_params)
return mod2
except:
print('error of loading net2')
mod2 = None
if os.path.isfile(DATA_RUNTIME_FOLDER+'/model-0000.params'):
ctx = mx.cpu(0)
mod3 = get_model(ctx, [112,112], DATA_RUNTIME_FOLDER+'/model,0', 'fc1')
print('backup model loaded')
return mod3
elif os.path.isfile('/root/model-r50-am-lfw/model-0000.params'):
ctx = mx.cpu(0)
mod3 = get_model(ctx, [112,112], '/root/model-r50-am-lfw/model,0', 'fc1')
print('backup model loaded')
return mod3
def FaceProcessingOne(imgpath,sess,graph):
images_placeholder = graph.get_tensor_by_name("import/input:0")
embeddings = graph.get_tensor_by_name("import/embeddings:0")
phase_train_placeholder = graph.get_tensor_by_name("import/phase_train:0")
image_size = 160 #images_placeholder.get_shape()[1]
embedding_size = 128 #embeddings.get_shape()[1]
# Run forward pass to calculate embeddings
print('Runnning forward pass on LFW images')
batch_size = 1 #args.lfw_batch_size
nrof_batches = 1
image = load_image(imgpath)
feed_dict = { images_placeholder:image, phase_train_placeholder:False }
features = sess.run(embeddings, feed_dict=feed_dict)
return features
def FaceProcessingImageData(imgData,sess,graph):
images_placeholder = graph.get_tensor_by_name("import/input:0")
embeddings = graph.get_tensor_by_name("import/embeddings:0")
phase_train_placeholder = graph.get_tensor_by_name("import/phase_train:0")
image_size = 160 #images_placeholder.get_shape()[1]
embedding_size = 128 #embeddings.get_shape()[1]
# Run forward pass to calculate embeddings
print('Runnning forward pass on LFW images')
batch_size = 1 #args.lfw_batch_size
nrof_batches = 1
img_list = [None] * 1
img_list[0] = imgData
image = np.stack(img_list)
feed_dict = { images_placeholder:image, phase_train_placeholder:False }
features = sess.run(embeddings, feed_dict=feed_dict)
return features
def FaceProcessingImageData2(img_path):
img_data = misc.imread(img_path)
img = cv2.cvtColor(img_data, cv2.COLOR_BGR2RGB)
return _FaceProcessingImageData2(img)
def FaceProcessingBase64ImageData2(base64_string):
sbuf = StringIO()
sbuf.write(base64.b64decode(base64_string))
pimg = Image.open(sbuf)
img = np.array(pimg)
#img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
return _FaceProcessingImageData2(img)
def _FaceProcessingImageData2(img):
global mod2
global mod3
embedding = None
nimg = np.transpose(img, (2,0,1))
resize_img = misc.imresize(nimg, [112, 112], interp='bilinear')
if mod2 is not None:
a = transform_image(resize_img).astype('float32')
mod2.run(data=a)
try:
out1 = mod2.get_output(0).asnumpy()
except TypeError as err:
out1 = mod2.get_output(0, __t.nd.empty((512,))).asnumpy()
embedding = sklearn.preprocessing.normalize(out1).flatten()
elif mod3 is not None:
aligned = resize_img.transpose((2, 0, 1))
input_blob = np.expand_dims(aligned, axis=0)
data = mx.nd.array(input_blob)
db = mx.io.DataBatch(data=(data,))
mod3.forward(db, is_train=False)
embedding = mod3.get_outputs()[0].asnumpy()
embedding = sklearn.preprocessing.normalize(embedding).flatten()
return embedding
def transform_image(image):
#image = np.array(image) - np.array([123., 117., 104.])
#image /= np.array([58.395, 57.12, 57.375])
image = image.transpose((2, 0, 1))
image = image[np.newaxis, :]
return image