好友
阅读权限10
听众
最后登录1970-1-1
|
首先需要ai.baidu.com的账号,然后在右上角点击控制台,在控制台里面选择“文字识别”,然后创建应用,就能得到应用的API Key 和Secret Key,在python程序里面需要用到
# encoding:utf-8
import requests
import base64
import json
from PIL import Image
#图片的路径
filePath='E:\工程\838-2017 2.png'
img = Image.open(filePath)
dir(img)
img.show() #显示图片,为了扔对比,也可以不要
#百度ai里面文字识别应用的APIKey和SecretKey
API_Key='你的apikey'
Secret_Key='你的SecretKey'
#获取Access Token
# client_id 为官网获取的AK, client_secret 为官网获取的SK
host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id='+API_Key+'&client_secret='+Secret_Key
response = requests.get(host)
if response:
#print(response.json())
jsonret=response.json()
access_token=json.loads(response.text).get("access_token")
print(access_token)
'''
文字识别
'''
request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic"
# 二进制方式打开图片文件
f = open(filePath, '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())
result=response.json()
try:
with open(filePath.split('.')[0]+'.txt','w',encoding='utf-8') as f:
for i in result['words_result']:
f.write(i['words']+'\n')
s=i['words'
print(s)
print('finish')
except BaseException as e :
print(e)
else:
print('处理完成')
else:
print('no response')
|
|
发帖前要善用【论坛搜索】功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。 |
|
|
|
|