【百度人脸识别】》人脸对比接口的调用
程序员文章站
2022-07-12 19:42:18
...
大概流程:
进入百度云的人脸识别控制台
https://console.bce.baidu.com/?_=1602320265738#/index/overview
创建人脸识别应用
创建完成后,点击“返回应用列表”进行下一步操作。
API文档
https://cloud.baidu.com/doc/FACE/s/Lk37c1tpf
文档里已经说明首先要获取AccessToken,,这里很简单(可通过后台的API Key和Secret Key生成)
# 获取调用接口所需的AccessToken
host = f'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={API_Key}&client_secret={Secret_Key}'
response = requests.get(host)
if response:
# print(response.json())
Access_Token = response.json().get('access_token')
print(Access_Token)
最后调用对比接口
API文档中得知请求方式是POST
先构造参数
需要对两张图片进行base64编码
with open("6b4.jpg", "rb") as f:
# b64encode:编码,b64decode: 解码
base64_6b4 = base64.b64encode(f.read())
with open("75d.jpg", "rb") as f:
# b64encode:编码,b64decode: 解码
base64_75d = base64.b64encode(f.read())
然后根据文档构造请求
headers = {'content-type': 'application/json'}
URL = 'https://aip.baidubce.com/rest/2.0/face/v3/match' + "?access_token=" + Access_Token
resp = requests.post(URL, data=payload, headers=headers)
if resp:
print(resp.json())
return jsonify(resp.json())
return jsonify('出错了!!!')
完整代码
import json
from flask import Flask, jsonify
from face_baidu.constants import API_Key, Secret_Key
import requests
import base64
app = Flask(__name__)
@app.route('/bd_face')
def face_recognition():
Access_Token = None
# 获取调用接口所需的AccessToken
host = f'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={API_Key}&client_secret={Secret_Key}'
response = requests.get(host)
if response:
# print(response.json())
Access_Token = response.json().get('access_token')
print(Access_Token)
# 进行人脸识别调用接口
with open("6b4.jpg", "rb") as f:
# b64encode:编码,b64decode: 解码
base64_6b4 = base64.b64encode(f.read())
with open("75d.jpg", "rb") as f:
# b64encode:编码,b64decode: 解码
base64_75d = base64.b64encode(f.read())
payload = json.dumps([
{'image': str(base64_75d, 'utf-8'), 'image_type': 'BASE64'},
{'image': str(base64_6b4, 'utf-8'), 'image_type': 'BASE64'},
])
payload = payload.encode(encoding='UTF8')
headers = {'content-type': 'application/json'}
URL = 'https://aip.baidubce.com/rest/2.0/face/v3/match' + "?access_token=" + Access_Token
resp = requests.post(URL, data=payload, headers=headers)
if resp:
print(resp.json())
return jsonify(resp.json())
return jsonify('出错了!!!')
if __name__ == '__main__':
app.run()
其实就这样简单。不过有几个注意点(这是最坑的地方吧):
1、有人会出现这个问题
啥意思,就是说请求体应该被json格式化其实文档里有说过
我做的处理如下(既然他要json就转一下吗)
2、基于问题一修改后发现
为啥会出现这个问题(字节类型的对象不能json序列化),还记得对图片的处理吗?把图片进行base64编码了,他就是二进制,所以这里要对他进行特殊处理如下
我把他强行搞成utf-8的字符串
再次调试成功