Python利用百度AI平台实现人脸识别(登录注册)
百度AI平台提供的接口十分丰富,对于做项目来说,百度AI是一个很好的开放平台,利用百度提供的接口来实现人脸识别,而且可以无限制调用,不仅功能强大还很方便,非常适合我们。
实现步骤
一、安装baidu-aip模块(pip3 install baidu-aip)
二、获取百度AI接口密钥
进入百度AI官方网站:百度AI开放平台
三、调用百度接口识别人脸
创建应用成功后即可获得AppID、API Key、Secret Key,以及可查看操作内容和添加人脸库等技术文档,进行学习操作。
人脸注册:向人脸库中添加人脸
请求URL数据格式:
request_url = 'https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add'
# encoding:utf-8
import requests
# client_id 为官网获取的AK, client_secret 为官网获取的SK
host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=【官网获取的AK】&client_secret=【官网获取的SK】'
response = requests.get(host)
if response:
print(response.json())
向API服务地址使用POST发送请求,必须在URL中带上参数access_token,可通过后台的API Key和Secret Key生成。
图片转换:
百度Api支持的图片格式是base64,因此我们要将图片转换为base64格式。图片类型 BASE64:图片的base64值,base64编码后的图片数据,编码后的图片大小不超过2M
img_data = 'image.jpg'
data = base64.b64encode(img_data)
image = data.decode()
imageType = "BASE64"
调用人脸注册:
# encoding:utf-8
import requests
'''
人脸注册
'''
request_url = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add"
params = "{\"image\":\"027d8308a2ec665acb1bdf63e513bcb9\",\"image_type\":\"FACE_TOKEN\",\"group_id\":\"group_repeat\",\"user_id\":\"user1\",\"user_info\":\"abc\",\"quality_control\":\"LOW\",\"liveness_control\":\"NORMAL\"}"
access_token = '[调用鉴权接口获取的token]'
request_url = request_url + "?access_token=" + access_token
headers = {'content-type': 'application/json'}
response = requests.post(request_url, data=params, headers=headers)if response:
print (response.json())
返回示例:
{
"face_token": "2fa64a88a9d5118916f9a303782a97d3",
"location": {
"left": 117,
"top": 131,
"width": 172,
"height": 170,
"rotation": 4
}}
人脸搜索 1:N 识别:将一张人脸图片在人脸库的中进行搜索,返回最相似的一张或多张人脸及对应相似度
请求URL数据格式:request_url = "https://aip.baidubce.com/rest/2.0/face/v3/search"
调用人脸搜索:
# encoding:utf-8
import requests
'''
人脸搜索
'''
request_url = "https://aip.baidubce.com/rest/2.0/face/v3/search"
params = "{\"image\":\"027d8308a2ec665acb1bdf63e513bcb9\",\"image_type\":\"FACE_TOKEN\",\"group_id_list\":\"group_repeat,group_233\",\"quality_control\":\"LOW\",\"liveness_control\":\"NORMAL\"}"
access_token = '[调用鉴权接口获取的token]'
request_url = request_url + "?access_token=" + access_token
headers = {'content-type': 'application/json'}
response = requests.post(request_url, data=params, headers=headers)if response:
print (response.json())
返回示例:
{
"face_token": "fid",
"user_list": [
{
"group_id" : "test1",
"user_id": "u333333",
"user_info": "Test User",
"score": 99.3
}
]
}