最后编辑于2022-04
本人学python也不久,看到官方只有python2的示例代码,就写了python3的,同时也锻炼自己的模块熟悉程度,写了些程序,分享出来供大家借鉴。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#@data = '2018.4.21'
#@author = 'Shawn Dong'
#----------------------
import requests
import json
import base64
import urllib
from aip import AipImageClassify
def get_access_token():
#这里添上自己的app数据就ok
APP_ID = 'xxx'
API_KEY = 'xxx'
SECRET_KEY = 'xxx'
url = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s' % (API_KEY, SECRET_KEY)
response = requests.post(url)
access_token = response.content.decode('utf-8')
access_token = json.loads(access_token)
access_token = str(access_token['access_token'])
return access_token
def get_file_content(filePath):
with open(filePath,'rb') as fp:
return fp.read()
def get_recognization(access_token):
host = 'https://aip.baidubce.com/rest/2.0/image-classify/v2/dish?access_token=' + access_token
header = {'Content-Type' : 'appliapplication/x-www-form-urlencodedcation/x'}
#这里改成自己的文件路径
image = get_file_content('/home/pi/pythoncode/download.jpg')
image = base64.b64encode(image)
body = {'image' : image, 'top_num' : 1}
body = urllib.parse.urlencode(body)
response = requests.post(host,data=body,headers=header)
response = json.loads(response.text)
name = response['result'][0]['name']
return name
def main():
at = get_access_token()
recognization = get_recognization(at)
print(recognization)
if __name__ == '__main__':
main()
至于其中的模块用法我也是边看书边百度+google,具体用法就不多说了,大家可以轻松的查阅到
请登录后评论
TOP
切换版块
Python3-API 分享的不错 ~ 鼓励多分享