百度AI 文字识别OCR的使用过程:
1、首先创建一个百度开发者帐号,如果你有百度的帐号可以直接用此帐号登陆,没有就需要新创建一个百度帐号,网址https://developer.baidu.com/
2、在控制台中创建一个应用,应用的名称为“文字识别”,记录下这个应用的appid, apikey, secretkey这三个数据,后面调用文字的识别应用时要用到。
3、进行这一步前你的电脑中要有python的开发环境,python2.7, python3都可以 ,安装百度的python sdk, 命令中输入pip install baidu-aip即可安装完成
4、利用百度的sdk编写一个ocr文字识别的程序,创建一个程序文件ocr.py,在打开文件写入以下代码
from aip import AipOcr
APP_ID = '换成你的app id'
API_KEY = '换成你的api key'
SECRET_KEY = '换成你的secret key'
client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
#读取图片
def get_file_content(filePath):
with open(filePath, 'rb') as fp:
return fp.read()
image = get_file_content('test1.jpg')
#设置可选参数
options={}
options['language_type'] = 'CHN_ENG'
options['detect_direction'] = 'true'
options['detect_language'] = 'true'
options['probability'] = 'false'
#调用通用文字识别,图片参数为本地图片
#ret = client.basicGeneral(image, options)
#print(ret)
#返回图片中文字的位置信息,大小高度信息
ret = client.general(image, options)
print(ret)
line = ''
top = 0
top_his = 0
word_len = len(ret.get('words_result' , []))
#根据字符的位置按行打印出来识别的文字
for i in range(0, word_len):
top = ret['words_result'][i]['location']['top']
left = ret['words_result'][i]['location']['left']
left = left // 8
if left == 0:
left = 1
if (top_his != 0) and ((top - top_his) > 3):
#发生了换行
print(line)
line = ''
space = ''
for j in range(0, left):
space = space + ' '
line = line + space + ret['words_result'][i].get('words', 'ERROR')
else:
left = left - len(line)
space = ''
for j in range(0, left):
space = space + ' '
line = line + space + ret['words_result'][i].get('words', 'ERROR')
top_his = top
#打印最后一行文字
print(line)
#end of file
5、程序编写完成,在程序文件的同一目录下面放入一个购买小票的图片文件test1.jpg,按F5运行,识别一个test1.jpg的小票中的文字信息
从识别结果可以看出,小票中的文字大部分都初识别出来。这个脚本程序中根据获取到的文字的位置信息进行了排版打印,目前只是简单的实现排版,对于其他样式的文字图片还需要做调整优化。