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 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 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 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 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'] #print(landmarks) keys = [ 'left_eye_right_corner','left_eye_left_corner','right_eye_right_corner','right_eye_left_corner','left_eyebrow_right_corner','right_eyebrow_left_corner', 'mouth_right_corner','mouth_left_corner','mouth_lower_lip_left_contour2','mouth_lower_lip_left_contour3','mouth_lower_lip_bottom','mouth_lower_lip_right_contour2','mouth_lower_lip_right_contour3','nose_left','nose_right'] new_dict = {} for k,v in landmarks.iteritems(): new_dict[k] = np.array([v['x'],v['y']]) return new_dict
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 batch_process(src_path,dst_path): api = API(API_KEY,API_SECRET); cnt = 0; for parent,dirnames,filenames in os.walk(src_path): filenames.sort(); while (not len(filenames)==0): filename = filenames.pop(); if (os.path.exists(os.path.join(dst_path,os.path.splitext(filename)[0]+'.npy'))): cnt = cnt+1; continue; try: result = api.detect(image_file = File(os.path.join(parent,filename)),return_landmark=2, return_attributes="gender,age,headpose,eyestatus,emotion,mouthstatus,eyegaze") np.save(os.path.join(dst_path,os.path.splitext(filename)[0]+'.npy'),result); cnt = cnt+1; print(cnt,filename) # dictionary = np.load(filename).item() except APIError, error: print(error.body); filenames.append(filename);
def action(): api = API(API_KEY, API_SECRET) cap = cv2.VideoCapture(0) while True: ret, frame = cap.read() cv2.imwrite('demo.jpeg', frame, [int(cv2.IMWRITE_JPEG_QUALITY), 40]) # detect image Face = {} res = api.detect(image_file=File(face_one), return_landmark=2, return_attributes='headpose', calculate_all=1) try: #print_result("person_one", res['time_used']) #print_result("person_one", res['faces'][0]['attributes']['headpose']) head = res['faces'][0]['attributes']['headpose'] for i in range(3): if head[headposelist[i]] < (-1) * int(detectrange[i]): print action[i][0] if head[headposelist[i]] > detectrange[i]: print action[i][1] except: continue for item in res['faces'][0]['landmark']: try: y = res['faces'][0]['landmark'][item]['x'] x = res['faces'][0]['landmark'][item]['y'] frame[x, y] = [0, 0, 255] frame[x + 1, y] = [0, 0, 255] frame[x, y + 1] = [0, 0, 255] frame[x - 1, y] = [0, 0, 255] frame[x, y - 1] = [0, 0, 255] except: continue cv2.imshow("capture", frame) cv2.waitKey(1)
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) # 创建一个Faceset用来存储FaceToken # create a Faceset to save FaceToken ret = api.faceset.create(outer_id='test') print_result("faceset create", ret) # 对图片进行检测 # detect image Face = {} res = api.detect(image_url=face_one) print_result("person_one", res) Face['person_one'] = res["faces"][0]["face_token"] 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='test', face_tokens=Face.itervalues()) # 对待比对的图片进行检测,再搜索相似脸 # detect image and search same face ret = api.detect(image_file=File(face_search)) print_result("detect", ret)
# 首先,导入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) # 创建一个Faceset用来存储FaceToken # create a Faceset to save FaceToken ret = api.faceset.create(outer_id='test') print_result("faceset create", ret) # 对图片进行检测 # detect image Face = {} res = api.detect(image_url=face_one) print_result("person_one", res) Face['person_one'] = res["faces"][0]["face_token"] 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='test', face_tokens=Face.itervalues()) # 对待比对的图片进行检测,再搜索相似脸 # detect image and search same face ret = api.detect(image_file=File(face_search)) print_result("detect", ret)
result = encode(result) print '\n'.join(" " + i for i in pformat(result, width=75).split('\n')) from facepp import API, File api = API(API_KEY, API_SECRET) # 创建一个Faceset用来存储FaceToken # create a Faceset to save FaceToken ret = api.faceset.create(outer_id='facedetect') print_result("faceset create", ret) Face = {} res = api.detect(image_file=File(face_one)) print_result("person_one", res) Face['person_one'] = res["faces"][0]["face_token"] res = api.detect(image_file=File(face_two)) print_result("person_two", res) Face['person_two'] = res["faces"][0]["face_token"] res = api.detect(image_file=File(face_three)) print_result("person_three", res) Face['person_three'] = res["faces"][0]["face_token"] res = api.detect(image_file=File(face_four)) print_result("person_four", res) Face['person_four'] = res["faces"][0]["face_token"]
from pprint import pformat import sys import cv2 files = [] for arg in sys.argv[1:]: files.append(arg) api_server_international = 'https://api-us.faceplusplus.com/facepp/v3/' API_KEY = 'TKc09eEMggaDnrTMaJ4wueum7ljWa5Lf' API_SECRET = '3gX8LSHV7X1R4ODVxsMO-inu4qZDyOSJ' api = API(API_KEY, API_SECRET, srv=api_server_international) # api.faceset.delete(outer_id='test1', check_empty=0) ret = api.faceset.create(outer_id='test1') for filename in files: img = cv2.imread(filename); size = img.shape res = api.detect(image_file=File(filename), return_landmark=2) face = res["faces"][0]["landmark"] person_file = open(filename+".txt", "w") for face_area, face_points in face.iteritems(): person_file.write(str(face_points[u'x']) + "\t" + str(face_points[u'y']) + "\n") api.faceset.delete(outer_id='test1', check_empty=0)
class FaceDectect: def __init__(self, id='test', API_KEY='w1s9SPlbJkhetEnq-BD8puseCT2LDTyj', API_SECRET='a8uEA_hK6lzuRHAY-LiqhlNcoDmS3I7A'): self.api = API(API_KEY, API_SECRET) self.Face = {} self.id = id self.search_result = {} def changeFaceset(self, id): try: ret = self.api.faceset.create(outer_id=id) except Exception as e: print "id already exists" self.id = id def delete_Faceset(self, id): self.api.faceset.delete(outer_id=id, check_empty=0) def addFaceToSet(self, image_file, info): res = self.api.detect(image_file=File(image_file)) self.Face['%s' % info] = res["faces"][0]["face_token"] print "add to Face sucess" def addFaceToInternet(self): print[i for i in self.Face.itervalues()] self.api.faceset.addface(outer_id=self.id, face_tokens=self.Face.itervalues()) print "add to internet face sucess" 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 save_Face(self, face_file="default_face.txt"): face_file = open(face_file, 'wb') pickle.dump(self.Face, face_file) face_file.close() def load_Face(self, face_file="default_face.txt"): face_file = open(face_file, 'rb') self.Face = pickle.load(face_file) face_file.close() 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'))
class Analyze(object): def __init__(self, path_to_analyze_config, output_dir_name="analyzed_result", wait_time=None): self.path_to_analyze_config = path_to_analyze_config with open(self.path_to_analyze_config, "r") as f: self.config = yaml.load(f, Loader=yaml.SafeLoader) self.output_dir_name = output_dir_name self.wait_time = wait_time #自然数で指定する必要がある. if self.config["output_json_name"] is None: self.output_json_name = "output" else: self.output_json_name = self.config["output_json_name"] self.api = API(API_KEY=self.config["API_KEY"], API_SECRET=self.config["API_SECRET"]) del self.config["API_KEY"], self.config["API_SECRET"] def get_dataset(self, serch_config_name="config_camera.yaml", path_to_image=None): if path_to_image is None: path_to_image = self.config["target_dir_name"] if serch_config_name in os.listdir(path_to_image): self.abs_path = os.path.abspath(path_to_image) path_to_camera_config = os.path.join( *[self.abs_path, serch_config_name]) with open(path_to_camera_config, "r") as f: self.config_camera = yaml.load(f, Loader=yaml.SafeLoader) self.path_to_image = os.path.join( *[self.abs_path, self.config_camera["image_dir_name"]]) else: print("'{}' do not have Image dirctory, ex) {}".format( path_to_image, os.path.join(*[path_to_image, "Images/"]))) exit() path_list = glob.glob( os.path.join(*[ self.path_to_image, "*{}".format( self.config_camera['image_style']) ])) path_list = sorted(path_list, key=lambda x: int(x.split("/")[-1].split(".")[0])) output_dir_path = os.path.join(*[self.abs_path, self.output_dir_name]) os.makedirs(output_dir_path, exist_ok=True) with open( os.path.join(*[ output_dir_path, self.path_to_analyze_config.split("/")[-1] ]), "w") as f: yaml.dump(self.config, f) return path_list def choise_function(self, encode_image, api_kind): if api_kind == "Detect": return self.api.detect(image_base64=encode_image, return_landmark=1, return_attributes=",".join( self.config["Attribute_Detect"])) elif api_kind == "Dence": return self.api.face.thousandlandmark(image_base64=encode_image, return_landmark="all") def detect(self, path_list, api_kind): print("-" * 10 + api_kind + "-" * 10) output_list = [] p_bar = ProgressBar(maxval=len(path_list)) for i, each_file in enumerate(path_list): p_bar.update(i) encode_img = self.img_to_bese64(each_file) output = self.choise_function(encode_image=encode_img, api_kind=api_kind) output["image_path"] = each_file output_list.append(output) if (api_kind == "Dence") and (self.wait_time is not None): import time time.sleep(int(self.wait_time)) #実行制限の関係から,ここの値を調整する必要がある. json_name, file_name = self.get_json_name(api_kind) self.save_output(json_name, file_name, output_list) def compere(self, path_list, target_file=None): if target_file is None: print("target_file is None, pleasse give any path to image file") exit() print("-" * 10 + "Get Compere" + "-" * 10) p_bar = ProgressBar(maxval=len(path_list)) output_list = [] if target_file is None: target_file = self.config["target_file"] target_img = self.img_to_bese64(target_file) for i, each_file in enumerate(path_list): p_bar.update(i) if each_file != target_file: each_img = self.img_to_bese64(each_file) output = self.api.compare(image_base64_1=target_img, image_base64_2=each_img) output["image_path"] = each_img output_list.append(output) json_name, file_name = self.get_json_name( "Compere", name=target_file.split("/")[-1].split(".")[0]) self.save_output(json_name, file_name, output_list) def get_json_name(self, api_kind, name=None, name_concat=False): if name is None: if not name_concat: return os.path.join( *[self.abs_path, self.output_dir_name, api_kind ]), self.output_json_name + ".json" else: return os.path.join(*[ self.abs_path, self.output_dir_name, api_kind, self.output_json_name + ".json" ]) else: if not name_concat: return os.path.join( *[self.abs_path, self.output_dir_name, api_kind ]), name + ".json" else: return os.path.join(*[ self.abs_path, self.output_dir_name, api_kind, name + ".json" ]) def save_output(self, path, file_name, output_list): os.makedirs(path, exist_ok=True) with open(os.path.join(*[path, file_name]), "w") as f: json.dump(output_list, f) def img_to_bese64(self, target_file): with open(target_file, 'rb') as f: data = f.read() return base64.b64encode(data) def __call__(self, target_file=None, path_to_image=None): path_list = self.get_dataset(path_to_image=path_to_image) if self.config["USE_API_Detect"]: self.detect(path_list, api_kind="Detect") Detect_api_json_to_csv( path_to_json=self.get_json_name("Detect", name_concat=True))() if self.config["USE_API_Compare"]: self.compere(path_list, target_file) if self.config["USE_API_Dense_Facial_Landmarks"]: self.detect(path_list, "Dence") Dence_api_json_to_csv( path_to_json=self.get_json_name("Dence", name_concat=True))() sys.exit()
from facepp import API, File #创建一个API对象 api = API(API_KEY, API_SECRET) #----------------------------------------------------------------------------- # 本地图片的地址 face_6 = './gtl6.jpg' face_7 = './gtl7.jpg' face_8 = './gtl8.jpg' face_9 = './gtl9.jpg' face_10 = './gtl10.jpg' # 对图片进行检测 Face = {} res = api.detect(image_file=File(face_6)) print_result("person_6", res) Face['person_6'] = res["faces"][0]["face_token"] res = api.face.setuserid(face_token=Face['person_6'], user_id="古天乐") res = api.detect(image_file=File(face_7)) print_result("person_7", res) Face['person_7'] = res["faces"][0]["face_token"] res = api.face.setuserid(face_token=Face['person_7'], user_id="古天乐") res = api.detect(image_file=File(face_8)) print_result("person_8", res) Face['person_8'] = res["faces"][0]["face_token"] res = api.face.setuserid(face_token=Face['person_8'], user_id="古天乐") res = api.detect(image_file=File(face_9))
# 导入系统库并定义辅助函数 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')) # First import the API class from the SDK # 首先,导入SDK中的API类 from facepp import API, File api = API(API_KEY, API_SECRET) #return_attributes=[gender, age, smiling, glass, headpose,facequality,blur] res = api.detect(image_url=face_one, return_landmark=1) print res[u'faces'] res1 = api.detectsceneandobject(image_url=face_one)
line_list = line.split() # 按空格分割会将时间分为两个对象,因此变成13个 face_url = line_list[12].replace("'", "") strline = line_list[1] + ',' + line_list[2] + ',' + line_list[3] + ' ' + line_list[4] + ',' \ + line_list[5] + ',' + line_list[6] + ',' + line_list[7] + ',' + line_list[8] + ',' + line_list[ 9] + ',' \ + line_list[10] + ',' + line_list[11] + ',' + line_list[12] # print face_one InsertFaceTable(flickrDataName[j], strline) ''' InsertFaceTable(line_list[0],long(line_list[1]),line_list[2],line_list[3],line_list[4],\ long(line_list[5]),line_list[6],line_list[7],line_list[8],float(line_list[9]),\ float(line_list[10]),int(line_list[11]),line_list[12]) ''' res = api.detect(image_url=face_url, return_attributes=["gender", "age", "smiling", "emotion", "facequality"]) # print res["faces"][0]["attributes"] i = len(res["faces"]) if i != 0: fileWriter.write(line) for i in range(0, i): image_id = long(line_list[1]) num = i + 1 gender = res["faces"][i]["attributes"]["gender"]["value"] age = res["faces"][i]["attributes"]["age"]["value"] smile = res["faces"][i]["attributes"]["smile"]["value"] anger = res["faces"][i]["attributes"]["emotion"]["anger"] disgust = res["faces"][i]["attributes"]["emotion"]["disgust"] fear = res["faces"][i]["attributes"]["emotion"]["fear"] happiness = res["faces"][i]["attributes"]["emotion"]["happiness"] neutral = res["faces"][i]["attributes"]["emotion"]["neutral"]
import pickle, json from facepp import API, File users = [] for line in open('users_full.json'): users.append(json.loads(line)) # get API Key and API Secret from faceplusplus.com API_KEY = '' API_SECRET = '' api = API(API_KEY, API_SECRET) i = 1 for user in users: print("processing user #" + str(i) + " out of " + str(len(users))) i = i + 1 try: res = api.detect(image_url=user['profile_image_twitter'], return_attributes='age') faces = res['faces'] if (len(faces) > 0): user['age_profile_image_twitter'] = faces[0]['attributes']['age'][ 'value'] except: continue finally: with open('users_full_age.json', 'a') as f: json.dump(user, f) f.write('\n')
# the server of international version api_server_international = 'https://api-us.faceplusplus.com/facepp/v3/' # 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, srv=api_server_international) api.faceset.delete(outer_id=FACESET_ID, check_empty=0) # create a Faceset to save FaceToken ret = api.faceset.create(outer_id=FACESET_ID) print_result("faceset create", ret) # detect image Face = {} res = api.detect(image_file=File(target_face)) print_result(target, res) target_token = res["faces"][0]["face_token"] # save FaceToken in Faceset api.faceset.addface(outer_id=FACESET_ID, face_tokens=[target_token]) t = 0 last_found = False clips = [] t = 0 last_found = False clips = [] video = VideoFileClip(filename='/Users/zhiminhe/wbq.mp4')
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) #----------------------------------------------------------------------------- # 创建一个Faceset用来存储FaceToken ret = api.faceset.create(outer_id='face') # 本地图片的地址 face_one = './gtl2.jpeg' face_two = './demo.jpeg' # 对图片进行检测 Face = {} res = api.detect(image_file=File(face_one)) print_result("person_one", res) Face['person_one'] = res["faces"][0]["face_token"] res = api.detect(image_file=File(face_two)) print_result("person_two", res) Face['person_two'] = res["faces"][0]["face_token"] # 将得到的FaceToken存进Faceset里面 api.faceset.addface(outer_id='face', face_tokens=Face.itervalues())
class use_facepp: def __init__(self, path): self.path = path self.api = API(API_KEY, API_SECRET, srv=api_server_international) self.frame_count = 0 self.per_frame = 1 self.folder_list = [] self.video_list = {} self.open_folder() with open("log.txt", "w") as log: print "reset log" def open_folder(self): self.folder_list = os.listdir(self.path) for folder in self.folder_list: #各フォルダーにJsonフォルダが無ければ作る try: os.mkdir(self.path+'/'+folder+"/Json") except OSError: pass #Videoフォルダ内のファイル一全てをvideo_listに追加 self.video_list[folder] = os.listdir(self.path+'/'+folder+"/Video") def main(self): for folder in self.folder_list: for video in self.video_list[folder]: #カウントリセット self.frame_count = 0 #動画名のフォルダを作成 try: os.mkdir(self.path+'/'+folder+"/Json/"+video.split('.')[0]) except OSError: pass #Opencv用意 cap = cv2.VideoCapture(self.path+'/'+folder+"/Video/"+video) while True: ret, frame = cap.read() if ret == False: break self.frame_count += 1 if (self.frame_count-1) % self.per_frame == 0: cv2.imwrite("current.jpg", frame) #ファイルがあったらパス if os.path.isfile(self.path+'/'+folder+"/Json/"+video.split('.')[0]+'/'+video.split('.')[0]+'_'+str(self.frame_count)+".json") is True: continue res = self.api.detect(image_file=File("current.jpg")) with open(self.path+'/'+folder+"/Json/"+video.split('.')[0]+'/'+video.split('.')[0]+'_'+str(self.frame_count)+".json", "w") as file: json.dump(res, file, indent=4) print "Finish: "+self.path+'/'+folder+'/Video/'+video with open("log.txt", "a") as log: log.write("Finish: "+self.path+'/'+folder+'/Video/'+video+'\n') print "Finish: "+self.path+'/'+folder with open("log.txt", "a") as log: log.write("Finish: "+self.path+'/'+folder+'\n') print "Finish All" with open("log.txt", "a") as log: log.write("Finish All") os.remove("current.jpg")
# 创建一个Faceset用来存储FaceToken #ret = api.faceset.create(outer_id='gtl') # 本地图片的地址 face_1 = './gtl.jpeg' face_2 = './gtl2.jpeg' face_3 = './gtl3.jpg' face_4 = './gtl4.jpg' face_5 = './gtl5.jpg' # 对图片进行检测 Face = {} res = api.faceset.getdetail(outer_id='gtl') print_result("111111", res) res = api.detect(image_file=File(face_1)) print_result("person_1", res) Face['person_1'] = res["faces"][0]["face_token"] res = api.face.setuserid(face_token=Face['person_1'], user_id="古天乐") api.faceset.addface(outer_id='gtl', face_tokens=Face.itervalues()) res = api.detect(image_file=File(face_2)) print_result("person_2", res) Face['person_2'] = res["faces"][0]["face_token"] res = api.face.setuserid(face_token=Face['person_2'], user_id="古天乐") api.faceset.addface(outer_id='gtl', face_tokens=Face.itervalues()) res = api.detect(image_file=File(face_3)) print_result("person_3", res) Face['person_3'] = res["faces"][0]["face_token"] res = api.face.setuserid(face_token=Face['person_3'], user_id="古天乐")
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')) from facepp import API, File api = API(API_KEY, API_SECRET) ret = api.detect(image_file=File(face_search)) print_result("detect", ret) print '=' * 60 search_result = api.search(face_token=ret["faces"][0]["face_token"], outer_id=outer_id) print_result('search', search_result) print '=' * 60
time.sleep(2) face_cascade = cv2.CascadeClassifier( "/opt/ros/kinetic/share/OpenCV-3.3.1-dev/haarcascades/haarcascade_frontalface_alt2.xml" ) #导入opencv的参数 img = cv2.imread("/home/wyx/桌面/one_re/photo1.jpg") #读取照片信息 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #得到灰度图像 faces = face_cascade.detectMultiScale(gray) #使用opencv自带库寻找照片中是否有人脸 if (len(faces) > 0): #返回值大于0 存在人脸 face_re = True else: face_re = False time.sleep(2) print face_re if (face_re): #如何人脸存在 res = api.detect(api_key=API_KEY, api_secret=API_SECRET, image_file=File(img_re)) print_result(printFuctionTitle("人脸检测"), res) # 人脸比对:https://console.faceplusplus.com.cn/documents/4887586 compare_res = api.compare(api_key=API_KEY, api_secret=API_SECRET, image_file1=File(img2_re), image_file2=File(img_re)) #compare_res = api.compare(image_file1=File(face_search_img), image_file2=File(face_search_img)) print_result(printFuctionTitle("compare"), compare_res) print compare_res.confidence #打印俩张照片的置信度 越高则越相似 # 人脸搜索:https://console.faceplusplus.com.cn/documents/4888381 # 人脸搜索步骤 # 1,创建faceSet:用于存储人脸信息(face_token) # 2,向faceSet中添加人脸信息(face_token) # 3,开始搜索
class FaceTask(object): def __init__(self, dbpath=SHELVE_DB): self.api = API(API_KEY, API_SECRET) if RASPBERRYPI: GPIO.setmode(GPIO.BCM) GPIO.setup(BCM_PIN4_SHOW_TAKE_PHOTO, GPIO.OUT) GPIO.output(BCM_PIN4_SHOW_TAKE_PHOTO, True) try: self.api.faceset.create(outer_id = 'default') except APIError as e: """如果 'default' 已创建, 忽略改错误。""" pass self.camera_lock = threading.Lock() def delete_faceset(self, outer_id): try: return self.api.faceset.delete(outer_id=outer_id, check_empty=0) except APIError as e: return str(e) def add_faceset(self, outer_id): try: return self.api.faceset.create(outer_id=outer_id) except APIError as e: return str(e) def get_facesets(self): """获取所有的faceset""" try: facesets = self.api.faceset.getfacesets()['facesets'] except KeyError: return None return [faceset['outer_id'] for faceset in facesets] def get_faceset(self, outer_id='default'): """获取指定faceset中的face.""" faces = [] try: detail = self.api.faceset.getdetail(outer_id = outer_id) faces_tokens = detail['face_tokens'] except ValueError: return None except APIError: return None def get_faces_name(face_token): face_detail = self.api.face.getdetail(face_token = face_token) return face_detail.get('user_id', None) tmp_executor = ThreadPoolExecutor() return list(tmp_executor.map(get_faces_name, faces_tokens)) def upload_faces(self, outer_id='default', **kwargs): """上传face到指定的faceset keyword args image_file or image_url """ name = kwargs.pop('name', None) if name == None: name = raw_input('Please enter the picture name:') try: face_token = self.api.detect(**kwargs)["faces"][0]["face_token"] except (KeyError, IndexError): return None self.api.faceset.addface(outer_id=outer_id, face_tokens=face_token) self.api.face.setuserid(face_token=face_token, user_id=name) img = db.models.Image(name=name, path=kwargs.pop('image_path'), token=face_token) img.save() return face_token, name def search_faces(self, face_token, outer_id='default'): """ 根据face_token在指定的faceset中进行匹配搜索 """ try: results = self.api.search(face_token=face_token, outer_id=outer_id)['results'] except (KeyError): return None return [face['user_id'] for face in results if face['confidence'] > CONFIDENCE] def search_people_from_camera(self, outer_id='default'): if not RASPBERRYPI: return None image_name = '%s.jpg' % time.time() GPIO.output(BCM_PIN4_SHOW_TAKE_PHOTO, 1) cmd = 'sudo raspistill -t 2000 -o %s -p 100,100,300,200 -q 5' % image_name GPIO.output(BCM_PIN4_SHOW_TAKE_PHOTO, 0) with self.camera_lock: os.system(cmd) ret = self.api.detect(image_file=File(image_name)) try: face_token=ret["faces"][0]["face_token"] except (IndexError, KeyError): if isinstance(ret, dict) and ('error_message' in ret.keys()): return ret['error_message'] return 'The picture is invalid.' return self.search_faces(face_token, outer_id=outer_id) 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 clear(self): if RASPBERRYPI: GPIO.cleanup()