菜品识别 API调用
#get_access_token.py
#获取access_token
1 import requests 2 3 4 5 def GetToken(API_KEY,SECRET_KEY): 6 url = 'https://aip.baidubce.com/oauth/2.0/token?' \ 7 'grant_type=client_credentials&' \ 8 'client_id='+API_KEY+'&' \ 9 'client_secret='+SECRET_KEY 10 response=requests.get(url) 11 print('access_token=',response.json()['access_token']) 12 return response.json()['access_token']
调用API
1 import requests 2 import base64 3 from get_access_token import GetToken 4 import os 5 6 """ 填入参数 """ 7 API_KEY = 'your API_KEY' 8 SECRET_KEY = 'your SECRET_KEY' 9 url = "https://aip.baidubce.com/rest/2.0/image-classify/v2/dish" 10 11 def DishRecg(url,data,access_token,folder): 12 header = { 13 'Content-Type': 'application/x-www-form-urlencoded' 14 } 15 request_url = url + "?access_token=" + access_token 16 response=requests.post(url=request_url,data=data,headers=header).json() 17 result=response['result'][0] 18 print(folder, 19 '\t菜品为:',result['name'], 20 '\t置信度:', result['probability'], 21 '\t卡路里:', result['calorie']) 22 23 24 def image_base64(imagepath): 25 # 二进制方式打开图片文件 26 f = open(imagepath, 'rb') 27 img = base64.b64encode(f.read()) 28 return img 29 30 31 if __name__ == "__main__": 32 data={} 33 access_token = GetToken(API_KEY, SECRET_KEY) 34 dish_path = os.getcwd() 35 dish_path = dish_path + '/dish' 36 folderlist = os.listdir(dish_path) 37 for folder in folderlist: 38 imagepath=dish_path + '/' + folder 39 image=image_base64(imagepath) 40 data['image']=str(image,'utf-8') 41 DishRecg(url,data,access_token,folder)