关于OCR&百度云OCR
OCR全称为Optical Character Recognition,指电子设备(例如扫描仪或数码相机)检查纸上打印的字符,通过检测暗、亮的模式确定其形状,然后用字符识别方法将形状翻译成计算机文字的过程;即,针对印刷体字符,采用光学的方式将纸质文档中的文字转换成为黑白点阵的图像文件,并通过识别软件将图像中的文字转换成文本格式,供文字处理软件进一步编辑加工的技术。
在这里百度云OCR是识别并返回图片中的文字。百度云中的文字识别有专门针对如身份证,驾驶证,银行卡等API供调用,本项目的图片均为商品包装图片,故选择通用文字识别和通用文字识别(高精度版)两个进行比较使用。
步骤
1.登录百度云,创建管理应用,获取AppID,API Key,Secret Key。
2.下载需要的包,pip install baidu-aip
3.准备代码如下,
from aip import AipOcr #pip install baidu-aip
import time
t1=time.time()
# 定义常量
APP_ID = '你的AppID'
API_KEY = '你的API Key'
SECRET_KEY = '你的Secret Key'
# 初始化AipFace对象
aipOcr = AipOcr(APP_ID, API_KEY, SECRET_KEY)
# 读取图片
filePath = "1111.png"
def get_file_content(filePath):
with open(filePath, 'rb') as fp:
return fp.read()
# 定义参数变量
options = {
'detect_direction': 'true',
'language_type': 'CHN_ENG',
'probability':'true',
}
# 调用通用文字识别接口 5w次每天
#result = aipOcr.basicGeneral(get_file_content(filePath), options)
# print(result)
# 调用高精度版 500次每天
result=aipOcr.basicAccurate(get_file_content(filePath), options)
# 整理返回的结果
a=''
for i in result['words_result']:
a=a+i['words']+','
print(a)
# 将结果写入文件
with open('输出.txt','w',encoding='utf-8') as f: #设置文件对象
f.write(a)
t2=time.time()
print("调用耗时:",t2-t1)