有点懒,直接上完整代码
import json
import requests
API_KEY = 'xxxxxxxxxxxx' # 官网的api_key
SECRET_KEY = 'xxxxxxxxxxxx' # 官网的secret_key
GROUP_ID = 'xxxxxx' # 所属组
HEADERS = {'content-type': 'application/json'} # 请求头
def get_access_token():
'''获取access_token'''
request_url = f'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={API_KEY}&client_secret={SECRET_KEY}'
response = requests.get(url=request_url, headers=HEADERS)
content = response.content
access_token = json.loads(content)["access_token"]
return access_token
def binary_pictures():
'''二进制读取图片'''
import base64
with open("./images/成龙1.jpg", 'rb') as f:
imageB = base64.b64encode(f.read())
image = str(imageB, 'utf-8')
return image
def request_to_retrieve_api(image, access_token):
'''请求检索api'''
request_url = "https://aip.baidubce.com/rest/2.0/face/v3/search"
params = {"image_type": "BASE64", "group_id_list": "pur_water", "quality_control": "LOW"}
params["image"] = image
request_url = request_url + "?access_token=" + access_token
response = requests.post(url=request_url, data=params, headers=HEADERS)
content = eval(response.text)
return content
if __name__ == '__main__':
# 获取access_token
access_token = get_access_token()
# 二进制打开索要搜索的图片
image = binary_pictures()
# 请求
respnse_content = request_to_retrieve_api(image, access_token)
# 提取user_id
user_id = respnse_content['result']['user_list'][0]['user_id']
print(user_id)
引用
https://www.cnblogs.com/ningxinjie/p/11291152.html