OCR小项目:调用百度api文字识别,并将结果存入txt文件
百度API: http://ai.baidu.com/tech/ocr
百度提供了文字识别的api可以利用它来做文字识别啦,要不要尝试一下,很简单哦
注意:免费使用次数有限哦
代码:
代码语言:javascript复制import os
import os.path
import sys
from aip import AipOcr
APP_ID = '10498120'
API_KEY = 'hwwISLbyb1en11SsjDyEu7tW'
SECRET_KEY = 'waOoWyci9GDlRw1CkWNtmfkHRNokwhca'
client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
# 读取图片,返回路径的集合
def file_name(file_dir):
pathSet = []
FN = []
for root, dirs, files in os.walk(file_dir):
for file in files:
FN.append(file)
pathSet.append(os.path.join(root, file))
return pathSet
# 打开文件 读取文件内容
def get_file_content(filePath):
with open(filePath, 'rb') as fp:
return fp.read()
# 返回文件的类型符号,如:最后.jpg
def file_extension(path):
return os.path.splitext(path)[1]
file_dir = 'E:images_new'
pathSet = file_name(file_dir)
result = []
for filePath in pathSet:
# 调用通用文字识别接口
if (file_extension(filePath) == '.jpg'):
result = client.basicGeneral(get_file_content(filePath))
# {'log_id': 6775584000925260612, 'words_result_num': 1, 'words_result': [{'words': '20'}]}
if 'words_result' in result:
rest = result['words_result'][0]['words']
else:
break
f = open('E:images_newresult.txt', 'a', encoding='utf-8')
f.write('
' '/images_new/' os.path.basename(filePath) ' ' rest)
f.close()
# 如果图片是url 调用示例如下
#result = client.basicGeneral('http://www.xxxxxx.com/img.jpg')