文字識別是利用計算機自動識別字符的技術,是模式識別應用的一個重要領域。文字識別一般包括文字信息的採集、信息的分析與處理、信息的分類判別等幾個部分。
文字識別可應用於許多領域,如閱讀、翻譯、文獻資料的檢索、信件和包裹的分揀、稿件的編輯和校對、大量統計報表和卡片的匯總與分析、銀行支票的處理、商品發票的統計匯總、商品編碼的識別、商品倉庫的管理,以及水、電、煤氣、房租、人身保險等費用的徵收業務中的大量信用卡片的自動處理和辦公室打字員工作的局部自動化等。以及文檔檢索,各類證件識別,方便用戶快速錄入信息,提高各行各業的工作效率。
隨著我國信息化建設的全面開展,OCR文字識別技術誕生20餘年來,經歷從實驗室技術到產品的轉變,已經進入行業應用開發的成熟階段。相比發達國家的廣泛應用情況,OCR文字識別技術在國內各行各業的應用還有著廣闊的空間。隨著國家信息化建設進入內容建設階段,為OCR文字識別技術開創了一個全新的行業應用局面。文通,雲脈技術、漢王等中國文字識別的領軍企業將會更加深入到信息化建設的各個領域。
在文字識別中,許多應用軟體可以幫我們忙,那麼強大的python可以實現圖片中的文字識別嗎?
在學習python的圖像識別中,我們了解到關於中文的識別,效果比較好而且開源的應該就是Tesseract-OCR了,python裡面也有一個包去使用Tesseract-OCR,這個包叫pytesseract。但是在學習過程中,我發現利用百度 AI 開發平臺的 OCR 文字識別 API 也可以識別並提取圖片中的文字。
首先,我們需要一個百度帳號,然後打開百度AI開放平臺(https://ai.baidu.com/)並登陸,點擊「控制臺」,進入左邊欄中的「文字識別」,創建一個應用,並記住你的AppID,API Key和Secret Key。
然後,我們在cmd窗口,安裝百度ai接口的庫。
好了,到這裡基本工作已經做完。接下來是文本識別並且提取的核心部分:
def baiduOCR(picfile, outfile): filename = path.basename(picfile) APP_ID = '****' API_KEY = '****' SECRECT_KEY = '****' client = AipOcr(APP_ID, API_KEY, SECRECT_KEY) i = open(picfile, 'rb') img = i.read() print("正在識別圖片:\t" + filename) message = client.basicGeneral(img) print("識別成功!") i.close();以上即為利用百度api文字識別並提取中的識別部分,接下來只需要將提取文字提取出來即可。
想要將識別的文字提取出來,我們需要做以下設置:
with open(outfile, 'a+') as fo: fo.writelines("+" * 60 + '\n') fo.writelines("識別圖片:\t" + filename + "\n" * 2) fo.writelines("文本內容:\n") for text in message.get('words_result'): fo.writelines(text.get('words') + '\n') fo.writelines('\n'*2) print("文本導出成功!") print()
import globfrom os import pathimport osfrom aip import AipOcrfrom PIL import Imagedef convertimg(picfile, outdir): '''調整圖片大小,對於過大的圖片進行壓縮 picfile: 圖片路徑 outdir:圖片輸出路徑 ''' img = Image.open(picfile) width, height = img.size while(width*height > 4000000): width = width // 2 height = height // 2 new_img=img.resize((width, height),Image.BILINEAR) new_img.save(path.join(outdir,os.path.basename(picfile)))def baiduOCR(picfile, outfile): filename = path.basename(picfile) APP_ID = '****' API_KEY = '****' SECRECT_KEY = '****' client = AipOcr(APP_ID, API_KEY, SECRECT_KEY) i = open(picfile, 'rb') img = i.read() print("正在識別圖片:\t" + filename) message = client.basicGeneral(img) print("識別成功!") i.close(); with open(outfile, 'a+') as fo: fo.writelines("+" * 60 + '\n') fo.writelines("識別圖片:\t" + filename + "\n" * 2) fo.writelines("文本內容:\n") for text in message.get('words_result'): fo.writelines(text.get('words') + '\n') fo.writelines('\n'*2) print("文本導出成功!") print()if __name__ == "__main__": outfile = 'export.txt' outdir = 'tmp' if path.exists(outfile): os.remove(outfile) if not path.exists(outdir): os.mkdir(outdir) print("壓縮過大的圖片...") for picfile in glob.glob("picture/*"): convertimg(picfile, outdir) print("圖片識別...") for picfile in glob.glob("tmp/*"): baiduOCR(picfile, outfile) os.remove(picfile) print('圖片文本提取結束!文本輸出結果位於 %s 文件中。' % outfile) os.removedirs(outdir)