问题
百度手写识别解决方案非常简单,看到喜欢的不得了,十分快速的就能实现文字ocr,无论是图片还是手写识别
解决
获得百度文字识别的链接token
搜索百度智能云平台
点文字识别申请一下
将ak与sk换成在百度智能云上申请的文字识别ak和sk秘钥字符串
执行后就可以得到链接百度智能云的链接token字符串
有了这个字符串,将图片传送到百度云接口才能被认证通过,这个是鉴权用的
def get_token():
# client_id 为官网获取的AK, client_secret 为官网获取的SK
host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=【ak】&client_secret=【sk】'
response = requests.get(host)
if response:
token = response.json()["access_token"]
print(token)
return token
然后就是识别就行了
输入一个图片地址,附加鉴权token,得到识别的文字结果
request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/handwriting"
# 二进制方式打开图片文件
# pic_path = r"C:\Users\Administrator.DESKTOP-KMH7HN6\Desktop\az.jpg"
f = open(picFilePath, 'rb')
img = base64.b64encode(f.read())
params = {"image": img}
access_token = get_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:
words = ""
for i in response.json()["words_result"]:
words = words + i["words"] + "\n"
综合起来就得到一个完整的根据图片识别文字的函数
# 根据截图去识别手写笔迹
# 图片上传接口地址
def start_hand(picFilePath):
'''
手写文字识别
'''
def get_token():
# client_id 为官网获取的AK, client_secret 为官网获取的SK
host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=【ak】&client_secret=【sk】'
response = requests.get(host)
if response:
token = response.json()["access_token"]
print(token)
return token
request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/handwriting"
# 二进制方式打开图片文件
# pic_path = r"C:\Users\Administrator.DESKTOP-KMH7HN6\Desktop\az.jpg"
f = open(picFilePath, 'rb')
img = base64.b64encode(f.read())
params = {"image": img}
access_token = get_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:
words = ""
for i in response.json()["words_result"]:
words = words + i["words"] + "\n"
return words