1.通过图片
import base64
import urllib3, base64
import json
from urllib.parse import urlencode
access_token = 'your'
http = urllib3.PoolManager()
url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=' + access_token
f = open('image.png', 'rb')
# 参数image:图像base64编码
img = base64.b64encode(f.read())
params = {'image': img}
# 对base64数据进行urlencode处理
params = urlencode(params)
request = http.request('POST',
url,
body=params,
headers={'Content-Type': 'application/x-www-form-urlencoded'})
# 对返回的byte字节进行处理。Python3输出位串,而不是可读的字符串,需要进行转换
result = str(request.data, 'utf-8')
# 返回参数json序列化处理
res = json.loads(result)
res = res['words_result'][0]['words']
print(res)
2.通过url
import base64
import urllib3,base64
import json
from urllib.parse import urlencode
access_token='your'
http=urllib3.PoolManager()
url='https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token='+access_token
img_url = 'https://raw.githubusercontent.com/Python3WebSpider/TestTess/master/image.png'
params={'url':img_url}
#对base64数据进行urlencode处理
params=urlencode(params)
request=http.request('POST',
url,
body=params,
headers={'Content-Type':'application/x-www-form-urlencoded'})
#对返回的byte字节进行处理。Python3输出位串,而不是可读的字符串,需要进行转换
result = str(request.data,'utf-8')
#返回参数json序列化处理
res = json.loads(result)
print(res)