OCR小項目:調用百度api文字識別,並將結果存入txt文件
百度API: http://ai.baidu.com/tech/ocr
百度提供了文字識別的api可以利用它來做文字識別啦,要不要嘗試一下,很簡單哦
注意:免費使用次數有限哦
代碼:
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_new\result.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')