python调用百度API实现图片识别标题
1. 获取access_token
-
其必须携带三个参数:
- 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. 实现图片识别
-
请求头headers:{Content-Type": “application/json;charset=utf-8”}
-
注意:请求的参数必须为json格式,不然会报参数错误282004,即下面代码中的params
-
图片分为网络图片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("请求出现错误,请换张图片试试")