记一次百度 OCR 的使用

tsvico Lv5

恰巧用到了 OCR 批量识别,鉴于准确度没有使用在本地训练的 TensorFlow-OCR,而是选择了百度 OCR,可选的方式多种多样,比如 Google 文字识别,腾讯 OCR 等等,不一一列举

很简单的 demo,参照开发文档

http://ai.baidu.com/docs#/OCR-Python-SDK/80d64770

image

先去控制台注册一个开发者账号,并创建一个文字识别应用,在管理应用中可以看到 AppID 等相关信息

安装 SDK pip install baidu-aip

新建一个 python 文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
from aip import AipOcr
from glob import glob
from docx import Document
import os
import json
""" 你的 APPID AK SK """
APP_ID = '你的 App ID'
API_KEY = '你的 Api Key'
SECRET_KEY = '你的 Secret Key'
client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
root_path = os.getcwd() #获取当前路径
document = Document() #初始化word文档
num = 0
""" 读取图片 """
def get_file_content(FilePath):
with open(FilePath, 'rb') as fp:
return fp.read()

""" 调用通用文字识别, 图片参数为本地图片 """
def result(image_file,image):
""" 如果有可选参数 """
options = {}
#options["language_type"] = "CHN_ENG"#
options["detect_direction"] = "true"
#options["detect_language"] = "true"#
options["probability"] = "true"
#m = client.basicGeneral(image);
"""带参数调用通用文字识别, 图片参数为本地图片 """
#client.basicGeneral(image,options)
#url = "https//www.x.com/sample.jpg"
#调用通用文字识别, 图片参数为远程url图片
#client.basicGeneralUrl(url);
#普通
#res = client.basicGeneral(image,options)
#高精度
res = client.basicAccurate(image,options)
global num
num = num + 1
print("这是第"+str(num)+"个文件")
print(res)
if 'error_code' in res:
print("有错误")
File("出错了,第"+image_file.split("/")[-1]+'个','/error')
else:
if(num>0):
document.add_page_break()
fname = image_file.split("/")[-1]
document.add_heading(fname,level=2) #添加二级标题
os.remove(image_file)
for item in res['words_result']:
print(item['words'])
File(item['words'],image_file)
write_word(item['words'])

'''文件写入'''
def File(string,name):
with open(root_path+'/demo/text/'+name.split("/")[-1]+'.txt','a+') as f:
f.write('\n'+string)

def write_word(string):
document.add_paragraph(string)
document.save(root_path+'/demo/text/'+'test.docx')
"""指定目录下所有文件路径"""
image_files = glob(root_path+'/demo/image/*.*')
#image_files = glob('./image/*.*')
for image_file in sorted(image_files):
print(image_file)
image = get_file_content(image_file)
result(image_file,image)

支持导出到 word 文档,可以在第 51,52 行中添加 / 修改将结果写入的文件,7,8,9 改成自己控制台的内容才可以使用,相应目录都写在文件中,只需稍微修改

自动读取 image 文件夹下的所有文件,识别后将结果保存在 text 目录下

目录树

1
2
3
4
5
6
.
├── BaiduOcr.py
├── error.txt
├── image
│   └── 028.jpg
└── text
  • 标题: 记一次百度 OCR 的使用
  • 作者: tsvico
  • 创建于 : 2018-11-12 11:04:27
  • 更新于 : 2021-03-06 20:21:07
  • 链接: https://blog.tbox.fun/2018/8d4a5af0.html
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
评论
目录
记一次百度 OCR 的使用