def facepp_detect(): API_KEY = '76f2ed8ab272e8793c990ae6c9e0a5e8' API_SECRET = 'RdVvpVpLaBYi37eMfGzAa8drJyDtDBpE' api = API(API_KEY, API_SECRET) count = 0 for pic in POSITIVE_SAMPLES: #if pic != "../data/positive_samples/IMG_7207.JPG": # continue st = time.time() res = api.detection.detect(img = File(pic), mode = 'normal') print pic,":",(time.time()-st)*1000,"ms" if has_valid_pic(res): count += 1 print pic,":YES" else: print pic,":NO",":",len(res['face']) print "True Positive:",round(float(count)*100/len(POSITIVE_SAMPLES),2) print "False Negative:",100 - round(float(count)*100/len(POSITIVE_SAMPLES),2) count = 0 for pic in NEGTIVE_SAMPLES: #if pic != "../data/negtive_samples/IMG_7404.JPG": # continue res = api.detection.detect(img = File(pic), mode='normal') if not has_valid_pic(res): count += 1 print pic,":YES" else: print pic,":NO",":",len(res['face']) print "True Negative:",round(float(count)*100/len(NEGTIVE_SAMPLES),2) print "False Positive:",100 - round(float(count)*100/len(NEGTIVE_SAMPLES),2)
def faceclone(src_name, dst_name): src_img = cv2.imread(src_name) dst_img = cv2.imread(dst_name) src_rst = api.detection.detect(img=File(src_name), attribute='pose') src_img_width = src_rst['img_width'] src_img_height = src_rst['img_height'] src_face = src_rst['face'][0] dst_rst = api.detection.detect(img=File(dst_name), attribute='pose') dst_img_width = dst_rst['img_width'] dst_img_height = dst_rst['img_height'] dst_face = dst_rst['face'][0] # here we will change our coordinate system # by moving the left top point dw = 100 dh = 100 nsrc_img = copy_image(src_img, dw, dh) ndst_img = copy_image(dst_img, dw, dh) ss = np.array(get_feature_points(src_face, src_img_width, src_img_height, dw, dh), dtype=np.float32) ps = np.array(get_feature_points(dst_face, dst_img_width, dst_img_height, dw, dh), dtype=np.float32) map_matrix = cv2.getAffineTransform(ps, ss) nsrc_img_width = src_img_width + dw * 2 nsrc_img_height = src_img_height + dh * 2 ndst_img_width = dst_img_width + dw * 2 ndst_img_height = dst_img_height + dh * 2 map_result = cv2.warpAffine(ndst_img, map_matrix, dsize=(nsrc_img_width, nsrc_img_height)) extract_mask, center = contour.extract_face_mask(src_face['face_id'], src_img_width, src_img_height, src_name) next_mask = copy_image(extract_mask, dw, dh) center = (map_result.shape[0] / 2, map_result.shape[1] / 2) map_result = cv2.seamlessClone(nsrc_img, map_result, next_mask, center, flags=cv2.NORMAL_CLONE) imap_matrix = cv2.invertAffineTransform(map_matrix) final = cv2.warpAffine(map_result, imap_matrix, dsize=(ndst_img_width, ndst_img_height)) new_final = copy_back_image(final, dw, dh) return new_final
def callFaceppApi(self, image_byte_content, face_id = None): for attempts in range(5): try: # face_id is a necessary parameter to the landmark api, so if it's passed in here, it's a landmark invoke if face_id: print 'Uploading image to facepp api for landmark.' result = api.detection.landmark(img=File('b.jpg', image_byte_content), face_id=face_id, type='25p') else: print 'Uploading image to facepp api for detection.' result = api.detection.detect(img=File('b.jpg', image_byte_content), mode = 'normal', attribute = 'glass,pose,gender,age,race,smiling') return result except: print 'DEBUG, upload image failed, timeout, retrying...' else: print 'ERROR, all attempts to call facepp api failed, timeout.'
def landmarkFromFacepp(imgPath): infor = api.detection.detect(img=File(imgPath)) try: faceID = infor[u'face'][0][u'face_id'] except: print("no face detected") req_url = "http://api.faceplusplus.com/detection/landmark" params = urllib.urlencode({ 'api_secret': API_SECRET, 'api_key': API_KEY, 'face_id': faceID, 'type': '83p' }) req_rst = urllib.urlopen(req_url, params).read() # landmark data req_rst_dict = JSONDecoder().decode(req_rst) if len(req_rst_dict['result']) == 1: landmarkDict = req_rst_dict['result'][0]['landmark'] imgInfo = Image.open(imgPath) xSize = imgInfo.size[0] ySize = imgInfo.size[1] landmarkList = sorted(list(landmarkDict)) landmark_array = [] for key in landmarkList: temp_xy = [landmarkDict[key]['x'], landmarkDict[key]['y']] landmark_array.append(np.array(temp_xy)) landmarkArray = np.array(landmark_array) landmarkArray[:, 0] = landmarkArray[:, 0] * xSize / 100 landmarkArray[:, 1] = landmarkArray[:, 1] * ySize / 100 return landmarkArray
def is_person(self, image_file): path = 'media/image/face.png' # path = os.path.join('media/image/', image_file.filename) image_file.save(path) # import ipdb; ipdb.set_trace() f = File(path) api = API(API_KEY, API_SECRET, SERVER) print("Sending face to api") response = api.recognition.identify(group_name='Hackathoners', img=f) print(response) faces = response['face'] if len(faces) > 0: face = faces[0] name = face['candidate'][0]['person_name'] if name in self.people.keys(): print("Found " + name) self.audio.add_to_playlist(self.people[name]) self.audio.play() else: self.audio.add_to_playlist('run.wav') self.audio.play() print("Did not match a person.")
def get_pic(): image_string = request.form['data'] timestamp = (datetime.now() - datetime(1970, 1, 1)).total_seconds() image_file = open(IMAGE_FOLDER + 'temp' + str(timestamp) + '.png', 'wb') image_file.write(image_string.decode('base64')) image_file.close() try: a = api.detection.detect(img=File('D:\\temp' + str(timestamp) + '.png')) if len(a['face']) >= 0: # print a['face'][0]['face_id'] try: api.person.create(person_name=current_user.student_id, face_id=a['face'][0]['face_id']) # print a['face'][0]['face_id'] os.remove('D:\\temp' + str(timestamp) + '.png') current_user.update(pic_exist=True) api.train.verify(person_name=current_user.student_id) except APIError, e: print e.body return "Error.Face++ is so Low." return url_for('main.check_in') except APIError, e: try: api.person.delete(person_name=current_user.studetn_id) except: pass print e.body
def face_identify(photo_url = '', photo_img = '', defaultGroupName = 'yahoohack') : if photo_url == '' and photo_img == '': print 'photo is empty!' return if photo_img != '' : res = face_api.recognition.identify(group_name = defaultGroupName, img = File(photo_img)) img = Image.open(photo_img) img_width, img_height = img.size if photo_url != '' : #??? res = face_api.recognition.identify(group_name = defaultGroupName, url = photo_url) faces = res['face'] faces_confidence = [ (face['candidate'][0]['confidence'],face) for face in faces] sorted(faces_confidence, key=lambda q: -q[0]) faces = [item[1] for item in faces_confidence] #print faces faces_box = {} for face in faces : print face person_name = face['candidate'][0]['person_name'] box = getFaceBox(face,img_width,img_height) if faces_box.get(face['face_id'],None) == None : faces_box[face['face_id']] = person_name, box return faces_box
def face_compare(): face_search = '/Users/Roy/Documents/Thesis/python-sdk/test_image/faceDetected.jpg' # 对待比对的图片进行检测,再搜索相似脸 # detect image and search same face ret = api.detect(image_file=File(face_search)) search_result = api.search(face_token=ret["faces"][0]["face_token"], outer_id='test1') # 输出结果 # print result print_result('search', search_result) print '=' * 60 for k, v in Face.iteritems(): if v == search_result['results'][0]['face_token']: print 'The person with highest confidence:', k break print k if k == "chen.jpeg": person = "chen" elif k == "gakki.jpeg": person = "gakki" elif k == "roy.jpg": person = "roy" pass return person
def face_compare(): face_search = '/Users/Roy/Documents/masterthesis/test_image/faceDetected.jpg' # detect image and search same face ret = api.detect(image_file=File(face_search)) search_result = api.search(face_token=ret["faces"][0]["face_token"], outer_id='test1') # print result print_result('search', search_result) print '=' * 60 if search_result['results'][0]['confidence'] > 60: for k, v in Face.iteritems(): if v == search_result['results'][0]['face_token']: print 'The person with highest confidence:', k break print k else: k = "none" print(k) if k == "chen.jpeg": compare_result = "chen" elif k=="gakki.jpeg": compare_result="gakki" elif k=="roy.jpg": compare_result ="roy" else: compare_result = "none" return compare_result
def face_search(photo_url = '', photo_img = '', defaultFaceSetName = 'yahoohack_faceset') : if photo_url == '' and photo_img == '': print 'photo is empty!' return if photo_img != '' : res = face_api.detection.detect(img = File(photo_img)) if photo_url != '' : res = face_api.detection.detect(url = photo_url) if not res['face']: return [] face_id = res['face'][0]['face_id'] search_res = face_api.recognition.search(key_face_id = face_id, faceset_name = defaultFaceSetName, count = 10) faces_res = search_res['candidate'] face_ids = [face['face_id'] for face in faces_res] face_ids_str = ','.join(face_ids) face_info = face_api.info.get_face(face_id = face_ids_str)['face_info'] person_names = {} for face in face_info : if len(face['person']) > 0 : person_names[face['face_id']] = face['person'][0]['person_name'] person_name_list = [] for face_id in face_ids : if person_names.get(face_id,None) != None : person_name_list.append(person_names[face_id]) print person_name_list return person_name_list
def proc_image(self, img_name): print 'proc_image: image file', img_name rst = api.detection.detect(img=File(img_name), attribute='pose') for face in rst['face']: # basically, there will be only one image in the lfw file self.proc_face(face, rst['img_width'], rst['img_height'], img_name) print 'proc_image: done'
def processing(): api = API(API_KEY, API_SECRET) #url = "http://blogs.reuters.com/great-debate/files/2013/07/obama-best.jpg" result = api.detection.detect(img=File( 'C:/Users/Bhawana/Desktop/bhaw.jpg')) #to detect local images #result = api.detection.detect(url=url) to detect online images return print_result(result)
def DetectFace(filepath): face_detect = api.detection.detect(img=File(filepath)) if face_detect['face'] != []: return face_detect['face'][0]['face_id'] else: return -1
def analysisPhoto(imgPath): face1,face2,results,smile = 0, 0, 0, 0 api = API(APIKEY, APISCRETE) try: detect_res = api.detection.detect(img=File(imgPath)) except Exception,e: print e detect_res = {}
def test_facepp(pic): #pic = '../data/negtive_samples/IMG_7404.JPG' #pic = '../data/positive_samples/IMG_7116.JPG' API_KEY = '76f2ed8ab272e8793c990ae6c9e0a5e8' API_SECRET = 'RdVvpVpLaBYi37eMfGzAa8drJyDtDBpE' api = API(API_KEY, API_SECRET) res = api.detection.detect(img = File(pic), mode='normal') print_result('detect result', res)
def afr_test(msg): subprocess.call('raspistill -o face.jpg -t 300 -w 480 -h 360 ', shell=True) result = api.recognition.recognize(img=File('face.jpg'), group_name='ry_robot_001') #print 'result',result if result['face']: return result['face'][0]['candidate'][0]['person_name'] else: return 'no person'
def getFaceInfo(self, input_file): ret = self.api.detect(image_file=File(input_file)) self.search_result = self.api.search( face_token=ret["faces"][0]["face_token"], outer_id=self.id) for k, v in self.Face.iteritems(): if v == self.search_result['results'][0]['face_token']: print 'The person with highest confidence:', k return k break
def faceclone(src_name, dst_name): src_img = cv2.imread(src_name) dst_img = cv2.imread(dst_name) src_rst = api.detection.detect(img=File(src_name), attribute='pose') src_img_width = src_rst['img_width'] src_img_height = src_rst['img_height'] src_face = src_rst['face'][0] dst_rst = api.detection.detect(img=File(dst_name), attribute='pose') dst_img_width = dst_rst['img_width'] dst_img_height = dst_rst['img_height'] dst_face = dst_rst['face'][0] ss = np.array(get_feature_points(src_face, src_img_width, src_img_height), dtype=np.float32) ps = np.array(get_feature_points(dst_face, dst_img_width, dst_img_height), dtype=np.float32) map_matrix = cv2.getAffineTransform(ps, ss) #dsize = (300,300) map_result = cv2.warpAffine(dst_img, map_matrix, dsize=(src_img_width, src_img_height)) extract_mask, center = contour.extract_face_mask(src_face['face_id'], src_img_width, src_img_height, src_name) # merge ## first blending the border extract_alpha = contour.extract_face_alpha(src_face['face_id'], src_img_width, src_img_height, src_name) center = (map_result.shape[0] / 2, map_result.shape[1] / 2) map_result = cv2.seamlessClone(src_img, map_result, extract_mask, center, flags=cv2.NORMAL_CLONE) imap_matrix = cv2.invertAffineTransform(map_matrix) final = cv2.warpAffine(map_result, imap_matrix, dsize=(dst_img.shape[0:2])) return final
def update_faces_from_camera(self, outer_id='default'): if not RASPBERRYPI: return None image_name = '%s.jpg'%time.time() cmd = 'sudo raspistill -t 2000 -o %s -p 100,100,300,200 -q 5' % image_name GPIO.output(BCM_PIN4_SHOW_TAKE_PHOTO, True) with self.camera_lock: os.system(cmd) GPIO.output(BCM_PIN4_SHOW_TAKE_PHOTO, False) return self.upload_faces(outer_id, image_file=File(image_name), image_path=image_name)
def register(filepath, setid, list): ret = api.detect(image_file=File(filepath)) while (ret.has_key("error_message") != 0): ret = api.detect(image_file=File(filepath)) #print_result("detect", ret) if not len(ret['faces']): print("相片中没有人脸") return search_result = api.search(face_token=ret["faces"][0]["face_token"], outer_id=setid) while (search_result.has_key("error_message") != 0): search_result = api.search(face_token=ret["faces"][0]["face_token"], outer_id=setid) if (search_result["results"][0]["confidence"] >= search_result["thresholds"]["1e-5"]): print(search_result['results'][0]['user_id']) list.append(search_result['results'][0]['user_id']) else: print("不在名单中")
def recognize_with_facepp(self, path): # rst = api.recognition.identify(group_name = 'test', url = TARGET_IMAGE) rst = api.recognition.identify(group_name='saladgroup', img=File(path)) print('recognition result', rst) print('=' * 60) if len(rst['face']) > 0 and len(rst['face'][0]['candidate']) > 0: print('The person with highest confidence:', \ rst['face'][0]['candidate'][0]['person_name']) return rst
def analyze_user(filepath, id_img): print filepath api = API(API_KEY, API_SECRET) ret = api.faceset.create(outer_id=id_img) # print_result("faceset create", ret) Face = {} res = api.detect(image_file=File(filepath)) if res["faces"]: Face['person'] = res["faces"][0]["face_token"] res = api.face.analyze( image_file=File(filepath), face_tokens=Face['person'], return_attributes= 'gender,age,smiling,glass,headpose,facequality,blur') print_result("person", res) # res = api.detect(image_file=File(face_two)) # print_result("person_two", res) # Face['person_two'] = res["faces"][0]["face_token"] # # 将得到的FaceToken存进Faceset里面 # # save FaceToken in Faceset # api.faceset.addface(outer_id=id_test, face_tokens=Face.itervalues()) # # 对待比对的图片进行检测,再搜索相似脸 # # detect image and search same face # ret = api.detect(image_file=File(face_search)) # print_result("detect", ret) # search_result = api.search(face_token=ret["faces"][0]["face_token"], outer_id=id_test) # # 输出结果 # # print result # print_result('search', search_result) # print '=' * 60 # for k, v in Face.iteritems(): # if v == search_result['results'][0]['face_token']: # print 'The person with highest confidence:', k # break api.faceset.delete(outer_id=id_img, check_empty=0) return res
def afr_online(msg): file_path = os.path.join(os.path.dirname(__file__), 'face.jpg') subprocess.call('raspistill -o %s -t 300 -w 480 -h 360 ' % file_path, shell=True) result = api.recognition.recognize(img=File(file_path), group_name='ry_robot_001') #print 'result',result if result['face']: return result['face'][0]['candidate'][0]['person_name'] else: return 'no person'
def detect(path): API_KEY = "3o6_lMDRxcpYalXhuXq9cymJeeN7cHCS" API_SECRET = "6776wZFWYVfYjwDgS8G_0rmWhtXVyUcW" from facepp import API, File api = API(API_KEY, API_SECRET) result = api.detect(image_file=File(path),return_landmark=1) landmarks = result['faces'][0]['landmark'] new_dict = {} for k,v in landmarks.iteritems(): new_dict[k] = np.array([v['y'],v['x']]) return new_dict
def facedetect(path): API_KEY = "RuF7pDgXRAl0EfZjZrWIYElt_QoO-XhN" API_SECRET = "lpUhYiPv8dSdFgMyjkaBKvO2X1nbKzv1" from facepp import API, File api = API(API_KEY, API_SECRET) result = api.detect(image_file=File(path), return_landmark=1) #we only detect face feature points landmarks = result['faces'][0]['landmark'] feature_dict = {} for k, v in landmarks.iteritems(): feature_dict[k] = np.array([v['x'], v['y']]) return feature_dict
def create_face_id(pic_folder, result_file): file_list = os.listdir(pic_folder) f_result = open(result_file, 'w') for file_name in file_list: try: file_path = os.path.join(pic_folder, file_name) face = api.detection.detect(img=File(file_path)) face_id = face['face'][0]['face_id'] f_result.write(file_path.decode('gbk') + '\t' + face_id + '\n') print file_path.decode('gbk') except: traceback.print_exc() continue
def createFace (): # 您需要先注册一个App,并将得到的API key和API secret写在这里。 # You need to register your App first, and enter you API key/secret. API_KEY = "o_aUYdJlo0Pl1beu0kXiIQShUheA7pe3" API_SECRET = "Q0DrLrFybJvD7VP_XCKbOEeVeq7mUdLA" #get the folder list name_list=os.listdir('/Users/Roy/Documents/masterthesis/image_set') print (name_list) face_list=[] for i in range(len(name_list)): face_url = '/Users/Roy/Documents/masterthesis/image_set/'+name_list[i] face_list.append(face_url) print face_list api_server_international = 'https://api-us.faceplusplus.com/facepp/v3/' # First import the API class from the SDK # 首先,导入SDK中的API类 from facepp import API, File #创建一个API对象,如果你是国际版用户,代码为:api = API(API_KEY, API_SECRET, srv=api_server_international) #Create a API object, if you are an international user,code: api = API(API_KEY, API_SECRET, srv=api_server_international) api = API(API_KEY, API_SECRET) api.faceset.delete(outer_id='test1', check_empty=0) print('deleted') # 创建一个Faceset用来存储FaceToken # create a Faceset to save FaceToken ret = api.faceset.create(outer_id='test1') # print_result("faceset create", ret) print('faceset create') # 对图片进行检测 # detect image Face = {} Face2 = {} for i in range(len(face_list)): res = api.detect(image_file=File(face_list[i])) # Face['person'+str(i)] = res["faces"][0]["face_token"] Face[name_list[i]] = res["faces"][0]["face_token"] print (Face) # print (Face2) # 将得到的FaceToken存进Faceset里面 # save FaceToken in Faceset my_faceset = api.faceset.addface(outer_id='test1', face_tokens=Face.itervalues()) print('finally create') return Face
def GenerateSet(path): filename = os.path.join(path, 'setid.txt') if not os.path.isdir(path): os.makedirs(path) if os.path.exists(filename): input = open(filename) setid = input.readlines()[0].strip('\n') input.close() return setid else: output = open(filename, 'w') ret = api.faceset.create(outer_id=path.split('/')[-1]) while (ret.has_key("error_message") != 0): ret = api.faceset.create(outer_id=path.split('/')[-1]) print_result("faceset create", ret) setid = ret["outer_id"] output.write(setid) output.close() list_file = [] GetPicFile(path, list_file) Face = {} print(list_file) for i in list_file: res = api.detect(image_file=File(i)) while (res.has_key("error_message") != 0): res = api.detect(image_file=File(i)) Face[GetFilename(i)] = res["faces"][0]["face_token"] for k, v in Face.items(): result = api.face.setuserid(face_token=v, user_id=k) while (result.has_key("error_message") != 0): result = api.face.setuserid(face_token=v, user_id=k) print_result("set id", result) result1 = api.faceset.addface(outer_id=setid, face_tokens=v) while (result1.has_key("error_message") != 0): result1 = api.faceset.addface(outer_id=setid, face_tokens=v) print_result("add face", result1) return setid
def bidui(image_path): import sys reload(sys) sys.setdefaultencoding( "utf-8" ) #将需要识别的图片和集合对比 #------------------------------------------------------------------------------ #准备阶段 API_KEY = "a4OWmRJTir1XGFx6vZtwPvlf6nsYxErQ" API_SECRET = "Q1bR1pHjv7SGWa3xSN0tNivJ4lK0K8Tu" #国际版的服务器地址 api_server_international = 'https://api-us.faceplusplus.com/facepp/v3/' # 导入系统库并定义辅助函数 from pprint import pformat def print_result(hit, result): def encode(obj): if type(obj) is unicode: return obj.encode('utf-8') if type(obj) is dict: return {encode(v): encode(k) for (v, k) in obj.iteritems()} if type(obj) is list: return [encode(i) for i in obj] return obj print hit result = encode(result) print '\n'.join(" " + i for i in pformat(result, width=75).split('\n')) #导入SDK中的API类 from facepp import API, File #创建一个API对象 api = API(API_KEY, API_SECRET) #----------------------------------------------------------------------------- # 本地图片的地址 face_search = image_path # 对待比对的图片进行检测 Face = {} res = api.detect(image_file=File(face_search)) #print_result("face_search", res) #搜索相似脸 search_result = api.search(face_token=res["faces"][0]["face_token"], outer_id='finally') # 输出结果 search_confidence = search_result['results'][0]['confidence'] uers=search_result['results'][0]['user_id'] print '置信度:', search_confidence if search_confidence >=80: print '你好!',uers.decode('utf-8') return 1 else: return 0
def AddPicToSet(): filename = raw_input("Enter setid file path: ") path = raw_input("Enter Picture path: ") if os.path.exists(filename): input = open(filename) setid = input.readlines()[0].strip('\n') list_file = [] GetPicFile(path, list_file) Face = {} print(list_file) for i in list_file: res = api.detect(image_file=File(i)) while (res.has_key("error_message") != 0): res = api.detect(image_file=File(i)) Face[GetFilename(i)] = res["faces"][0]["face_token"] for k, v in Face.items(): result = api.face.setuserid(face_token=v, user_id=k) while (result.has_key("error_message") != 0): result = api.face.setuserid(face_token=v, user_id=k) print_result("set id", result) result1 = api.faceset.addface(outer_id=setid, face_tokens=v) while (result1.has_key("error_message") != 0): result1 = api.faceset.addface(outer_id=setid, face_tokens=v) print_result("add face", result1)