#!/usr/bin/python3 # 百度人脸对比 & 人脸检测api-v3 import sys, tkinter.messagebox, ast import ssl, json,requests import pdb import base64 from urllib import request, parse from aip import AipFace ssl._create_default_https_context = ssl._create_unverified_context class BaiDuAipFaceAndFaceIdentify(object): def __init__(self): # client_id 为官网获取的AK, client_secret 为官网获取的SK self.__client_id = "mH7LbbbnfolCy55Tp6xIXA5N" self.__client_secret = "8vokD7ug44e2LzZHvfb0zPTUTTUTfc79" self.get_token_url = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s' % ( self.__client_id, self.__client_secret) self.match_url = 'https://aip.baidubce.com/rest/2.0/face/v3/match?access_token=' self.token = 0 # 获取token def get_token(self): req = request.Request(self.get_token_url) req.add_header('Content-Type', 'application/json; charset=UTF-8') response = request.urlopen(req) # 获得请求结果 content = response.read() # print(content) # 结果转化为字符 content = bytes.decode(content) # 转化为字典 content = eval(content[:-1]) self.__token = content['access_token'] # 转换图片 # 读取文件内容,转换为base64编码 # 二进制方式打开图文件 def imgdata(self, file1path, file2path): f1 = open(r'%s' % file1path, 'rb') pic1 = base64.b64encode(f1.read()) f1.close() f2 = open(r'%s' % file2path, 'rb') pic2 = base64.b64encode(f2.read()) f2.close() # 将图片信息格式化为可提交信息,这里需要注意str参数设置 params = json.dumps([{"image": str(pic1, 'utf-8'), "image_type": "BASE64" # "face_type":"LIVE", # "quality_control":"LOW" # "liveness_control":"NONE" }, {"image": str(pic2, 'utf-8'), "image_type": "BASE64" # "face_type": "LIVE", # "quality_control": "LOW" # "liveness_control": "NONE" }, ]) return params # 提交进行对比获得结果 def FaceMath(self): token = self.__token pics = self.base64_img(2) # 将图片信息格式化为可提交信息,这里需要注意str参数设置 params = [] for pic in pics: params.append({"image": str(pic, 'utf-8'), "image_type": "BASE64" # "face_type":"LIVE", # "quality_control":"LOW" # "liveness_control":"NONE" }) # pdb.set_trace() params = json.dumps(params) url = self.match_url + token # urlencode处理需提交的数据 content = self.post(url,params) # 获得分数 score = content['result']['score'] tkinter.messagebox.showinfo('图片相似度','两个人的相似度为:%d'%score) if score > 80: print('照片相似度:' + str(score) + ',为同一个人') else: print('照片相似度:' + str(score) + ',不是同一个人') # 此函数进行人脸识别,返回识别到的人脸列表 # 此函数被parse_face_pic调用,没用到 """ def identify_faces(self, pic, url_fi): headers = { 'Content-Type': 'application/json; charset=UTF-8' } post_data = { 'image': pic, 'image_type': 'BASE64', 'face_field': 'facetype,gender,age,beauty', # expression,faceshape,landmark,race,quality,glasses 'max_face_num': 2 } response_fi = requests.post(url_fi, headers=headers, data=post_data) json_fi_result = json.loads(response_fi.text) return json_fi_result['result']['face_list'] # 下边的print也许是最直观,你最想要的 # print(json_fi_result['result']['face_list'][0]['age']) # print(json_fi_result['result']['face_list'][0]['beauty']) """ # 此函数用于解析进行人脸图片,输出图片上的人脸的性别、年龄、颜值 # 此函数调用identify_faces def parse_face_pic(self): url_pic = input("请输入图片地址? 请您输入:") f1 = open(r'%s' % url_pic, 'rb') pic = base64.b64encode(f1.read()) f1.close() # 调用get_access_token获取access_token access_token = self.__token url = 'https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=' + access_token # 调用identify_faces,获取人脸列表 #json_faces = self.identify_faces(pic, url_fi) params = json.dumps({ 'image':str(pic, 'utf-8'), 'image_type': 'BASE64', 'face_field': 'facetype,gender,age,beauty', # expression,faceshape,landmark,race,quality,glasses 'max_face_num': 2 }) json_faces = self.post(url, params) pdb.set_trace() if len(json_faces) == 0: print('未识别到人脸') else: for json_face in json_faces['result']['face_list']: #pdb.set_trace() # 调试 print('种类:' + json_face['face_type']['type']) if str(json_face['gender']['type']) == 'female': print('性别: 女' ) else: print('性别: 男') print('年龄:' + str(json_face['age'])) print('颜值:' + str(json_face['beauty'])) #face_merge 暂时没有v3 api ,所以暂时没用 def face_merge(self): file1path, file2path = map(str, input("请输入需要融合图片地址a(模版),b(目标图片)空格隔开? 请您输入:").split()) f1 = open(r'%s' % file1path, 'rb') pic1 = base64.b64encode(f1.read()) f1.close() f2 = open(r'%s' % file2path, 'rb') pic2 = base64.b64encode(f2.read()) f2.close() headers = { 'Content-Type': 'application/json; charset=UTF-8' } post_data = {"image_template": {'image': pic1, 'image_type': 'BASE64', 'quality_control': "NONE" }, "image_target": {'image': pic2, 'image_type': 'BASE64', 'quality_control': "NONE" } } access_token = self.__token url_fi = 'https://aip.baidubce.com/rest/2.0/face/v1/merge?access_token=' + access_token response_fi = requests.post(url_fi, headers=headers, data=post_data) json_fi_result = json.loads(response_fi.text) print(json_fi_result) pdb.set_trace() #face_faceverify def face_faceverify(self): pics = self.base64_img(2) # 将图片信息格式化为可提交信息,这里需要注意str参数设置 params=[] for pic in pics: params.append({"image": str(pic, 'utf-8'), "image_type": "BASE64", 'face_field': "age,beauty,expression" }) #pdb.set_trace() params = json.dumps(params) access_token = self.__token url = 'https://aip.baidubce.com/rest/2.0/face/v3/faceverify?access_token=' + access_token content = self.post(url,params) #pdb.set_trace() for json_face in content['result']['face_list']: # pdb.set_trace() # 调试 print('表情:' + json_face['expression']['type']) print('年龄:' + str(json_face['age'])) print('颜值:' + str(json_face['beauty'])) #post 请求工具方法 def post(self,url,params): req = request.Request(url=url, data=params.encode('utf-8')) req.add_header('Content-Type', 'application/json; charset=UTF-8') response = request.urlopen(req) content = response.read() content = content.decode('utf-8') #print(content) content = ast.literal_eval(content) return content #本地图片上传base64 #type 1 /单张图片 2 /两张图片 def base64_img(self,type): imgs = [] if type==1: url_pic = input("请输入图片地址? 请您输入:") f1 = open(r'%s' % url_pic, 'rb') pic = base64.b64encode(f1.read()) f1.close() return pic else: file1path, file2path = map(str, input("请输入图片地址a,b空格隔开? 请您输入:").split()) f1 = open(r'%s' % file1path, 'rb') imgs.append(base64.b64encode(f1.read())) f1.close() f2 = open(r'%s' % file2path, 'rb') imgs.append(base64.b64encode(f2.read())) f2.close() return imgs if __name__ == '__main__': # file1path = './1.png' # file2path = './2.png' b = BaiDuAipFaceAndFaceIdentify() b.get_token() #调用人脸对比方法 b.FaceMath() #调用人脸检测方法 b.parse_face_pic() #调用在线活体检测 b.face_faceverify()