帮我写一个百度ai人脸识别的python源码
时间: 2023-06-09 08:04:26 浏览: 48
好的,以下是代码:
```python
import requests
import base64
# 根据百度AI开放平台的要求,先获取access_token
host = '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:
access_token = response.json()['access_token']
# 读取图片并进行base64编码
with open('test.jpg', 'rb') as f:
image = base64.b64encode(f.read())
image = str(image, 'utf-8')
# 设置要访问的接口
request_url = "https://aip.baidubce.com/rest/2.0/face/v3/detect"
# 设置请求参数
params = {
"image": image,
"image_type": "BASE64",
"face_field": "faceshape,facetype",
"max_face_num": "10"
}
headers = {
"Content-Type": "application/json",
}
access_token = access_token
request_url = request_url + "?access_token=" + access_token
# 发送请求并处理响应结果
response = requests.post(request_url, headers=headers, json=params)
result = response.json()
print(result)
```
运行代码前,需要先替换其中的API Key和Secret Key为自己在百度AI开放平台申请的相应key。并且需要将要识别的图片命名为`test.jpg`并与代码保存在同一目录下。识别结果会以JSON格式输出到控制台。