def compare(filename): imfile = File(filename) for root, dir, file in os.walk('faceimg/'): for f in file: #if('.png' in f): cmpres = api.compare(image_file1=imfile, image_file2=File(root + f)) #比较 name = None try: if (cmpres['confidence'] > 80): name = f.split('.')[0] return (name) #返回文件名 except: pass return None
def addFace(self): user_name = self.main.name.toPlainText() print(user_name) if user_name: try: res = self.api.detect(image_file=File(self.img_file)) faceList = res.faces if len(faceList) > 0: try: self.api.faceset.addface( outer_id=self.faceset, face_tokens=faceList[0].face_token) try: self.api.face.setuserid( face_token=faceList[0].face_token, user_id=user_name) self.face_ids.append(user_name) self.face_tokens.append(faceList[0].face_token) self.popupMsg.popupmsg('加了: ' + user_name, '增加人脸') except: self.popupMsg.popupmsg('设置人脸名字失败', '增加人脸') except: self.popupMsg.popupmsg('增加人脸失败', '增加人脸') else: self.popupMsg.popupmsg('检测不到人脸', '增加人脸') except: self.popupMsg.popupmsg('检测人脸失败', '增加人脸') else: self.popupMsg.popupmsg('请输入名字', '增加人脸') self.main.name.setPlainText("")
def addNewFace(self): global faceSet_img faceSet_img = QtWidgets.QFileDialog.getOpenFileName( self, 'open the dialog', "C:\\Users\Administrator\Desktop", 'JEPG files(*.jpg);;PNG files(*.PNG)') faceStr = [] #存储face_token #创建一个faceset api.faceset.create(outer_id='test2') #探测图片中的face res = api.detect(image_file=File(faceSet_img[0]), return_attributes='emotion') print_result("detect resule", res) #将返回值中的数据复制给faceList faceList = res["faces"] #创建一个str数组存储所有face的facetoken for i in range(len(faceList)): faceStr.append(faceList[i]["face_token"]) #在创建时就获得face_token并将其写入文件 self.data_manager.face_token_set = faceStr self.data_manager.write_face_token_to_csv( self.data_manager.face_token_set) self.loading.show() self.add_thread.faceList = faceList self.add_thread.start()
def searchFace(self, face_search_img): #不显示图片是因为多线程的问题,单一线程会导致图片和搜索同时,搜索完了图片还没加载 print(face_search_img) QtWidgets.QMessageBox.information( self, '请稍等', '将在几秒钟内完成签到', QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.Yes) #首先显示要搜索的图片 serach_res = api.search(image_file=File(face_search_img), outer_id='test2') detec_res = api.detect(image_file=File(face_search_img), return_attributes='emotion') print_result("搜索结果", serach_res) print_result("探测结果", detec_res) #serach_list用于将serach_res中的faces部分信息转换为列表 #输出特定的face_token serach_result = serach_res['results'] #输出对应的置信值 serach_confidence = serach_result[0]['confidence'] face_token = serach_result[0]['face_token'] threshold_up = serach_res['thresholds']['1e-5'] detec_res = detec_res['faces'] down_emotion_detect = ( detec_res[0]['attributes']['emotion']['disgust'] + detec_res[0]['attributes']['emotion']['anger'] + detec_res[0]['attributes']['emotion']['fear'] + detec_res[0]['attributes']['emotion']['sadness']) / 4 up_emotion_detect = ( detec_res[0]['attributes']['emotion']['happiness'] + detec_res[0]['attributes']['emotion']['neutral']) / 2 if (serach_confidence >= threshold_up): print(face_token + '到位了') self.data_manager.add_arrive_data( face_token, QtCore.QDateTime.currentDateTime().toString( 'yyyy-MM-dd hh:mm:ss')) self.data_manager.add_emotion_data( face_token, (up_emotion_detect / down_emotion_detect)) self.data_manager.write_data_to_csv() self.data_manager.write_emotion_to_csv() QtWidgets.QMessageBox.information( self, '成功', face_token + "您已经签到成功", QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.Yes)
def register(): # 获取图片文件 name = register img = request.files.get('register') path = basedir + "\static\\" img_name = 'register.jpg' file_path = path + img_name img.save(file_path) # 人脸检测:https://console.faceplusplus.com.cn/documents/4888373 detect_result = api.detect(image_file=File(img_register), return_attributes="") # print_result (print_function_title ("人脸检测"), detect_result) # 获取face_token detect_result = json.dumps(eval(str(detect_result))) detect_result = json.loads(detect_result) # 如果成功,返回值里有faces字段 if 'faces' in detect_result: faces = json.dumps(eval(str(detect_result['faces']))) faces = faces[1:-1] faces = json.loads(faces) face_token = faces['face_token'] print('新上传的face_token' + face_token) # 根据face_token设置user_id user_id = request.form['user_id'] # Face set_user_id set_id_result = api.face.setuserid(face_token=str(face_token), user_id=str(user_id)) print('set_user_id的结果:', set_id_result) # 将新建的用户加入FaceSet add_face_result = api.faceset.addface(face_tokens=face_token, outer_id='check on work') add_face_result = json.dumps(eval(str(add_face_result))) add_face_result = json.loads(add_face_result) print('新增数目:', add_face_result['face_added']) return '新学生 ' + user_id + ' 注册成功' # 请求错误(有错误码) elif 'error_message' in detect_result: error = detect_result['error_message'] print(error) return '识别失败,请重试!' # 其他错误(网络等原因) else: return '未知错误'
def savelandmarks_facepp(filename): api = API() video = loadvideo(filename) landmarks = [] print('Number of Frames: %d' % (len(video))) cnt = 0 for image in video: cv2.imwrite('temp.jpg', image) landmarks.append(get_landmarks_facepp(File('./temp.jpg'), api)) cnt = cnt + 1 print('%f%%' % (cnt / len(video) * 100)) # Dump landmarks to file with open(filename.split('.')[0] + '.facepp', 'wb') as f: pickle.dump(landmarks, f)
def identify(self): try: search_result = self.api.search(image_file=File(self.img_file), outer_id=self.faceset) face_confidence = search_result.results[0].confidence user_name = search_result.results[0].user_id if face_confidence > 50: self.main.name.setPlainText(user_name) self.speaker.speakMsg(user_name + ',你好,欢迎回来') self.arduino.open_door() else: self.speaker.speakMsg("对不起,没有你的记录") except: self.popupMsg.popupmsg('人脸检测API调用失败', '人脸检测')
def detect(filename, frame, name=None, savepath=None): b1 = File(filename) res = api.detect( image_file=b1 ) #, return_attributes="gender,age,smiling,headpose,facequality," # "blur,eyestatus,emotion,ethnicity,beauty," # "mouthstatus,skinstatus") #print_result(printFuctionTitle("人脸检测"), res) for face in res['faces']: rect = face['face_rectangle'] #人脸所在的矩形框 w, h, l, t = rect['width'], rect['height'], rect['left'], rect['top'] #cv2.rectangle(frame,(rect['left'],rect['top']),(rect['left']+rect['width'],rect['top']+rect['height']),(0,255,0), 5) #cv2.imwrite(filename,frame) if name: cv2.imwrite(savepath + name + '.png', frame[t:t + h, l:l + w]) #保存人脸图像 return w, h, l, t
def train(path2): api.faceset.delete(outer_id='STFace', check_empty=0) # 1.创建一个faceSet ret = api.faceset.create(outer_id='STFace') # path2="/home/marigolci/Downloads/face_recognition-master/examples/FacialSet" for name in os.listdir(path2): faceResStr = "" res = api.detect(image_file=File(os.path.join(path2, str(name)))) faceList = res["faces"] for index in range(len(faceList)): # if(index==0): faceResStr = faceResStr + faceList[index]["face_token"] # else: # faceResStr = faceResStr + ","+faceList[index]["face_token"] api.faceset.addface(outer_id='STFace', face_tokens=faceResStr) connection[name] = faceResStr name = os.path.splitext(name)[0]
def build_gallery_probe(gallery_imgs, probe_imgs): # gallery info # Key: Face Token # Value: Person id gallery = {} # probe info # Key: Face Token # Value: Person id probe = {} # init api api = API() # delete useless face_set api.faceset.delete(outer_id='face_recognition', check_empty=0) # # 1.create faceSet ret = api.faceset.create(outer_id='face_recognition') # # # 2.add pics to faceSet(face_token) img_path = gb.glob(gallery_imgs) for img in img_path: faceResStr = "" res = api.detect(image_file=File(img)) # get person's name person_name = img[-12:][0:5] print(person_name) print(res) faceList = res["faces"] for index in range(len(faceList)): gallery[faceList[index]["face_token"]] = person_name if index == 0: faceResStr = faceResStr + faceList[index]["face_token"] else: faceResStr = faceResStr + "," + faceList[index]["face_token"] api.faceset.addface(outer_id='face_recognition', face_tokens=faceResStr) print(gallery) # build probe set img_path = gb.glob(probe_imgs) for img in img_path: faceResStr = "" res = api.detect(image_file=File(img)) # get person's name person_name = img[-12:][0:5] print(person_name) print(res) faceList = res["faces"] probe[faceList[0]["face_token"]] = person_name print("probe") print(probe) json.dump(gallery, open('gallery.json', 'w')) json.dump(probe, open('probe.json', 'w')) ''' ''' with open("./gallery.json", 'r') as g: gallery = json.load(g) with open("./probe.json", 'r') as p: probe = json.load(p) genuine_scores = [] imposter_scores = [] for gallery_key, gallery_value in gallery.items(): for probe_key, probe_value in probe.items(): result = api.compare(face_token1=gallery_key, face_token2=probe_key) res = {} res['gallery'] = gallery_value res['probe'] = probe_value res['confidence'] = result['confidence'] if gallery_value == probe_value: genuine_scores.append(res) else: imposter_scores.append(res) json.dump(genuine_scores, open('genuine_scores.json', 'w')) json.dump(imposter_scores, open('imposter_scores.json', 'w'))
def transmit(): # 获取图片文件 name = transmit img = request.files.get('transmit') # 定义一个图片存放的位置 存放在static下面 path = basedir + "\static\\" # 图片名称 img_name = 'transmit.jpg' # 图片path和名称组成图片的保存路径 file_path = path + img_name # 保存图片 img.save(file_path) # 开始搜索相似脸人脸信息 search_result = api.search(image_file=File(img_transmit), outer_id='check on work') print_result('search', search_result) # 整个json转化为字符串 search_result = json.dumps(eval(str(search_result))) # 整个json转化为字典 search_result = json.loads(search_result) print(search_result) # 如果成功(返回值中有results字段),返回user_id if 'results' in search_result: # results转化为字符串 results = json.dumps(eval(str(search_result['results']))) # results去除首位的方括号 results = results[1:-1] # result转化为元组 results = json.loads(results) user_id = results["user_id"] # 判断结果可信度 if results['confidence'] > 80: # todo 签到记录写入数据库 # SQL 插入语句 # mysql 初始化 db = pymysql.connect(host="localhost", user="******", password="******", db="check_on_work") # 加入数据库作为历史纪录 try: with db.cursor() as cursor: sql = "INSERT INTO `register` (`student_id`) VALUES ('%s')" % ( user_id) cursor.execute(sql) db.commit() finally: db.close() pass # 返回user_id return '签到成功:' + user_id else: return '验证失败' # 失败返回错误信息 elif 'error_message' in search_result: error = search_result['error_message'] return error elif not search_result['faces']: return '未识别到人脸' else: return '未知错误'
luke_bowsher = './KnightbookScraping/Grade-12/Male/Luke Bowsher_male_Grade-12.png' matt_phua = './KnightbookScraping/Grade-12/Male/Matthew Phua_male_Grade-12.png' abby_doll = './KnightbookScraping/Grade-12/Female/Abigail Doll_female_Grade-12.png' neha_tarkad = './KnightbookScraping/Grade-12/Female/Neha Tarakad Juneja_female_Grade-12.png' max_dostart = './KnightbookScraping/Grade-12/Male/Max Dostart-Meers Dostart Meers_male_Grade-12.png' paras_arora = './KnightbookScraping/Grade-12/Male/Paras Arora_male_Grade-12.png' joseph_ma = './KnightbookScraping/Grade-12/Male/Joseph Ma Chou_male_Grade-12.png' #此方法专用来打印api返回的信息 def print_result(hit, result): print(hit) print('\n'.join(" " + i for i in pformat(result, width=75).split('\n'))) def printFuctionTitle(title): return "\n" + "-" * 60 + title + "-" * 60 # 初始化对象,进行api的调用工作 api = API() #人脸融合:https://console.faceplusplus.com.cn/documents/20813963 #template_rectangle参数中的数据要通过人脸检测api来获取 mergeFace_res = api.mergeface(template_file=File(matt_phua), merge_file=File(santa)) print_result("mergeFace", mergeFace_res) # Start Fusion PythonSDK.ImagePro.ImageProCls.getMergeImg(mergeFace_res["result"])
# 2,向faceSet中添加人脸信息(face_token) # 3,开始搜索 # 初始化对象,进行api的调用工作 api = API() # 删除无用的人脸库,这里删除了,如果在项目中请注意是否要删除 api.faceset.delete(outer_id='testset', check_empty=0) # 1.创建一个faceSet ret = api.faceset.create(outer_id='testset', display_name='测试用set', tags='useless') # 2.向faceSet中添加人脸信息(face_token) faceResStr = "" res = api.detect(image_file=File(faceSet_img)) faceList = res["faces"] for index in range(len(faceList)): if index == 0: faceResStr = faceResStr + faceList[index]["face_token"] else: faceResStr = faceResStr + "," + faceList[index]["face_token"] api.faceset.addface(outer_id='testset', face_tokens=faceResStr, user_id='bbb') # 3.开始搜索相似脸人脸信息 search_result = api.search(image_file=File(face_search_img), outer_id='testset') print_result('search', search_result)
#res = api.detect(image_url=detech_img_url, return_attributes="gender,age,smiling,headpose,facequality," #"blur,eyestatus,emotion,ethnicity,beauty," #"mouthstatus,skinstatus") #print_result(printFuctionTitle("人脸检测"), res) img = cv2.imread('./imgResource/img.jpg') cv2.namedWindow('raw pic') cv2.imshow('raw pic', img) cv2.waitKey(0) cv2.destroyAllWindows() faceStr = [] face_string = '' face_string_2 = '' api.faceset.delete(outer_id='test2', check_empty=0) ret = api.faceset.create(outer_id='test2') res = api.detect(image_file=File(faceSet_img), return_attributes='emotion') print_result("detect resule", res) faceList = res["faces"] print(len(faceList)) for i in range(len(faceList)): api.faceset.addface(outer_id='test2', face_tokens=faceList[i]["face_token"]) print(faceList[i]["face_token"]) for i in range(len(faceList)): faceStr.append(faceList[i]["face_token"]) r = api.faceset.getdetail(outer_id='test2') print_result('faceset结果', r)
# # 开始抠像 # PythonSDK.ImagePro.ImageProCls.getSegmentImg("./imgResource/demo-segment.b64") # -----------------------------------------------------------证件识别部分------------------------------------------- # 身份证识别:https://console.faceplusplus.com.cn/documents/5671702 # ocrIDCard_res = api.ocridcard(image_url="https://gss0.bdstatic.com/94o3dSag_xI4khGkpoWK1HF6hhy/baike/" # "c0%3Dbaike80%2C5%2C5%2C80%2C26/sign=7a16a1be19178a82da3177f2976a18e8" # "/902397dda144ad34a1b2dcf5d7a20cf431ad85b7.jpg") # print_result('ocrIDCard', ocrIDCard_res) # 银行卡识别:https://console.faceplusplus.com.cn/documents/10069553 # ocrBankCard_res = api.ocrbankcard(image_url="http://pic.5tu.cn/uploads/allimg/1107/191634534200.jpg") # print_result('ocrBankCard', ocrBankCard_res) # -----------------------------------------------------------图像识别部分------------------------------------------- # 人脸融合:https://console.faceplusplus.com.cn/documents/20813963 # template_rectangle参数中的数据要通过人脸检测api来获取 # mergeFace_res = api.mergeface(template_file=File(segment_img), merge_file=File(merge_img), # template_rectangle="130,180,172,172") # print_result("mergeFace", mergeFace_res) # # # 开始融合 # PythonSDK.ImagePro.ImageProCls.getMergeImg(mergeFace_res["result"]) # 人脸关键点检测: https://api-cn.faceplusplus.com/facepp/v1/face/thousandlandmark landmarks = api.thousandlandmark(image_file=File(face_search_img), return_landmark="all") print_result(printFuctionTitle("人脸关键点检测"), landmarks)