AI接入
参考官方文档:AI接入指南
参考:网络图片文字识别申请
参考:鉴权认证机制,用于获取access token
网络文字识别示例代码
下面是官方给的示例代码,从代码中我们可以看出,只要获取到access_token就可以进行API调用,进行本地图片的识别了。
# encoding:utf-8
import requests
import base64
request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/webimage"
# 二进制方式打开图片文件
f = open('[本地文件]', 'rb')
img = base64.b64encode(f.read())
params = {"image":img}
access_token = '[调用鉴权接口获取的token]'
request_url = request_url + "?access_token=" + access_token
headers = {'content-type': 'application/x-www-form-urlencoded'}
response = requests.post(request_url, data=params, headers=headers)
if response:
print (response.json())
调用API
- 准备测试图片
- 完整代码
# coding=utf-8
import requests
import base64
class ImageDistinguish:
def __init__(self):
# 获取access_token的url,client_id是应用的API Key,client_secret是应用的Secret Key
self.url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=XXXXXXXXXX&client_secret=XXXXXXXXXX"
def get_ak(self):
res = requests.get(self.url)
return res.json().get('access_token')
def distinguish(self):
request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/webimage"
# 二进制方式打开图片文件
with open('test.jpg', 'rb') as f:
img = base64.b64encode(f.read())
params = {"image": img}
access_token = self.get_ak()
request_url = request_url + "?access_token=" + access_token
headers = {'content-type': 'application/x-www-form-urlencoded'}
try:
response = requests.post(request_url, data=params, headers=headers)
# 返回识别结果,并提取对应识别的内容
return response.json().get("words_result")[0].get('words')
except Exception as e:
print(e)
if __name__ == '__main__':
img = ImageDistinguish()
result = img.distinguish()
print(result)
- 结果
C:\Python36\python.exe C:/Users/Administrator/PycharmProjects/T/webIMAGE.py
致富十年功