def item_completed(self, results, item, info): print(item) print('thisis pix') conn = mysql.connector.connect(host='127.0.0.1', user='******', password='******', database='bigdata') db = conn image_paths = [x['path'] for ok, x in results if ok] # ok判断是否下载成功 if not image_paths: raise DropItem("Item contains no images") # item['image_paths'] = image_paths else: print('dowok') for ok, x in results: path = x['path'] rootpath = os.path.abspath('..') filePath = rootpath + "\\images\\" + path print(filePath) aipFace = AipFace(APP_ID, API_KEY, SECRET_KEY) imageType = "BASE64" options = {} options["face_field"] = "age,gender,beauty" with open(filePath, 'rb') as fp: content = base64.b64encode(fp.read()) base64ss = content.decode('utf-8') result = aipFace.detect(base64ss, imageType, options) beauty = 0 if result['error_code'] == 0: face = result['result']['face_list'] beauty = face[len(face) - 1]['beauty'] elif result['error_code'] == 18: aipFace1 = AipFace(APP_ID1, API_KEY1, SECRET_KEY1) result1 = aipFace1.detect(base64ss, imageType, options) if result1['error_code'] == 0: face = result1['result']['face_list'] beauty = face[len(face) - 1]['beauty'] img_url = item['image_urls'] type = 1 cursor = db.cursor() sql = "INSERT INTO pic (img_url,`type`,beauty) VALUES (%s,%s,%s)" val = (img_url, type, beauty) cursor.execute(sql, val) db.commit() cursor.close() print("1 条记录已插入, ID:", cursor.lastrowid) return item
class FaceScan: def __init__(self): self.imageType = "BASE64" """ 你的 APPID AK SK """ self.APP_ID = '16361765' self.API_KEY = '08eNIM7h4mcc9tPzOZaOrkR1' self.SECRET_KEY = 'gErwZbxYktnzwQnLVvQKT1oWLffem4EA' # imagePath = 'zipai.jpg'#should be a variable def getAttrOfPic(self,imagePath): with open(imagePath, 'rb') as fp: image = base64.b64encode(fp.read()) # print(type(image)) self.client = AipFace(self.APP_ID, self.API_KEY, self.SECRET_KEY) self.options = {} # self.options["face_field"] = "age,faceshape,beauty,landmark" self.options["face_field"] = "age,faceshape,beauty,landmark,gender" # 调用ai客户端的detect方法,这个方法返回的结果就是对人脸检测后的数据 self.result = self.client.detect(image, self.imageType, self.options) #print result # 解析返回数据中的位置参数,获取到人脸的矩形信息 self.beauty = self.result['result']['face_list'][0]['beauty'] self.shape = self.result['result']['face_list'][0]['face_shape'] self.faceShape = self.shape['type'] self.probability = self.shape['probability'] self.gender = self.result['result']['face_list'][0]['gender'] self.landMark = self.result['result']['face_list'][0]['landmark72'] self.location = self.result['result']['face_list'][0]['location'] def getShape(self): return self.faceShape def getLandMark(self): return self.landMark
def detection(APP_ID, API_KEY, SECRET_KEY, filename, maxnum): ''''' :param APP_ID: https://console.bce.baidu.com/ai/创建人脸检测应用对应的APP_ID :param API_KEY: https://console.bce.baidu.com/ai/创建人脸检测应用对应的API_KEY :param SECRET_ID: https://console.bce.baidu.com/ai/创建人脸检测应用对应的SECRET_ID :param filename: 图片路径 :param maxnum: 最大检测数 :return: ''' # 初始化AirFace对象 aipface = AipFace(APP_ID, API_KEY, SECRET_KEY) # 设置 options = { 'max_face_num': 10, # 检测人脸的最大数量 'face_fields': "age,beauty,expression,faceshape", } # 读取文件内容 def get_file_content(filePath): with open(filePath, 'rb') as fp: return fp.read() result = aipface.detect(get_file_content(filename), options) return result
def showResult(self): # 填入百度API信息 APP_ID = '' API_KEY = '' SECRET_KEY = '' aipFace = AipFace(APP_ID, API_KEY, SECRET_KEY) # 使用base64重新编码图片 def get_file_content(filePath): with open(filePath, 'rb') as fp: content = base64.b64encode(fp.read()) return content.decode('utf-8') pass imageType = "BASE64" options = {} options["face_field"] = "age,gender,beauty" result = aipFace.detect(get_file_content(path_), imageType, options) sex = result['result']['face_list'][0]['gender']['type'] age = result['result']['face_list'][0]['age'] beauty = result['result']['face_list'][0]['beauty'] # 使用标签显示结果 Label(root, text="sex: " + sex).place(x=260, y=30) Label(root, text="age: " + str(age)).place(x=260, y=60) Label(root, text="beauty: " + str(beauty)).place(x=260, y=90) pass
def detection(path): """ 你的 APPID AK SK """ APP_ID = '16918274' API_KEY = '8LPSpFQpG1WTSTP77arZKTFG' SECRET_KEY = 'Me1HVHyWjm6sPSluFBGeNHGTYZQNbcyf' client = AipFace(APP_ID, API_KEY, SECRET_KEY) with open(path, 'rb') as f: # print(f.read()) data = base64.b64encode(f.read()) # exit() image = data.decode() imageType = "BASE64" """ 调用人脸检测 """ # client.detect(image, imageType); """ 如果有可选参数 """ options = {} options["face_field"] = "beauty" # options["max_face_num"] = 2 # options["face_type"] = "LIVE" # options["liveness_control"] = "LOW" """ 带参数调用人脸检测 """ response = client.detect(image, imageType, options) # print(response) if response['error_code'] != 0: print('失败', response['error_code']) else: return response['result']['face_list'][0]['beauty']
def face_detection(image, imageType, *options): #################### Define by Baidu Document #################### # pip3 install baidu_aip - After installing Baidu-AI python package, # import Baidu face detection Python SDK client from aip import AipFace # create Aipface client """ 你的 APPID AK SK """ APP_ID = '14325294' API_KEY = 'AsvKVw4Kb1Hk5aYiZifxihHh' SECRET_KEY = 'opAuwOddyUIfHgpkE4tdn3qf94PsaYAT' client = AipFace(APP_ID, API_KEY, SECRET_KEY) ########## detect face in picture and mark position ########## #image = "取决于image_type参数,传入BASE64字符串//或URL字符串//或FACE_TOKEN字符串" # Example: #### image = "http://pic5.newssc.org/upload/ori/20160413/1460515143090.jpg" #### imageType = "URL" image = image imageType = imageType """ 调用人脸检测 """ #result = client.detect(image, imageType) """ 如果有可选参数 """ options = {} options["face_field"] = "age" options["max_face_num"] = 10 options["face_type"] = "LIVE" """ 带参数调用人脸检测 """ result = client.detect(image, imageType, options) # return json format return result
def face_score(link): # 图片名称 pic_name = re.findall(r"public/(.+?)$", link) # 图片存储位置 # 还能巧妙的避免重复!!! filePath = '/Users/zhaowenbo/Downloads/crawl_ouban/pictures/' + pic_name[0] # 根据图片的URL获取并保存图片 urllib.request.urlretrieve(link, filePath) # 百度api的一些key APP_ID = '18072729' API_KEY = 'ZRQcBl5i4f6hlTML09h47vA9' SECRET_KEY = 'dimWQ2OhId6Z4AEnpUMdpvuZ4k1se3AR' # 使用百度人脸识别API aipFace = AipFace(APP_ID, API_KEY, SECRET_KEY) def get_file_content(filePath): with open(filePath, 'rb') as fp: content = base64.b64encode(fp.read()) return content.decode('utf-8') imageType = "BASE64" options = {} options["face_field"] = "age,gender,beauty" result = aipFace.detect(get_file_content(filePath), imageType, options) # result['result']['face_list'][0]['beauty'] float return result['result']['face_list'][0]['beauty']
def face_information(img_path): """ 你的 APPID AK SK """ APP_ID = '17151694' API_KEY = 'PVc6kFsF0Pk8ZPpGewaIhoK8' SECRET_KEY = '43XAsfZnkcezXDAjA4czgDirnpa4TudW' client = AipFace(APP_ID, API_KEY, SECRET_KEY) # 打开本地文件 f = open(r'%s' % img_path, 'rb') # # 打开url地址 # f = urllib.request.urlopen(img_path) pic = base64.b64encode(f.read()) image = str(pic, 'utf-8') imageType = "BASE64" """ 如果有可选参数 """ options = {} options["face_field"] = "age,beauty,gender,face_shape,quality" options["max_face_num"] = 1 options["face_type"] = "LIVE" """ 带参数调用人脸检测 """ a = client.detect(image, imageType, options) # for item in a['result']['face_list']: # print("年龄:", item['age'], "容貌评分:", item['beauty'], "性别:", item['gender'],"脸型:",item['face_shape']) return a
class BaiduFaceDetector(FaceDetector): """docstring for BaiduFaceDetector""" def __init__(self, options=None): self._options = options self._client = AipFace(baiduAI['APP_ID'], baiduAI['API_KEY'], baiduAI['SECRET_KEY']) def run(self, image): print('Detecting ...') cv2.imwrite('./01.png', image) ret = {} img = None with open('./01.png', 'rb') as fp: img = fp.read() image64 = base64.b64encode(img) ret = self._client.detect(image64, "BASE64") print(ret) return { 'frame': img, 'error_msg': ret['error_msg'], 'location': ret['result']['face_list'][0]['location'] if self.successDetectFace(ret) else None } @staticmethod def successDetectFace(ret): return ret and (ret['error_msg'] == 'SUCCESS')
def check_img(flag, path): # 面部识别 cli = AipFace(AppId, API_Key, Secret_Key) image, image_type = '', '' if flag == '1': image = 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1538151319150&di=196eda34652fd03b3335ec68aca74122&imgtype=0&src=http%3A%2F%2F01.minipic.eastday.com%2F20170306%2F20170306130710_4f981e8e34f472af11274a7cc68fa3bb_4.jpeg' image_type = 'URL' elif flag == '2': image = trans_base64(path) image_type = 'BASE64' options = {} options['face_field'] = 'age,beauty' options['max_face_num'] = 1 # 最多处理人脸的数目 options['face_type'] = 'LIVE' #人脸的类型 LIVE表示生活照:通常为手机、相机拍摄的人像图片、或从网络获取的人像图片等IDCARD表示身份证芯片照:二代身份证内置芯片中的人像照片 WATERMARK表示带水印证件照:一般为带水印的小图,如公安网小图 CERT表示证件照片:如拍摄的身份证、工卡、护照、学生证等证件图片 默认LIVE res = cli.detect(image, image_type, options) print(res) if res['error_code'] == 0: print('读取成功') face_num = res['result']['face_num'] face_age = res['result']['face_list'][0]['age'] face_beaty = res['result']['face_list'][0]['beauty'] print('人脸数量', face_num) print('人脸年龄', face_age) print('颜值', face_beaty) return face_num, face_age, face_beaty else: print('读取失败')
def check_face_img(image_path): image_str = get_image_base64(image_path) client = AipFace(config.APP_ID, config.APP_KEY, config.SECRET_KEY) imageType = "BASE64" # print(client.detect(image_str, imageType)['error_code'] != 0) if client.detect(image_str, imageType)['error_code'] != 0: # print('没有人脸的图片===>' + image_path) delete_no_face(image_path)
def req(filepath): client = AipFace(APP_ID, API_KEY, SECRET_KEY) with open(filepath,'rb') as f: base64_data=base64.b64encode(f.read()) image = str(base64_data,'utf-8') imageType = "BASE64" """ 调用人脸检测 """ client.detect(image, imageType) """ 如果有可选参数 """ options = {} options["face_field"] = "expression,glasses,quality,emotion" options["max_face_num"] = 10 options["face_type"] = "LIVE" time.sleep(1) """ 带参数调用人脸检测 """ req_dict_face = client.detect(image, imageType, options) return(req_dict_face)
class Face_id(object): def __init__(self): "your baidu ai APP_ID" self.APP_ID = '********' "your baidu ai API_KEY" self.API_KEY = '***************' "your baidu ai SECRET_KEY" self.SECRET_KEY = '*******************' self.aipFace = AipFace(self.APP_ID, self.API_KEY, self.SECRET_KEY) self.photo_name = '' self.group = 'Door' def get_file_content(self): with open(self.photo_name, 'rb') as fp: return fp.read() def get_file_constcontent(self): with open('me.jpg', 'rb') as fp: return fp.read() def face_detect(self): options = { 'max_face_num': 1, 'face_fields': 'age,beauty,expression,faceshape,gender,glasses' } result = self.aipFace.detect(self.get_file_content(), options) return result def face_add(self, group='Door', uid='', user_info='person'): result = self.aipFace.addUser(uid, user_info, group, self.get_file_content()) return result def face_recognize(self, group): options = {'user_top_num': 1} result = self.aipFace.identifyUser(group, self.get_file_content(), options) print result return result def get_user(self, uid='mrlian_door201', group='Door'): result = self.aipFace.getUser(uid) print result def get_group(self, start=0, num=100): options = {'start': start, 'num': num} result = self.aipFace.getGroupList(options) print result def get_groupuser(self, group='1', start=0, num=100): options = {'start': start, 'num': num} result = self.aipFace.getGroupUsers(group, options) return result def del_user(self, uid): result = self.aipFace.deleteUser(uid) return result
def detection(APP_ID, API_KEY, SECRET_KEY, filename, maxnum): client = AipFace(APP_ID, API_KEY, SECRET_KEY) image = base64.b64encode(get_file_content(filename)) image = str(image, 'utf-8') imageType = "BASE64" # 设置 options = {} options['max_face_num'] = 10 options["face_field"] = "age,beauty,expression,faceshape" result = client.detect(image, imageType, options) return result
class Ranking(object): # API配置文件 程序启动首先执行 相当于Java的构造函数 def __init__(self): """ 你的 APPID AK SK """ self.APP_ID = '16896745' self.API_KEY = 'bhFx6Mya2tNHnUf9fItqn6z2' self.SECRET_KEY = 'xfOmbc2KDUxINjGbXf1nf2kIBRBhwXqR' self.client = AipFace(self.APP_ID, self.API_KEY, self.SECRET_KEY) # 调用百度API接口分析获得图片并返回颜值 不懂直接去百度云看人脸识别API文档 def face_rg(self, file_path): with open(file_path, 'rb') as f: data = base64.b64encode(f.read()) # 加密 image = data.decode() options = {} options["face_field"] = "beauty" imageType = "BASE64" """ 调用人脸检测 """ res = self.client.detect(image, imageType, options) return res['result']['face_list'][0]['beauty'] # 获得图片 def get_pic(self): print('获取图片中...') if not os.path.exists('pic'): os.mkdir('pic') for i in range(1, 5): # 图片来源网址 url = f'http://www.7799520.com/api/user/pc/list/search?startage=21&endage=30&gender=2&cityid=197&startheight=161&endheight=170&marry=1&salary=2&page={i}' req = requests.get(url).json() avatars = jsonpath.jsonpath(req, '$..avatar') names = jsonpath.jsonpath(req, '$..username') for avatar, name in zip(avatars, names): urlretrieve(avatar, 'pic' + '\\' + name + '.png') # 颜值排名 def analyze(self): images = os.listdir('pic') print('排名中...') path = r'E:\Py_gather\Creeper\pic' yz = [] yz_dict = {} for image in images: try: score = self.face_rg(path + '\\' + image) name = image[0:-4] yz_dict[score] = name yz.append(score) except: pass yz.sort(reverse=True) for i, b in enumerate(yz): print('小姐姐的名字是{}=====她是第{}名=======她的颜值分{}'.format( yz_dict[b], i + 1, b))
def return_face(self): options = { 'max_face_num': 1, 'face_fields': "age,beauty,expression,faceshape", } aipFace = AipFace(self.APP_ID, self.API_KEY, self.SECRET_KEY) result = aipFace.detect(self.get_file_content(), options) if result['result'] == []: return "illegal" #没人脸 elif result['result'][0]['face_probability'] > 0.7: return "res" #符合 else: return "vague" #模糊
def detection(self): encode_image = self.image_encode_base64() imageType = 'BASE64' #初始化aipfacce对象 aipface = AipFace(self.APP_ID, self.API_KEY, self.SECRET_KEY) #设置 options = { 'max_face_num': 10, 'face_field': 'gender', "face_type": 'LIVE' } #接收返回的检测结果 result = aipface.detect(encode_image, imageType, options) print (result) #初始化统计数据 male_num=0 female_num=0 #定义OpenCV字体 font = cv2.FONT_HERSHEY_SIMPLEX #读取原始图片 cv_image = cv2.imread(self.path_to_save_image) face_num = result['result']['face_num'] #在原图像上标注人脸,并统计男性和女性的数目 for i in range(face_num): location = result['result']['face_list'][i]['location'] left_top = (int(location['left']), int(location['top'])) right_bottom = (int(left_top[0] + location['width']), int(left_top[1] + location['height'])) print ("No.{} face position is: {}".format(i+1, location)) if result['result']['face_list'][i]['gender']['type'] == 'male': cv2.rectangle(cv_image, left_top, right_bottom, (255, 0, 0), 2) cv2.putText(cv_image, 'male',(left_top[0]+30, left_top[1]+30), font, 1.2, (255, 0, 0), 2) if result['result']['face_list'][i]['gender']['type'] == 'female': cv2.rectangle(cv_image, left_top, right_bottom, (0, 0, 255), 2) cv2.putText(cv_image, 'female',(left_top[0]+30, left_top[1]+30), font, 1.2, (0, 0, 255), 2) if result['result']['face_list'][i]['gender']['type'] == 'male' : male_num=male_num+1 if result['result']['face_list'][i]['gender']['type'] == 'female' : female_num = female_num + 1 #生成自定义消息类型的对象 gender_message = GenderDetection() gender_message.female_num = female_num gender_message.male_num = male_num gender_message.sit_num = 0 gender_message.stand_num = 0 #保存并显示处理后的图片 cv2.imwrite(self.path_to_save_result, cv_image) self.pub_result.publish(gender_message) cv2.imshow('result', cv2.imread(self.path_to_save_result)) cv2.waitKey(100)
def detect(APP_ID, API_KEY, SECRET_KEY, image_path, image_maxnum): client = AipFace(APP_ID, API_KEY, SECRET_KEY) # 初始化AirFace对象 imopen = open(image_path, 'rb') # 打开图片 image = base64.b64encode( imopen.read()) # 图片类型 BASE64:图片的base64值,base64编码后的图片数据,需urlencode image64 = str(image, 'utf-8') # 转换string类型 image_type = "BASE64" # 图片类型 BASE64 # 调用人脸检测 如果有可选参数 options = {} options["face_field"] = "age" options["max_face_num"] = image_maxnum options["face_type"] = "LIVE" result = client.detect(image64, image_type, options) return result
def face_rg(file_path): APP_ID = '16363054' API_KEY = 'l2NxG0iy9rTiyV3rbhmTwjgB' SECRET_KEY = 'mcBPYBTeNiC1xznf9cEH5il8jVtmUCgM' client = AipFace(APP_ID, API_KEY, SECRET_KEY) with open(file_path, 'rb') as f: date = base64.b64encode(f.read()) image = date.decode() options = {} imageType = "BASE64" options["face_field"] = "beauty" """ 调用人脸检测 """ result=client.detect(image, imageType,options) beauty = jsonpath.jsonpath(result, '$..beauty') return beauty
def face_rg(filePath): """ 你的 APPID AK SK """ APP_ID = '17478660' API_KEY = 'KnGt4QsKBZqUL7Tuzi9fBqqZ' SECRET_KEY = '9ZUIcTGrqH87qGTlwyM7ZvIOqRAszg9q' client = AipFace(APP_ID, API_KEY, SECRET_KEY) with open(filePath, 'rb') as fp: data = base64.b64encode(fp.read()) image = data.decode() options = {} options["face_field"] = "beauty" imageType = "BASE64" """调用人脸识别""" result = client.detect(image, imageType, options) return result
def detection(self,msg): msg.data=msg.data.lower() if msg.data == 'photo_stored': #读取原始图像 img = cv2.imread(self.filename) cv2.imshow('source',img) #初始化aipfacce对象 aipface = AipFace(self.APP_ID, self.API_KEY, self.SECRET_KEY) #设置 options = { 'max_face_num': 10, 'face_fields':"gender", } #接收返回的检测结果 result = aipface.detect(self.get_file_content(self.filename),options) #print result['result'][0]['gender'] #print result['result_num'] #初始化统计数据 male_num=0 female_num=0 face_num = len(result['result']) #在原图像上标注人脸,并统计男性和女性的数目 for i in range(face_num): location = result['result'][i]['location'] left_top = (location['left'], location['top']) right_bottom = (left_top[0] + location['width'], left_top[1] + location['height']) if result['result'][i]['gender'] == 'male': cv2.rectangle(img, left_top, right_bottom, (255, 0, 0), 2) if result['result'][i]['gender'] == 'female': cv2.rectangle(img, left_top, right_bottom, (0, 0, 255), 2) if result['result'][i]['gender'] == 'male' : male_num=male_num+1 if result['result'][i]['gender'] == 'female' : female_num = female_num + 1 print male_num print female_num #向语音节点发布结果 self.human_pub.publish(str(face_num)) rospy.sleep(3) self.female_pub.publish(str(female_num)) rospy.sleep(3) self.male_pub.publish(str(male_num)) #保存并显示处理后的图片 cv2.imwrite('/home/kamerider/catkin_ws/src/face_detection_with_aip/face_detected.jpg', img) cv2.imshow('result', img) cv2.waitKey(0)
class FaceAPI: """ 你的 APPID AK SK """ APP_ID = '17809644' API_KEY = 'vlN74XYryBmSChGrytjkejqZ' SECRET_KEY = 'Z8NDrLKk53mCeB85PO2Z4STQFNeZ92ok' def __init__(self): # 初始化AipFace对象 self.client = AipFace(self.APP_ID, self.API_KEY, self.SECRET_KEY) # 人脸检测 def face_detect(self, fileName): image = imgToBase64(fileName) imageType = "BASE64" """ 如果有可选参数 """ options = {} options["face_field"] = "age" options["max_face_num"] = 2 options["face_type"] = "LIVE" options["liveness_control"] = "LOW" """ 带参数调用人脸检测 """ result = self.client.detect(image, imageType, options) return result # 图片匹配 def face_match(self, picPathName01, picPathName02): result = self.client.match([{ 'image': imgToBase64(picPathName01), 'image_type': 'BASE64', }, { 'image': imgToBase64(picPathName02), 'image_type': 'BASE64', }]) return result # 活体检测 def face_verify(self, picPathName01, picPathName02): result = self.client.faceverify([{ 'image': imgToBase64(picPathName01), 'image_type': 'BASE64', }, { 'image': imgToBase64(picPathName02), 'image_type': 'BASE64', }]) return result
def shibe_o(file): """ 你的 APPID AK SK """ APP_ID = '17817245' API_KEY = 'k1KhcY1c1v8MtiwF45XmkM5t' SECRET_KEY = 'G7QxCRnjz1Yep3Grjn1vD6xWNp4vLdqX' client = AipFace(APP_ID, API_KEY, SECRET_KEY) with open(file, "rb") as f: data = f.read() encodestr = base64.b64encode(data) # 得到 byte 编码的数据 images = str(encodestr, 'utf-8') # 重新编码数据 image = images imageType = "BASE64" """ 如果有可选参数 """ options = {} options[ "face_field"] = "age,beauty,expression,face_shape,gender,glasses,emotion,face_probability,eye_status,landmark,quality" """ 带参数调用人脸检测 """ m = client.detect(image, imageType, options) if m["error_msg"] == "SUCCESS": mm = m["result"] """print(mm)""" num = mm["face_num"] mmm = mm["face_list"][0] age = mmm["age"] beauty = mmm["beauty"] # 表情 exp = {'none': "不笑", 'smile': "微笑", 'laugh': "大笑"} expression = mmm["expression"]['type'] if expression in exp: expressions = exp[expression] else: expressions = "未知" global str3 print("年龄:%d, 颜值:%d, 表情:%s" % (age, beauty, expressions)) str3 = "\n\n更换发型后可能的数据\n年龄:" + str(age) + ", 颜值:" + str( beauty) + ", 表情:" + expressions str3 = str3.replace(" ", "#") str3 = str3.replace("\n", "@") else: print("人脸有误") str3 = "人脸有误"
def detect_person(): APP_ID = '11304911' API_KEY = 'pbW5Gp5iw2EFY6KVs9bOjmWe' SECRET_KEY = 'Z3oXfUVfwAMmb5NZhq94mWs16pUMnO4c' client = AipFace(APP_ID, API_KEY, SECRET_KEY) with open('test1.jpg', 'rb') as f: pic1 = f.read() temp = client.detect((b64encode(pic1)).decode(), 'BASE64') try: probability = temp['result']['face_list'][0]['face_probability'] if probability < 0.5: print('抱歉识别失败') return ('抱歉识别失败') else: print('你好,你是陌生人') return('你好,你是陌生人') except TypeError: print('抱歉识别失败') return ('抱歉识别失败')
def aip_client(image_path): """ 你的 APPID AK SK """ APP_ID = '10848231' API_KEY = 'NqlZYpBvgebz6rCRB0n4nGGQ' SECRET_KEY = 'm5ic5LO52gDUMQ2p2S9uGUOvlljgzRyl' client = AipFace(APP_ID, API_KEY, SECRET_KEY) imageType = "BASE64" options = {} options[ "face_field"] = "age,beauty,face_shape,gender,glasses,race,expression" #需要检测的参数 options["max_face_num"] = 1 #默认检测图中最大的那张脸盘 options["face_type"] = "LIVE" """ 带参数调用人脸检测 """ with open(image_path, "rb") as f: #二进制读入 img = base64.b64encode(f.read()) #b64编码 image = str(img, 'utf-8') res_all = client.detect(image, imageType, options) msg_list = [] error_code = res_all['error_code'] #错误代码 msg_list.append(str(error_code)) if int(error_code) == 0: error_msg = res_all['error_msg'] #错误信息 res_all_temp = res_all['result']['face_list'][0] age = res_all_temp['age'] #检测年龄 msg_list.append(str(age)) race = res_all_temp['race']['type'] #检测肤色 msg_list.append(race) beauty = res_all_temp['beauty'] #检测颜值 msg_list.append(str(beauty)) glasses = res_all_temp['glasses']['type'] #是否佩戴眼镜 msg_list.append(glasses) face_shape = res_all_temp['face_shape']['type'] #检测脸型 msg_list.append(face_shape) gender = res_all_temp['gender']['type'] #检测性别 msg_list.append(gender) expression = res_all_temp['expression']['type'] #检测表情 msg_list.append(expression) return msg_list return "1"
def face_recognize(config): client = AipFace(config[0], config[1], config[2]) while (1): photo.capture_photo() image = photo.image_read('photo.png') image = str(image, 'utf-8') detect_result = client.detect(image, "BASE64") if detect_result['result']['face_list'][0]['face_probability'] > 0.6: search_result = client.search(image, "BASE64", config[3]) if search_result['result']['user_list'][0]['score'] > 70: print("Recognize successfully!") print("Recognize score:", search_result['result']['user_list'][0]['score']) print("Clint_name:", search_result['result']['user_list'][0]['user_id']) break else: continue else: continue
def connectwithbaiduai(file_path): ''' @param: file_path: a string of the image's file name @return: a string indicating the image's gender connect with baidu ai and get the json data ref: https://www.cnblogs.com/dmass36/p/10182183.html ''' #百度接口信息 APP_ID = '16617513' API_KEY = 'ZfZGzKTMMdC82ZkmZKMevvG3' SECRET_KEY = 'PKpDDoLBIfNjLUAoSaQBT5cXpv5qqlIL' client = AipFace(APP_ID, API_KEY, SECRET_KEY) imageType = "BASE64" #定义参数变量 options = {} options["max_face_num"] = 10 options["face_field"] = "gender" # 初始化AirFace对象 aipface = AipFace(APP_ID, API_KEY, SECRET_KEY) #打开文件 with open(file_path, 'rb') as fp: # infile = fp.read() base64_date = base64.b64encode(fp.read()) image = str(base64_date, encoding='utf-8') result = client.detect(image, imageType, options) #将百度接口返回的数据转成json对象 json_str = json.dumps(result) #对数据进行解码 json_data = json.loads(json_str) return json_data
from aip import AipFace """ 你的 APPID AK SK """ APP_ID='' API_KEY='' SECRET_KEY='' '''创建应用''' client=AipFace(APP_ID,API_KEY,SECRET_KEY) '''人脸检测图片参数传入''' image = "http://youboyu.cn/wp-content/uploads/2018/08/eee.jpg" imageType='URL' """ 如果有可选参数 """ options={} options['face_field']='age,beauty' options['max_face_num']=1 options['face_type']='LIVE' """ 带参数调用人脸检测 """ result=client.detect(image,imageType,options) print(result)
from aip import AipFace import os import io APP_ID = 'f28be295cced4fb59bc2c0954b7530a5 ' API_KEY = '014caeebc5704738ad108aec0f80990c' SECRET_KEY = '3258586a65904692abd35106d8c2bc23' filePath = 'g:\\pic1.jpg' aipFace = AipFace(APP_ID, API_KEY, SECRET_KEY) def get_file_content(filePath): with open(filePath, 'rb') as fp: return fp.read() options = { 'max_face_num': 1, 'face_fields': "age,beauty,expression,faceshape", } result = aipFace.detect(get_file_content('g:\thepic.jpg'), options)
""" 如果有可选参数 """ options = {} options["face_field"] = "age" options["max_face_num"] = 10 options["face_type"] = "LIVE" while True: ret, frame = cap.read() cv2.imshow("capture", frame) cv2.imwrite(r"D:\python\faceplusplus\facelibrary\face1.jpg", frame) with open(r"D:\python\faceplusplus\facelibrary\face1.jpg", 'rb') as f: # 以二进制读取图片 data = f.read() encodestr = base64.b64encode(data) # 得到 byte 编码的数据 image = str(encodestr, 'utf-8') # 重新编码数据 response = client.detect(image, imageType, options) print("检测结果:", response) if response['error_msg'] == 'SUCCESS': width = [] top = [] height = [] left = [] img = cv2.imread("xxx.jpg") vis = img.copy() for i in range(response['result']['face_num']): width.append( response['result']['face_list'][i]['location']['width']) top.append(response['result']['face_list'][i]['location']['top']) left.append(response['result']['face_list'][i]['location']['left']) height.append(