调用百度API实现人脸对比

这篇博客介绍了如何通过Python调用百度AI的人脸对比API进行人脸比对。首先,需要注册百度账号并创建应用获取APIKey和SecretKey。然后,利用base64编码处理图片,并使用access_token发送POST请求进行人脸对比。示例代码中展示了从本地文件读取图片并进行对比,输出了相似度分数。进一步扩展,可以结合摄像头实现实时人脸对比。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

百度API人脸对比
1.首先注册一个百度账号
2.百度AI平台https://ai.baidu.com/,找到 开放能力>人脸与人体检测>人脸对比>立即使用>创建应用
,点击 创建 获取API KeySecret Key

百度人脸识别接口链接:https://ai.baidu.com/tech/face/compare

参考技术文档:人脸对比https://ai.baidu.com/ai-doc/FACE/Lk37c1tpf
人脸对比接口
创建API接口示例

from urllib import request
import requests
import json
import base64

def gettoken():
    ak = '******' #获取到的API Key
    sk = '******' #获取到的Secret Key
    host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id='+ak+'&client_secret='+sk
    my_request = request.Request(host)
    my_request.add_header('Content-Type', 'application/json; charset=UTF-8')
    response = request.urlopen(my_request)
    content = response.read() #获得请求结果
    content = bytes.decode(content)#结果转化为字符
    content = eval(content[:-1])#转化为字典
    return content['access_token']
#图片转码
def to_base64(file_name1,file_name2):
    with open(file_name1,'rb')as f1:
        base64_data1 = base64.b64encode(f1.read())
        image_1 = str(base64_data1,'utf-8')
    with open(file_name2,'rb')as f2:
        base64_data2 = base64.b64encode(f2.read())
        image_2 = str(base64_data2,'utf-8')
        return image_1,image_2

request_url = "https://aip.baidubce.com/rest/2.0/face/v3/match"
image_1, image_2 = to_base64('1.jpg','3.jpg')
params = json.dumps(
[{"image": image_1, "image_type": "BASE64", "face_type": "LIVE", "quality_control": "LOW"},
{"image": image_2, "image_type": "BASE64", "face_type": "CERT", "quality_control": "LOW"}]).encode(encoding='UTF8')

access_token = gettoken()
request_url = request_url + "?access_token=" + access_token
my_request = request.Request(url=request_url,data = params)
my_request.add_header('Content-Type','json')
#urlencode处理需提交的数据
response = request.urlopen(my_request)
null =0
content = response.read()
content = bytes.decode(content)
content = eval(content)
result = content['result']
score = result['score']
print('相似度:',score)

打印对比结果。
对比效果
进阶的话可以通过摄像头拍摄照片保存,修改image的路径即可实现拍照对比。

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值