Animal recognition with Baidu API

百度API

import base64
import requests

API_KEY = "xxx"
SECRET_KEY = "xxx"

def main():
    url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/animal?access_token=" + get_access_token()
    with open("/Users/lijing/Desktop/baiduai/chicken1.jpeg", 'rb') as f:
        img = base64.b64encode(f.read())

    payload = {
    
    "image": img}
    headers = {
    
    
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)

    print(response.text)


def get_access_token():
    """
    使用 AK,SK 生成鉴权签名(Access Token)
    :return: access_token,或是None(如果错误)
    """
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {
    
    "grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
    return str(requests.post(url, params=params).json().get("access_token"))


if __name__ == '__main__':
    main()

猜你喜欢

转载自blog.csdn.net/azenlijing/article/details/129022049