1.创建应用
想要调用百度的API进行人脸比对,首先需要登录百度智能云https://cloud.baidu.com/,在其控制台中创建人脸比对应用,如图:
创建好后,记录该应用的API KEY 和 Secret Key。
2.查看技术文档
人脸比对API请求文档: http://ai.baidu.com/docs#/Face-Match-V3/top
查看技术文档可知道,百度API调用具有鉴权认证机制,人脸比对请求头需要携带access_token参数,如图:
而access_token是通过API Key 和 Secret Key 获取的。
Access Token获取方法: http://ai.baidu.com/docs#/Auth/top
获取到access_token值后,将其保存起来,在之后人脸比对请求中使用。人脸比对请求的数据为json格式,如下图:
json字符拼接如下图所示,需要导入json和base64两个包。
image_data = json.dumps([
{"image": str(base64.b64encode(pic1), "utf-8"),"image_type":"BASE64","face_type":"LIVE","quality_control":"NORMAL","liveness_control":"NORMAL"},
{"image": str(base64.b64encode(pic2), "utf-8"),"image_type":"BASE64","face_type":"LIVE","quality_control":"NORMAL","liveness_control":"NORMAL"}
])
3.准备两张需要比对的图片:
4.参考程序源码: ( 需要修改client_id和client_secret为自己应用的API KEY 和 Secret Key )
import json
import base64
import requests
# 1.读取两张图片数据,整合两张图片 json数据
with open("1.jpg","rb") as f:
pic1 = f.read()
with open("2.jpg","rb") as f:
pic2 = f.read()
image_data = json.dumps([
{"image": str(base64.b64encode(pic1), "utf-8"),"image_type":"BASE64","face_type":"LIVE","quality_control":"NORMAL","liveness_control":"NORMAL"},
{"image": str(base64.b64encode(pic2), "utf-8"),"image_type":"BASE64","face_type":"LIVE","quality_control":"NORMAL","liveness_control":"NORMAL"}
])
# 2.拼接人脸识别API接口
get_token = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=XXX&client_secret=XXX"
API_url = "https://aip.baidubce.com/rest/2.0/face/v3/match?access_token="
text = requests.get(get_token).json()
print(text['access_token'])
url = API_url + text['access_token']
print(url)
# 3.请求API接口传入json数据,返回图片相似度
response = requests.post(url, image_data).json()
print(response)
score = response['result']['score']
print("相似度为:{}%".format(score))
if score > 80:
print("是同一个人")
else:
print("不是同一个人")
5.程序运行结果:
比对结果为两张图片相似度89.6%,当相似度大于80%时可认为是同一个人,本次执行人脸比对结果准确无误。