#!/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("請輸入圖片地址?\n請您輸入:") 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(目標圖片)空格隔開?\n請您輸入:").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("請輸入圖片地址?\n請您輸入:") f1 = open(r'%s' % url_pic, 'rb') pic = base64.b64encode(f1.read()) f1.close() return pic else: file1path, file2path = map(str, input("請輸入圖片地址a,b空格隔開?\n請您輸入:").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()