-
-
Notifications
You must be signed in to change notification settings - Fork 466
Expand file tree
/
Copy pathupload_api.py
More file actions
executable file
·2633 lines (2359 loc) · 121 KB
/
Copy pathupload_api.py
File metadata and controls
executable file
·2633 lines (2359 loc) · 121 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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding=utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os, json, time, sys, thread
import argparse
import unicodedata
import cv2
import shutil
import subprocess
import threading
# import dlib
import math
import time
import os.path
import Queue
from threading import Timer
from collections import defaultdict
from flask import Flask, request, url_for, make_response, abort, Response, jsonify, send_from_directory, redirect
from flask_sqlalchemy import SQLAlchemy
from migrate_db import People, TrainSet, db, AutoGroupSet, Stranger
from sqlalchemy import exc
#from flask_script import Server, Manager
#from flask_migrate import Migrate, MigrateCommand
#from werkzeug.utils import secure_filename
from uuid import uuid1
import urllib2
from urllib2 import Request, urlopen, URLError, HTTPError
from PIL import Image
import tensorflow as tf
import numpy as np
from scipy import misc
from math import hypot
from multiprocessing import Process
from collections import OrderedDict
SAVE_FULL_BODY=True
import facenet
import align.detect_face
if SAVE_FULL_BODY is True:
from align.align_dataset_mtcnn_crop_body import save_body_by_face_position_jpg
# from align import align_dlib
import classifier_classify_new
import clustering_people
from subprocess import Popen, PIPE
import FaceProcessing
from utilslib.uploadFile import uploadFileInit
from utilslib.mqttClient import MyMQTTClass
from utilslib.persistentUUID import getUUID
from utilslib.save2gst import save2gst, post2gst_motion, post2gst_video
from utilslib.save2gst import sendMessage2Group
from utilslib.getDeviceInfo import deviceId, get_current_groupid, get_deviceid, save_groupid_to_file
from utilslib.qiniuUpload import qiniu_upload_img, qiniu_upload_video, qiniu_upload_data, SUFFIX
# from utilslib.make_a_gif import load_all_images, build_gif, url_to_image
# from utilslib.timer import Timer
from utilslib.clean_droped_data import clean_droped_embedding
from objects.generate_bottlenecks import GenerateBottlenecks, resize
from objects.train_obj import TrainFromBottlenecks, train_from_bottlenecks
from objects.test_on_bottleneck import test_on_bottleneck
from Mobilenet.generate_bottlenecks import MobilenetBottlenecks, download_img_for_body, get_embedding_path_for_body, down_embedding_for_body
from Mobilenet.test_on_bottleneck import predict
from faces import save_embedding, test_on_embedding
from utilslib.resultqueue import push_resultQueue, get_resultQueue
BASEDIR = os.getenv('RUNTIME_BASEDIR',os.path.abspath(os.path.dirname(__file__)))
TMP_DIR_PATH = os.path.join(BASEDIR, 'faces', 'tmp_pic_path')
UPLOAD_FOLDER = os.path.join(BASEDIR, 'image')
DATABASE = 'sqlite:///' + os.path.join(BASEDIR, 'data.sqlite')
face_tmp_objid = None
obje_tmp_objid = None
EN_OBJECT_DETECTION = False
FACE_DETECTION_WITH_DLIB = False # Disable DLIB at this time
EN_SOFTMAX = False
SOFTMAX_ONLY = False
isUpdatingDataSet = False
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif', 'bitmap'])
EXT_IMG='png'
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['SQLALCHEMY_DATABASE_URI'] = DATABASE
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
# db = SQLAlchemy(app)
db.init_app(app)
ENABLE_DEBUG_LOG_TO_GROUP = False
DO_NOT_UPLOAD_IMAGE = True
DO_NOT_REPORT_TO_SERVER = True
NEAR_FRONTIAL_ONLY = False
image_size = 160
margin = 16
facenet_model = os.path.join(BASEDIR, 'facenet_models/20170512-110547/20170512-110547.pb')
minsize = 50 # minimum size of face
threshold = [0.6, 0.7, 0.7] # three steps's threshold
factor = 0.709 # scale factor
confident_value = 0.67
mineyedist = 0.3 # Eye distance of width of face bounding box
CONFIDENT_VALUE_THRESHOLD = 0.80 #点圈显示的匹配度阈值,大于这个才显示,针对数据库遍历
BLURY_THREHOLD = 20 # Blur image if less than it. Reference: http://www.pyimagesearch.com/2015/09/07/blur-detection-with-opencv/
uploadImg=None
mqttc=None
gbottlenecks=None
trainfromfottlenecks=None
gFlask_port=None
preFrameOnDevice = {}
all_face_index = 0 #每当识别出一个人脸就+1,当2个人同时出现在图片里面并且都不认识,需要区分开来
SAVE_ORIGINAL_FACE = False
original_face_img_path = os.path.join(BASEDIR, 'original_face_img')
if not os.path.exists(original_face_img_path):
os.mkdir(original_face_img_path)
SVM_CLASSIFIER_ENABLED=True
SVM_SAVE_TEST_DATASET=True
SVM_TRAIN_WITHOUT_CATEGORY=True
SVM_HIGH_SCORE_WITH_DB_CHECK=True
sess, graph = FaceProcessing.InitialFaceProcessor(facenet_model)
if FACE_DETECTION_WITH_DLIB is False:
graph2 = tf.Graph()
with graph2.as_default():
sess2 = tf.Session(config=tf.ConfigProto(log_device_placement=False), graph=graph2)
with sess2.as_default():
pnet, rnet, onet = align.detect_face.create_mtcnn(sess2, None)
else:
dlibFacePredictor = os.path.join(BASEDIR,'../models',
"shape_predictor_68_face_landmarks.dat") # 特征提取器
dlibAlign = align_dlib.AlignDlib(dlibFacePredictor) # 装载特征提取器,实例化AlignDlib类; 默认用了dlib自带的人脸检测器
def dlibImageProcessor(imgPath):
"""
dlib 处理图片
:param imgPath:
:return: 包含图片路径与 prewhitened 的 dict
"""
bgrImg = cv2.imread(imgPath)
if bgrImg is None:
raise Exception("Unable to load image: {}".format(imgPath))
rgbImg = cv2.cvtColor(bgrImg, cv2.COLOR_BGR2RGB)
# assert np.isclose(norm(rgbImg), 11.1355)
dets = dlibAlign.getAllFaceBoundingBoxes(rgbImg)
# dets的元素个数即为脸的个数
print("Number of faces detected: {}".format(len(dets)))
face_path = {} # 存放多个脸部图片及prewhitened
blury_arr = {}
# 使用enumerate 函数遍历序列中的元素以及它们的下标
# 下标i即为人脸序号
for i, bb in enumerate(dets):
if bb is not None:
alignedFace = dlibAlign.align(160, rgbImg, bb) # 缩放裁剪对齐
gray_face = cv2.cvtColor(alignedFace, cv2.COLOR_BGR2GRAY)
blury_value = cv2.Laplacian(gray_face, cv2.CV_64F).var()
if blury_value < BLURY_THREHOLD:
print('A blur face (%d) captured, avoid it.' % blury_value)
#continue
else:
print('Blur Value: %d, good' % blury_value)
prewhitened = facenet.prewhiten(alignedFace)
tmp_image_path = imgPath.rsplit('.', 1)[0] + str(i) + '.' + imgPath.rsplit('.', 1)[1]
misc.imsave(tmp_image_path, alignedFace) # 保存为图像
face_path[tmp_image_path] = prewhitened
blury_arr[tmp_image_path] = blury_value
return face_path, blury_arr
def is_acute(c_1, c_2, c_3):
dist_12 = math.hypot(c_1[0] - c_2[0], c_1[1] - c_2[1])
dist_23 = math.hypot(c_2[0] - c_3[0], c_2[1] - c_3[1])
dist_13 = math.hypot(c_1[0] - c_3[0], c_1[1] - c_3[1])
my_list = [dist_12, dist_23, dist_13]
my_list.sort()
if math.pow(my_list[0], 2) + math.pow(my_list[1], 2) - math.pow(my_list[2], 2) > 0:
return True
else:
return False
counter = 0
def load_align_image(image_path, sess, graph, pnet, rnet, onet):
img = misc.imread(os.path.expanduser(image_path))
img_size = np.asarray(img.shape)[0:2]
with graph2.as_default():
with sess2.as_default():
bounding_boxes, bounding_points = align.detect_face.detect_face(img, minsize, pnet, rnet, onet, threshold, factor)
nrof_faces = bounding_boxes.shape[0] # 人脸数目
width = img_size[1]
height = img_size[0]
if nrof_faces > 0:
face_path = {} # 存放多个脸部图片
blury_arr = {}
imgs_style = {} # 存放不同人脸图对应的类型,如左侧、右侧、低头、抬头、低像素、过模糊、标准
face_body = {} # 人脸对应的人体图片路径
#print('The number of faces detected: {}'.format(nrof_faces))
for i in range(nrof_faces): # 遍历所有faces
style = []
det = np.squeeze(bounding_boxes.copy()[i, 0:4])
# det = np.squeeze(align.detect_face.rerec(bounding_boxes.copy())[i, 0:4])
bounding_point = bounding_points[:, i] # 按i获取多个人脸的point
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])
if bb[0] == 0 or bb[1] == 0 or bb[2] >= width or bb[3] >= height:
print('Out of boundary ({},{},{},{})'.format(bb[0],bb[1],bb[2],bb[3]))
continue
else:
eye_1 = [bounding_point[0], bounding_point[5]]
eye_2 = [bounding_point[1], bounding_point[6]]
nose = [bounding_point[2], bounding_point[7]]
mouth_1 = [bounding_point[3], bounding_point[8]]
mouth_2 = [bounding_point[4], bounding_point[9]]
face_width = bb[2] - bb[0]
face_height = bb[3] - bb[1]
if face_width * face_height < minsize * minsize:
print("to small to recognise ({},{})".format(face_width,face_height))
continue
else:
middle_point = (bb[2] + bb[0])/2
y_middle_point = (bb[3] + bb[1]) / 2
print('eye_1[0]={}, eye_2[0]={}, middle_point={}, bounding_point[5]={}, bounding_point[6]={}, y_middle_point={}'.format(eye_1[0], eye_2[0], middle_point, bounding_point[5], bounding_point[6], y_middle_point))
if eye_1[0] > middle_point:
print('(Left Eye on the Right) Add style')
style.append('left_side')
# continue
elif eye_2[0] < middle_point:
print('(Right Eye on the left) Add style')
style.append('right_side')
# continue
elif max(bounding_point[5], bounding_point[6]) > y_middle_point:
print('(Eye lower than middle of face) Skip')
style.append('lower_head')
# continue
# 左右两个眼睛最低的y轴,低于图片的中间高度,就认为是低头
# style.append('lower_head')
#elif bounding_point[7] < y_middle_point:
# 鼻子的y轴高于图片的中间高度,就认为是抬头
# style.append('raise_head')
else:
style.append('front')
#print('Good Face')
if SAVE_FULL_BODY is True:
file_path_to_save = image_path.rsplit('.', 1)[0] + '_' + str(i) + '_t1.' + 'jpg'
result, width_ratio, height_ratio = save_body_by_face_position_jpg(bb,img,file_path_to_save)
cropped = img[bb[1]:bb[3], bb[0]:bb[2], :] # 裁剪
aligned = misc.imresize(cropped, (160, 160), interp='cubic') # 缩放图像
# Need to detect if face is too blury to be detected
gray_face = cv2.cvtColor(aligned, cv2.COLOR_BGR2GRAY)
blury_value = cv2.Laplacian(gray_face, cv2.CV_64F).var()
if blury_value < BLURY_THREHOLD:
print('A blur face (%d) captured, avoid it.' %blury_value)
style = ['blury']
#isDirty = True
# continue
else:
print('Blur Value: %d, good'%blury_value)
new_image_path = image_path.rsplit('.', 1)[0] + '_' + str(i) + '.' + EXT_IMG #image_path.rsplit('.', 1)[1]
misc.imsave(new_image_path, aligned) # 保存为图像
prewhitened = facenet.prewhiten(aligned)
face_path[new_image_path] = prewhitened
blury_arr[new_image_path] = blury_value
imgs_style[new_image_path] = '|'.join(style) # 如 'left_side|raise_head'
if SAVE_FULL_BODY and result:
face_body[new_image_path] = file_path_to_save
else:
face_body[new_image_path] = ''
#isDirty_arr[new_image_path] = isDirty
#print(prewhitened.shape)
return face_path, imgs_style, blury_arr, face_body #, isDirty_arr , dlib_bb_dict
return None, None, None, None #, None , None
def featureCalculation(imgpath):
img = misc.imread(os.path.expanduser(imgpath))
prewhitened = facenet.prewhiten(img)
with graph.as_default():
with sess.as_default():
embedding = FaceProcessing.FaceProcessingImageData(prewhitened, sess, graph)[0]
return embedding
def detectMotion(img_path,uuid):
min_area = 200
img_gray = cv2.imread(os.path.expanduser(img_path), 0)
if uuid in preFrameOnDevice:
frameDelta = cv2.absdiff(preFrameOnDevice[uuid], img_gray)
preFrameOnDevice[uuid] = img_gray
thresh = cv2.threshold(frameDelta, 25, 255, cv2.THRESH_BINARY)[1]
(cnts, _) = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
delta_value = 0
for c in cnts:
# if the contour is too small, ignore it
delta_value+= cv2.contourArea(c)
if delta_value >= min_area:
#(x, y, w, h) = cv2.boundingRect(c)
print(cv2.boundingRect(c))
#cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
print('Moved delta %d'% delta_value)
return True
return False
else:
preFrameOnDevice[uuid] = img_gray
return True
def updatePeopleImgURL(ownerid, url, embedding, uuid, objid, img_type, accuracy, fuzziness, sqlId, style, img_ts, tid,
p_ids,waiting):
if len(url) < 1 or len(uuid) < 1 or len(objid) < 1 or len(img_type) < 1:
return
print(sqlId)
if (img_type == 'object'):
if not DO_NOT_REPORT_TO_SERVER:
save2gst(uuid, objid, url, '', 'object', accuracy, int(fuzziness), 0, "", img_ts,tid,waiting) # 发送请求给workai
return
# 换成迁移训练,不需要预生成这个数据
# with app.app_context():
# man = People.query.filter_by(id=ownerid).first()
# man.aliyun_url = url
# db.session.add(man)
# db.session.commit()
#
# train = TrainSet(url=url,
# embed=embedding,
# device_id=uuid,
# face_id=ownerid) # 系统自动label,生成一个训练数据
# db.session.add(train)
# db.session.commit()
if not DO_NOT_REPORT_TO_SERVER:
save2gst(uuid, objid, url, '', 'face', accuracy, int(fuzziness), int(sqlId), style, img_ts, tid, p_ids,waiting) # 发送请求给workai
def compare(emb1, emb2):
dist = np.sqrt(np.sum(np.square(np.subtract(emb1, emb2))))
# d = emb1 - emb2
# sqL2 = np.dot(d, d)
# print("+ Squared l2 distance between representations: {:0.3f}, dist is {:0.3f}".format(sqL2,dist))
# print("+ distance between representations: {:0.3f}".format(dist))
# return sqL2
return dist
def compare2(emb1, emb2):
dist = np.sum([emb2]*emb1, axis=1)
return dist
def allowed_file(filename):
"""
检查文件扩展名是否合法
:param filename:
:return: 合法 为 True
"""
return '.' in filename and \
filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
def check_accuracy(confident, val):
c = int(confident*100)
v = int(val*100)
if v == c :
return 0.10
if v > c :
return 0.01
percent = (float(c) - float(v))/float(c)
if (percent<0.10):
percent = 0.49
else:
percent = percent + 0.50
if (percent>=1.0):
percent = 0.99
percent = round(percent, 2)
return percent
def blur_detection(img_path=None, img_buff=None):
img = None
if img_path is None and img_buff is None:
return 1
if img_buff is None:
img = misc.imread(os.path.expanduser(img_path))
else:
img = img_buff
gray_face = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blury_value = cv2.Laplacian(gray_face, cv2.CV_64F).var()
print(">>> object blury_value: %d" %(blury_value))
return blury_value
#
# 返回值:
# found: 发现符合CONFIDENT_VALUE_THRESHOLD的记录
# total: 遍历过这个人的记录
#
def check_embedding_on_detected_person(current_groupid, embedding, style, classid):
total = 0
found = 0
people = None
#遍历整个数据库, 检查这个人是谁
if SVM_TRAIN_WITHOUT_CATEGORY is True:
people = People.query.filter_by(group_id=current_groupid, classId=classid).all()
else:
people = People.query.filter_by(group_id=current_groupid, style=style, classId=classid).all()
if people:
for person in people:
val = compare(embedding, person.embed)
total = total+1
face_accuracy = check_accuracy(confident_value, val) # facenet计算的accuracy
if face_accuracy >= CONFIDENT_VALUE_THRESHOLD:
found = found+1
if total >= 500:
break
return found, total
def check_embedding_on_detected_person_forSVM(current_groupid, embedding, style, classid):
total = 0
found = 0
people = None
#遍历整个数据库, 检查这个人是谁
if SVM_TRAIN_WITHOUT_CATEGORY is True:
people = People.query.filter_by(group_id=current_groupid, classId=classid).all()
else:
people = People.query.filter_by(group_id=current_groupid, style=style, classId=classid).all()
if people:
for person in people:
val = compare2(embedding, person.embed)
total = total+1
#face_accuracy = check_accuracy(confident_value, val) # facenet计算的accuracy
face_accuracy = val
print('face_accuracy={}'.format(face_accuracy))
#if face_accuracy >= 0.55:
if face_accuracy >= 0.70:
found = found+1
if total >= 500:
break
return found, total
#
# 返回值:
# classId: 点圈里面人名字对应的ID,多个平板之间同一个人名字这个ID是相同的, 返回None 表示没有识别出这个人
# sqlId: 与当前被检测embedding接近的那条数据的id, 即原始数据Id
# accuracy: 点圈里面显示的匹配度
#
def find_nearest_embedding(current_groupid, uuid, embedding, style, peopleNum):
if EN_SOFTMAX is True and SOFTMAX_ONLY is True:
return None, None, None
result_classId = {'Id': None, 'dist': None}
#遍历整个数据库,检查这张图片不是人脸
people = People.query.filter_by(group_id=current_groupid, classId="notface").all()
if people:
min_value = min([(compare(embedding, p.embed), p.objId, p.classId, p.id) for p in people]) # 遍历数据库并求最小compare值
if min_value[0] < confident_value:
face_accuracy = check_accuracy(confident_value, min_value[0]) # facenet计算的accuracy
if face_accuracy > 0.9:
print("this must be a None-face image")
return min_value[2], min_value[3], face_accuracy
#遍历整个数据库, 检查这个人是谁
people = People.query.filter_by(group_id=current_groupid, style=style).all()
if people:
min_value = min([(compare(embedding, p.embed), p.objId, p.classId, p.id) for p in people if p.classId != "notface"]) # 遍历数据库并求最小compare值
print(min_value)
face_accuracy = check_accuracy(confident_value, min_value[0]) # facenet计算的accuracy
if face_accuracy >= CONFIDENT_VALUE_THRESHOLD:
result_classId['Id'] = min_value[2]
result_classId['dist'] = min_value[0]
face_accuracy = check_accuracy(confident_value, min_value[0]) # facenet计算的accuracy
print(">>> same people(db): accuracy=%f" % (face_accuracy))
return result_classId['Id'], min_value[3], face_accuracy
return None, None, None
def insertOneImageIntoPeopleDB(filepath, uuid, group_id, objid, url, notFace=False, style="front"):
if notFace is True:
classId = "notface"
else:
classId = objid
if not os.path.exists(filepath):
print("file not exists %s" %(filepath))
return
embedding = featureCalculation(filepath)
with app.app_context():
people = People(embed=embedding, uuid=uuid, group_id=group_id,
objId=objid, aliyun_url=url, classId=classId, style=style)
db.session.add(people)
db.session.commit()
os.remove(filepath)
return embedding
#For AutoGroup
#AutogroupFilesList = {}
#AutogroupDatasetFilesList = {}
AutogroupDB = None
AutogroupDatasetDB = None
isSyncAutogroupDataset = True
isStartAutogroup = False
AUTOGROUP_UNKNOWNFACES_DB = os.path.join(BASEDIR, 'autogroup_unknownfaces_db.json')
AUTOGROUP_DATASET_DB = os.path.join(BASEDIR, 'autogroup_dataset_db.json')
class MyDB:
def __init__(self, dbpath, isSave=False):
print("MyDB: __init__")
self.isSave = isSave
self.collection = {}
if (os.path.isfile(dbpath)):
with open(dbpath) as fJson:
self.collection = json.load(fJson)
self.dbpath = dbpath
def fetch(self):
return self.collection.copy()
def find(self, key, fields):
return self.collection.get(key, fields)
'''
if key is None:
return {}
if key in self.collection.keys():
if fields is None:
return self.collection[key]
subDic = self.collection[key]
isMatch = True
for subKey, subValue in fields:
if subKey not in subDic.keys() or subValue != subDic[subKey]:
isMatch = False
return {}
if isMatch is True:
return subDic
return {}
'''
def insert(self, key, fields):
self.collection[key] = fields
if self.isSave is True:
self.save()
def update(self, key, fields):
self.collection.update({key:fields})
if self.isSave is True:
self.save()
def remove(self, key):
self.collection.pop(key, "Key not Found!")
if self.isSave is True:
self.save()
def batch_insert(self, items):
print("items={}".format(items))
for key, value in items.items():
if isinstance(value,dict):
self.insert(key, value)
else:
print("batch_insert: invalid data format.")
if self.isSave is True:
self.save()
def save(self):
if self.dbpath is None:
return
with open(self.dbpath, 'w') as fJson:
json.dump(self.collection, fJson)
def AutoGroupSetInsert(obj):
print("test")
def AutoGroupSetUpdate(obj):
print("test")
def AutoGroupSetRemove(obj):
print("test")
def disposeAutoGroupFunc(type, json=None):
global AutogroupDB
global AutogroupDatasetDB
global isSyncAutogroupDataset
global isStartAutogroup
print("disposeAutoGroupFunc: type={}, json={}".format(type, json))
if AutogroupDB is None:
AutogroupDB = MyDB(AUTOGROUP_UNKNOWNFACES_DB)
if AutogroupDatasetDB is None:
AutogroupDatasetDB = MyDB(AUTOGROUP_DATASET_DB)
if type == "dataset":
AutogroupDatasetDB.batch_insert(json)
print("Download autogroup dataset...")
elif type == "syncdataset":
isSyncAutogroupDataset = True
print("Set isSyncAutogroupDataset to True")
elif type == "autogroup":
if json is not None:
AutogroupDB.batch_insert(json)
isStartAutogroup = True
print("Autogroup...")
#Path format: GroupID_FaceId/url_filename
def getFacialImagePath(img_path):
part1 = os.path.basename(os.path.dirname(img_path))
part2 = os.path.basename(img_path)
return part1+"/"+part2
def downloadAutogroupDataset(result, group_id):
failedDownloadedItems = []
for person in result:
faceId = person.get("faceId")
urls = person.get("urls")
print('--> {}'.format(faceId))
for url in urls:
#print(' {}'.format(url))
# url,faceid 从点圈群相册获取
# todo 可以用for循环解析群相册获取的json数据
img_url = url['url']
faceid = faceId
style = url['style']
if style != 'front':
#print("style=%s"%style);
continue
#status, embedding = down_img_embedding(img_url, group_id, faceid, style=style)
img_path = save_embedding.get_image_path_dst(img_url, group_id, faceId, style, "autogroup")
#print("img_path = {}".format(img_path))
embedding_path = save_embedding.get_embedding_path(img_path)
embedding = None
if not os.path.exists(img_path):
img_path = save_embedding.download_img_for_svm_dst(img_url, group_id, faceId, style, "autogroup")
if img_path:
if not os.path.exists(embedding_path):
img = misc.imread(os.path.expanduser(img_path)) # 手动裁剪后的图片需要再缩放一下
aligned = misc.imresize(img, (image_size, image_size))
misc.imsave(img_path, aligned)
embedding = featureCalculation(img_path)
embedding_path = save_embedding.get_embedding_path(img_path)
save_embedding.create_embedding_string(embedding, embedding_path)
#print("1, type(embedding)={}".format(type(embedding)))
old_autogroup_set = AutoGroupSet.query.filter_by(url=img_url, group_id=group_id, is_or_isnot=True, style=style).first()
if not old_autogroup_set:
if embedding is None:
embedding_path = save_embedding.get_embedding_path(img_path)
embedding = save_embedding.read_embedding_string(embedding_path)
embedding = np.asarray(embedding)
print("read_embedding_string...........")
print("2, type(embedding)={}".format(type(embedding)))
unique_face_id = ''
if unique_face_id in url:
unique_face_id = url['unique_face_id']
#unique_face_id = url['unique_face_id'] if unique_face_id in url else ''
autoGroupSet = AutoGroupSet(url=img_url, group_id=group_id, is_or_isnot=True,
device_id='', face_id=faceId, unique_face_id=unique_face_id, style=style, filepath=img_path, embed=embedding)
db.session.add(autoGroupSet)
db.session.commit()
print('-> syncAutogroupDataset downloaded url {} to {}'.format(url['url'], img_path))
else:
failedDownloadedItems.append(person)
return failedDownloadedItems
def syncAutogroupDatasetFunc():
group_id = get_current_groupid()
#host="http://localhost:3000/restapi/datasync/token/" + str(group_id)
host = "http://workaihost.tiegushi.com/restapi/datasync/token/" + str(group_id)
result = None
try:
response = urlopen(host, timeout=10)
except HTTPError as e:
print('HTTPError: ', e.code)
return False
except URLError as e:
print('URLError: ', e.reason)
return False
except Exception as e:
print('Error: ', e)
return False
else:
# everything is fine
if 200 == response.getcode():
result = response.readline()
#print(result)
result = json.loads(result)
failedDownloadedItems = downloadAutogroupDataset(result, group_id)
try_count = 0
while len(failedDownloadedItems) > 0:
try_count = try_count+1
print("len(failedDownloadedItems) = {}, try_count={}".format(len(failedDownloadedItems), try_count))
if try_count > 3:
print("We have tried 3 times to download the autogroup dataset.")
break
failedDownloadedItems = downloadAutogroupDataset(failedDownloadedItems, group_id)
#Remove invalid data from local DB
urlsInLocalDB = AutoGroupSet.query.filter_by(group_id=group_id, style="front").all()
urlsOnServer = dict()
for person in result:
faceId = person.get("faceId")
urls = person.get("urls")
for url in urls:
img_url = url['url']
faceid = faceId
style = url['style']
urlsOnServer[img_url] = group_id, faceId, style
print("len(urlsInLocalDB) = {}".format(len(urlsInLocalDB)))
print("len(urlsOnServer) = {}".format(len(urlsOnServer)))
#print("urlsOnServer = {}".format(urlsOnServer))
if urlsInLocalDB:
for item in urlsInLocalDB:
image_path = None
#print("item = {}, item.url={}".format(item, item.url))
if item.url not in urlsOnServer.keys():
print("{}, {}, {}, {} is not on server, delete it from local DB.".format(item.url, item.group_id, item.face_id, item.style))
if item.filepath:
image_path = item.filepath
db.session.delete(item)
db.session.commit()
if image_path and os.path.isfile(image_path):
print('Remove image from local {}'.format(image_path))
os.remove(image_path)
embedding_path = save_embedding.get_embedding_path(image_path)
if embedding_path and os.path.isfile(embedding_path):
print('Remove embedding from local {}:'.format(embedding_path))
os.remove(embedding_path)
#Remove invalid photos from local
'''
dataset = []
for path in paths.split(':'):
path_exp = os.path.expanduser(path)
classes = [path for path in os.listdir(path_exp) \
if os.path.isdir(os.path.join(path_exp, path))]
classes.sort()
nrof_classes = len(classes)
for i in range(nrof_classes):
class_name = classes[i]
facedir = os.path.join(path_exp, class_name)
image_paths = []
if os.path.isdir(facedir):
images = os.listdir(facedir)
for img in images:
dataset.append(os.path.join(facedir,img))
if len(dataset) > 0:
for image_path in dataset:
l5 = (item for item in urlsInLocalDB if item.filepath == image_path)
if not l5:
print("image_path({}) only in local.".format(image_path))
if image_path and os.path.exists(image_path):
os.remove(filepath)
embedding_path = save_embedding.get_embedding_path(image_path)
if embedding_path and os.path.isfile(embedding_path):
os.remove(embedding_path)
'''
return True
else:
print('response code != 200')
return False
def autogroupThreadSubFunc(facial_encodings, unknownImages_array):
print("autogroupThreadSubFunc: len(unknownImages_array)={}".format(len(unknownImages_array)))
current_order_list = OrderedDict()
for item in unknownImages_array:
current_order_list[item["url"]] = item["face_id"], item["filepath"]
start_time = time.time()
#unknown_length = len(unknownImages_array)
current_groupid = get_current_groupid()
device_id = get_deviceid()
people = AutoGroupSet.query.filter_by(group_id=current_groupid, style="front").all()
print("len(people)={}".format(len(people)))
if people:
for person in people:
#facial_encodings[getFacialImagePath(person.filepath)] = person.embed
#print("person.url={}, person.embed={}".format(person.url, person.embed))
#numpy.ndarray
facial_encodings[person.url] = person.face_id, person.embed
#print("type(person.embed)={}".format(type(person.embed)))
#print("person.embed={}".format(person.embed))
current_order_list[person.url] = person.face_id, person.filepath
print("current_order_list = {}".format(current_order_list))
#print("facial_encodings={}".format(facial_encodings))
print("autogroupThreadSubFunc get facial encodings costs {} S".format(time.time() - start_time))
#sendMessage2Group(device_id, toid, '-> Train cost {}s'.format(time.time() - start_time))
print("facial_encodings={}".format(facial_encodings))
results = clustering_people.cluster_unknown_people(facial_encodings, current_order_list)
json_string = "{}devId:{}, group_id:{}, results:{}{}".format('{', device_id, current_groupid, results, '}')
json_dict = {"devId":device_id, "group_id":current_groupid, "results":results}
mqttc.publish("/msg/autogroup/{}".format(current_groupid), json.dumps(json_dict))
def autogroupThreadFunc():
global AutogroupDB
global AutogroupDatasetDB
global isSyncAutogroupDataset
global isStartAutogroup
unknown_faceId = "unknown"
while True:
try:
if isSyncAutogroupDataset is True:
if not syncAutogroupDatasetFunc():
time.sleep(6)
continue
isSyncAutogroupDataset = False
datasetDic = []
if AutogroupDatasetDB is not None:
datasetDic = AutogroupDatasetDB.fetch()
if (len(datasetDic) > 0):
print("len(AutogroupDatasetDB)={}".format(len(datasetDic)))
print("autogroupThreadFunc: download dataset %d" % len(datasetDic))
for key in datasetDic:
print("key = {}".format(key))
info = datasetDic[key]
#if SVM_TRAIN_WITHOUT_CATEGORY is True:
# info['style'] = 'front'
print("info = {}".format(info))
ret = urllib2.urlopen(info['url'])
if ret.code != 200:
AutogroupDatasetDB.remove(key)
print("URL{} not exists, continue.".format(info['url']))
print("info['url'] = {}".format(info['url']))
img_path = save_embedding.get_image_path_dst(info['url'], info['group_id'], info['face_id'], info['style'], "autogroup")
print("img_path = {}".format(img_path))
embedding_path = save_embedding.get_embedding_path(img_path)
embedding = None
if not os.path.exists(img_path):
img_path = save_embedding.download_img_for_svm_dst(info['url'], info['group_id'], info['face_id'], info['style'], "autogroup")
if img_path:
if not os.path.exists(embedding_path):
img = misc.imread(os.path.expanduser(img_path)) # 手动裁剪后的图片需要再缩放一下
aligned = misc.imresize(img, (image_size, image_size))
misc.imsave(img_path, aligned)
embedding = featureCalculation(img_path)
embedding_path = save_embedding.get_embedding_path(img_path)
save_embedding.create_embedding_string(embedding, embedding_path)
old_autogroup_set = AutoGroupSet.query.filter_by(url=info['url'], group_id=info['group_id'], is_or_isnot=True, style=info['style']).first()
if not old_autogroup_set:
if embedding is None:
embedding_path = save_embedding.get_embedding_path(img_path)
embedding = save_embedding.read_embedding_string(embedding_path)
embedding = np.asarray(embedding)
unique_face_id = info['unique_face_id'] if unique_face_id in info else ''
autoGroupSet = AutoGroupSet(url=info['url'], group_id=info['group_id'], is_or_isnot=True,
device_id=info['device_id'], face_id=info['face_id'], unique_face_id=unique_face_id, style=info['style'], filepath=img_path, embed=embedding)
db.session.add(autoGroupSet)
db.session.commit()
print('-> autogroupThreadFunc downloaded url {} to {}'.format(info['url'], img_path))
AutogroupDatasetDB.remove(key)
datasetDic = []
if AutogroupDB is not None:
datasetDic = AutogroupDB.fetch()
if isStartAutogroup is True:
facial_encodings = OrderedDict()
if (len(datasetDic) > 0):
print("len(AutogroupDB)={}".format(len(datasetDic)))
print("autogroupThreadFunc: download Autogroup data %d" % len(datasetDic))
unknownImages_array = []
for key in datasetDic:
info = datasetDic[key]
if 'url' not in info or 'group_id' not in info or 'face_id' not in info:
print("Missing key information in message.")
continue
ret = urllib2.urlopen(info['url'])
if ret.code != 200:
AutogroupDB.remove(key)
print("URL{} not exists, continue.".format(info['url']))
img_path = save_embedding.get_image_path_dst(info['url'], info['group_id'], unknown_faceId, info['style'], "autogroup")
embedding_path = save_embedding.get_embedding_path(img_path)
basepath = os.path.abspath(os.getenv('RUNTIME_BASEDIR',os.path.dirname(__file__)))
local_path = os.path.join(basepath, "face_testdataset/" + info['group_id']+"/noname/"+os.path.basename(info['url']))
print("local_path = {}".format(local_path))
if os.path.exists(local_path):
shutil.copy(local_path, img_path)
print("Copied local file {} to {}".format(local_path, img_path))
if not os.path.exists(img_path):
img_path = save_embedding.download_img_for_svm_dst(info['url'], info['group_id'], unknown_faceId, info['style'], "autogroup")
if img_path:
if not os.path.exists(embedding_path):
img = misc.imread(os.path.expanduser(img_path)) # 手动裁剪后的图片需要再缩放一下
aligned = misc.imresize(img, (image_size, image_size))
misc.imsave(img_path, aligned)
embedding = featureCalculation(img_path)
embedding_path = save_embedding.get_embedding_path(img_path)
save_embedding.create_embedding_string(embedding, embedding_path)
#AutoGroupEmbeddings.append({info['url']: embedding})
#facial_encodings[getFacialImagePath(img_path)] = embedding
else:
embedding_path = save_embedding.get_embedding_path(img_path)
embedding = save_embedding.read_embedding_string(embedding_path)
#list
facial_encodings[info['url']] = unknown_faceId, np.asarray(embedding)
print("type(embedding) = {}".format(type(embedding)))
unknownImages_array.append({"filepath":img_path, "url":info['url'], "face_id":unknown_faceId, "style":info['style']})
AutogroupDB.remove(key)
print("len(facial_encodings)={}".format(len(facial_encodings)))
if len(facial_encodings) > 0:
#TODO compare facial
autogroupThreadSubFunc(facial_encodings, unknownImages_array)
else:
autogroupThreadSubFunc(facial_encodings, [])
isStartAutogroup = False
except Exception as ex:
print('autogroupThreadFunc: except:', ex)
isSyncAutogroupDataset = False
isStartAutogroup = False
time.sleep(6)
autogroupThread = threading.Thread(target=autogroupThreadFunc)
autogroupThread.daemon = True
#autogroupThread.start()
#Sync train data sets
def recover_db(img_url, group_id, faceid, filepath, embedding, style='front'):
# 恢复embedding到db
uuid = get_deviceid()
p = People.query.filter_by(aliyun_url=img_url, group_id=group_id).first()
if not p:
people = People(embed=embedding, uuid=uuid, group_id=group_id,
objId=faceid, aliyun_url=img_url, classId=faceid, style=style)
db.session.add(people)
db.session.commit()
print("Add people")
#return True
#else:
#print("No need add people")
#return False
old_train_set = TrainSet.query.filter_by(url=img_url, group_id=group_id).first() # 一张图片对应的人是唯一的
if not old_train_set:
new_train_set = TrainSet(url=img_url, group_id=group_id, is_or_isnot=True,
device_id='', face_id=faceid, filepath=filepath, drop=False, style=style)
db.session.add(new_train_set)
db.session.commit()
else:
if old_train_set.filepath != filepath:
print("Update filepath in local DB")
TrainSet.query.filter_by(url=img_url, group_id=group_id).update(dict(filepath=filepath))
db.session.commit()
def downloadTrainDatasets(result, group_id):
failedDownloadedItems = []
img_path = None
embedding_path = None
try:
for person in result:
faceId = person.get("faceId")
urls = person.get("urls")
print('--> {}'.format(faceId))
for url in urls:
#print(' {}'.format(url))
# url,faceid 从点圈群相册获取
# todo 可以用for循环解析群相册获取的json数据
img_url = url['url']
faceid = faceId
style = url['style']
if SVM_TRAIN_WITHOUT_CATEGORY is True:
style = 'front'
#status, embedding = down_img_embedding(img_url, group_id, faceid, style=style)
img_path = save_embedding.get_image_path(img_url, group_id, faceId, style)
#print("img_path = {}".format(img_path))
embedding_path = save_embedding.get_embedding_path(img_path)
embedding = None
if not os.path.exists(img_path):
img_path = save_embedding.download_img_for_svm(img_url, group_id, faceId, style)