python基于百度AI开发文字识别

很多场景都会用到文字识别,比如app或者网站里都会上传身份证等证件以及财务系统识别报销证件等等

第一步,你需要去百度AI里去注册一个账号,然后新建一个文字识别的应用 然后你将得到一个API Key 和Secret Key,如下图

百度AI地址 https://ai.baidu.com/tech/imagerecognition

百度AI文档 https://cloud.baidu.com/doc/OCR/s/zk3h7xz52

接下来,你需要安装百度ai的包

pip install baidu-aip

下载成功之后直接上代码,哈哈

# 基于百度AI开发的文字识别
# encoding:utf-8
import requests
import json
import base64

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:
    request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic"
    f = open('./word.png', 'rb')
    img = base64.b64encode(f.read())
    params = {"image": img}
    access_token = json.loads(response.text).get("access_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())

注意,open图片的地址我是直接放在和此py文件同一级目录下,结果如下

 识别结果为

 识别结果还是很准的,比pytesser3等识别的结果还是有保证些

猜你喜欢

转载自www.cnblogs.com/ldlx-mars/p/12373665.html