python调用baidu_aip包中的AipOCR实现图像文字
2022-08-19 本文已影响0人
守望一株麦穗
软件环境:window10 x64 ; python3.9.2
(不同版本的python,语法可能会有不同。之前吃够了苦头。教程不注明环境,会浪费很多时间测试。)
pip安装baidu_aip包
pip install baidu_aip

下面的程序,可以调用baidu_aip包中的AipOCR
这里成功的关键点是申请百度云的服务,获取授权
当授权不成功时,会client.general(image)会返回类似下面的错误信息
{ “error_msg”: “IAM Certification failed”, “error_code”: 14 }
注意1:py程序文件与图像文件要放在同一目录里面。
这是因为 cf=os.path.realpath(sys.argv[0]) 获取的是当前程序py文件所在绝对路径。“D:\python_wd\图像识别.py”
os.path.split(cf)[0] #这里是获取的是当前程序文件所在的目录 "D:\python_wd"
注意2:当fname="test.jpg" 时,
os.path.splitext(fname)[0]的返回值是"test"
os.path.splitext(fname)[-1]的返回值是".jpg"
import os;
import sys;
from aip import AipOcr;
from docx import Document
from docx.shared import Pt
##这里的APP_ID, APP_KEY,SECRET_KEY是通过百度云获得的
##因为此程序引用了 baidu_aip包里面的AipOCR,这些包不是免费的
##好在百度智能云提供了试用包,如何申请请参考网页:
APP_ID='270xxxx'
APP_KEY='5wkObexxxxxxx'
SECRET_KEY='hquxxxxxxxx'
client=AipOcr(APP_ID,APP_KEY,SECRET_KEY)
def get_file_content(filePath):
with open(filePath,'rb') as fp:
return fp.read()
#获取的是当前程序文件的绝对路径。
#cf=os.path.realpath(sys.argv[0])
#os.path.split(cf)[0] #获取的是当前程序文件所在的目录
cf=os.path.realpath(sys.argv[0])
localdir=os.path.split(cf)[0]
all_file_names=os.listdir(localdir)
for fname in all_file_names:
#print(fname,os.path.splitext(fname)[0],os.path.splitext(fname)[-1])
if os.path.splitext(fname)[-1] in ['.jpg','png','tiff','jpeg']:
fig_path=localdir+"\\"+fname
fig_path2=localdir+"\\"+os.path.splitext(fname)[0]+'.docx'
print (fig_path)
#print(fig_path2)
image = get_file_content(fig_path)# 获取图片
msg=client.general(image) #调用API解析图片后生成一段信息储存在变量中
##这里是将图像识别后的内容存入word里面
##docx.add_paragraph()
docx = Document()
docx.add_paragraph(fname)
for i in msg.get('words_result'):
print(i.get('words'))
docx.add_paragraph(i.get('words'))
docx.add_paragraph("=====~~~~~end========")
docx.save(fig_path2)
如何从百度智能云中获取自己的app_id, app_key, secret_key
第一步:登录/注册百度智能云:https://cloud.baidu.com/

第二步:找到文字识别模块

第三步:领取尝鲜试用包,能领的都领上。


第四步:创建应用



这里就是要获取的AppID, API Key ,Secret Key