百度AI学习第一天_调用API接口通用步骤
#第一步获取access_token
# 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())
access_token = (response.json())['access_token']
print(access_token)
#第二步获取url
request_url = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add?access_token=获取的access_token"#根据需要选择
#第三步配置headers参数以及请求参数
其中请求参数可以参考https://cloud.baidu.com/doc/FACE/s/Gk37c1uzc
headers = {'content-type': 'application/json'}
#第四步发送请求参数,并得到返回的值存在response中
response = requests.post(request_url, data=params, headers=headers)
#第五步查看返回参数
其中返回的可以参考以下:
if response :
pprint (response.json())
下面给出人脸搜索的一个例子
'''
进行人脸搜索
'''
import requests
import base64
from urllib import parse
from pprint import *
import urllib
import json
#第一步获取access_token
# 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())
access_token = (response.json())['access_token'] # 提取access_token
print(access_token)
#第二步获取url
request_url = "https://aip.baidubce.com/rest/2.0/face/v3/search?access_token="+ access_token#进行1:N搜索
#第三步配置headers参数以及请求参数
headers = {'content-type': 'application/json'}
# 根据这里提供的照片去人脸库进行搜索
with open('C:/Users/MECHREVO/Pictures/Camera Roll/3.jpg','rb')as f:
img_jpg = f.read() # 以二进制读取图片
img64 = base64.b64encode(img_jpg) # 对图片进行base64编码
params = {}
params['image'] = img64
params['image_type'] = 'BASE64'
params['group_id_list'] = 'xxxx'#这里为组的名字
params['max_face_num'] = 10
params = urllib.parse.urlencode(params).encode() # params为字典,需要对它进行编码
#第四步发送请求参数,并得到返回的值存在response中
response = requests.post(request_url, data=params, headers=headers)
#第五步查看返回参数
if response :
pprint (response.json())