tesseract-ocr簡介
一款免費的開源圖像OCR文字識別引擎,初期Tesseract引擎由HP實驗室研發,后來貢獻給了開源軟件業,后由Google進行改進、修改bug、優化,重新發布。它就能根據你的命令將你想要識別的圖片中的文字轉換成文本的形式,或者轉換成能被常規文本編輯器編輯的文本如pdf。到目前為止,它已經支持簡體中文、繁體中文、英文、日文、韓文等等60多種語言的識別。並隨着大家對它功能上的要求在不斷改進、不斷消除bug、優化功能。
Pytesseract簡介
Pytesseract是python的光學字符識別(OCR)工具。也就是說,它將識別並讀取嵌入圖像中的文本。 Pytesseract是Google的Tesseract-OCR引擎的包裝器。它作為獨立的調用腳本也很有用,因為它可以讀取Python Imaging Library支持的所有圖像類型,包括jpeg,png,gif,bmp,tiff等,而tesseract-ocr默認只支持tiff和bmp。
安裝
安裝tesseract-ocr
sudo apt-get install tesseract-ocr
安裝語言庫
tesseract-ocr-eng是英文庫,tesseract-ocr-chi-sim是中文庫
sudo apt-get install tesseract-ocr-eng tesseract-ocr-chi-sim
安裝依賴及pytesseract
pytesseract是python調用谷歌tesseract-ocr工具的一個庫,用於識別圖片中的信息
# 安裝Pillow sudo pip3 install Pillow # 安裝pytesseract sudo pip3 install pytesseract
使用
try: from PIL import Image except ImportError: import Image import pytesseract # 如果PATH中沒有tesseract可執行文件,請指定tesseract路徑 pytesseract.pytesseract.tesseract_cmd = r'<full_path_to_your_tesseract_executable>' # Example tesseract_cmd = r'/usr/share/tesseract' # 識別的圖像的字符串 print(pytesseract.image_to_string(Image.open('test.png'))) # 指定語言識別圖像字符串,eng為英語 print(pytesseract.image_to_string(Image.open('test-european.jpg'), lang='fra')) # In order to bypass the image conversions of pytesseract, just use relative or absolute image path # NOTE: In this case you should provide tesseract supported images or tesseract will return error print(pytesseract.image_to_string('test.png')) # Batch processing with a single file containing the list of multiple image file paths print(pytesseract.image_to_string('images.txt')) # Timeout/terminate the tesseract job after a period of time try: print(pytesseract.image_to_string('test.jpg', timeout=2)) # Timeout after 2 seconds print(pytesseract.image_to_string('test.jpg', timeout=0.5)) # Timeout after half a second except RuntimeError as timeout_error: # Tesseract processing is terminated pass # 獲取圖像邊界框 print(pytesseract.image_to_boxes(Image.open('test.png'))) # 獲取包含邊界框,置信度,行和頁碼的詳細數據 print(pytesseract.image_to_data(Image.open('test.png'))) # 獲取方向和腳本檢測 print(pytesseract.image_to_osd(Image.open('test.png'))) # Get a searchable PDF pdf = pytesseract.image_to_pdf_or_hocr('test.png', extension='pdf') with open('test.pdf', 'w+b') as f: f.write(pdf) # pdf type is bytes by default # Get HOCR output hocr = pytesseract.image_to_pdf_or_hocr('test.png', extension='hocr')
示例
提取本地圖片上的文字為一個整體的字符串
def get_image_string(path, filename): '''使用谷歌開源框架ocr技術提取圖片上的信息為字符串 :Param path: <str> 圖片的位置 :Param filename: <str> 圖片的名稱 :Return : <string> 從圖片中提取的字符串 ''' username = getpass.getuser() path_base = '/home/' + str(username) + '/' + str(path) + '/' + str(filename) + '.png' text = pytesseract.image_to_string(Image.open(path_base), lang="chi_sim").replace(" ", "").replace("\n", "") print(text) return text