python调用百度API实现图片识别标题

python调用百度API实现图片识别标题

1. 获取access_token
  1. 请求网址为:

  2. 其必须携带三个参数:

    • grant_type:默认为client_credentials
    • client_id:在百度智能云中创建的实例 APP ID
    • client_secret:在百度智能云中创建的实例 Secret Key

    代码如下:

    import requests
    
    url = "https://aip.baidubce.com/oauth/2.0/token"
    data = {
        "grant_type": "你的实例APP ID",
        "client_id": "你的实例Secret Key",
        "client_secret": "vmm1UfuvX3FzqiEGEBeU0s2tfmeRRDTq"
    }
    response = requests.post(url, data=data)
    content_json = response.json()
    access_token = content_json.get("acess_token")
    print(access_token)
    
2. 实现图片识别
  1. 请求头headers:{Content-Type": “application/json;charset=utf-8”}

  2. 注意:请求的参数必须为json格式,不然会报参数错误282004,即下面代码中的params

  3. 图片分为网络图片imgUrl本机图片image

    import requests
    import json
    import base64
    
    
    access_token = '24.b2eb97e02ac6ad58262457cb6eb2f588.2592000.1598533125.282335-19765629'
    request_url = "https://aip.baidubce.com/api/v1/solution/direct/imagerecognition/combination"
    request_url = request_url + "?access_token=" + access_token
    headers = {"Content-Type": "application/json;charset=utf-8"} # 请求头
    
    print("请输入图片地址:(图片的网络地址或者此电脑的绝对地址)")
    input_img_url = input()
    
    if "http" in input_img_url: # 如果图片为网络地址
        img_type = "imgUrl"
        img_url = input_img_url
    else:                       # 图片为电脑中的地址
        img_type = "image"
        with open(input_img_url, 'rb') as f:
            base64_data = base64.b64encode(f.read()) # 使用base64编码
            img_url = base64_data.decode()   # 获取base64格式码
    
    
    params = {
        img_type: img_url,
        "scenes": ["animal", "plant", "ingredient", "dishs", "red_wine", "currency", "landmark"],
    }
    params = json.dumps(params)  # 转换为json格式
    
    
    response = requests.post(request_url, data=params, headers=headers)
    result = response.json()
    scenes_json = result.get("result")
    scenes_list = ["animal", "plant", "ingredient", "dishs", "red_wine", "currency", "landmark"]  # 识别的类型
    if scenes_json: 
        for item in scenes_list:
            name = scenes_json.get(item).get("result") 
            if type(name) is list:
                img_name = name[0].get("name") 
                if '非' not in img_name:
                    print(img_name)
    else:
        print("请求出现错误,请换张图片试试")
    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序烂人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值