import requests
import base64
import json
def Get_API(): #To obtain API
#注册百度智能云脸比对接口,获取API密钥和秘钥。
#client_id = 'API Key'
client_id = '******'
#client_secret = 'Secret Key'
client_secret = '******'
host = '/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s'%(client_id,client_secret)
#构造一个函数,从服务器请求Access_token的值,并生成人脸比较API。
response=requests.get(host) #从requests.get(url)中构造一个url对象,该对象向服务器请求一个资源
access_token=eval(response.text)['access_token'] #返回请求的str的值,并取出“access_token”
request_url='/rest/2.0/face/v3/match'
API = request_url + "?access_token=" + access_token #Stitching API
#API = "/rest/2.0/face/v3/match"+"?access_token="+access_token
return API
def Image_coding(img1,img2): #Base64 encoding of the images
f=open(r'%s' % img1,'rb')
pic1=base64.b64encode(f.read()) #Image1 Base64 encoding
f.close()
f=open(r'%s' % img2,'rb')
pic2=base64.b64encode(f.read()) #Image2 Base64 encoding
f.close()
params=json.dumps([
{"image":str(pic1,"utf-8"),"image_type":'BASE64',"face_type":"LIVE"},
{"image":str(pic2,"utf-8"),"image_type":'BASE64',"face_type":"IDCARD"}])
#Add a "liveness_control" option to identify if the person in the picture is a real person
'''params=json.dumps([
{"image":str(pic1,"utf-8"),"image_type":'BASE64',"face_type":"LIVE","liveness_control": "HIGH"},
{"image":str(pic2,"utf-8"),"image_type":'BASE64',"face_type":"IDCARD","liveness_control": "HIGH"}])'''
return params #Return image parameters
def Image_contrast(img1,img2): #Analyze images and compare them
API=Get_API() #obtain API
params=Image_coding(img1,img2) #Base64 encoding of the images
content=requests.post(API,params).text #Requests for posts are sent as form forms
score=eval(content)['result']['score'] #Calculate the score
if score>=60: #Set the threshold
print('二人相似度得分为 %s, 是同一人的可能性极大'%str(score))
else:
print('二人相似度得分为 %s, 不是同一人的可能性极大'%str(score))
Image_contrast("ziqiwen.jpg","huangzz.jpg") #To run the program