天天看點

Python 技術篇-3行代碼搞定圖像文字識别,pytesseract庫實作

我們需要 pillow 和 pytesseract 這兩個庫,pip install 安裝就好。

還需要安裝 Tesseract-OCR.exe 然後配置下就好了。

具體的環境配置方法請看

python 技術篇-使用pytesseract庫進行圖像識别之環境配置

英文字母圖像識别示範

這個是我儲存名為 English.png 的圖檔,下面我來提取文字。

Python 技術篇-3行代碼搞定圖像文字識别,pytesseract庫實作
pytesseract 庫的 image_to_string() 方法就能把圖檔中的英文字母提取出來。

from PIL import Image
import pytesseract
 
image = Image.open('English.png')
content = pytesseract.image_to_string(image)   # 解析圖檔
print(content)      

運作效果圖:

注:有些字型可能會識别出現問題,盡量用比較标準的字型。

Python 技術篇-3行代碼搞定圖像文字識别,pytesseract庫實作

中文漢字圖像識别示範

這個是我儲存名為 chinese.png 的圖檔,下面我來提取文字。

Python 技術篇-3行代碼搞定圖像文字識别,pytesseract庫實作

首先需要安裝對應的語言包:

Tesseract各個版本語言包擷取方式和安裝方法

要在 pytesseract 庫的 image_to_string() 方法裡加個參數

lang='chi_sim'

,這個就是引用對應的中文語言包,中文語言包的全名是 chi_sim.traineddata。

from PIL import Image
import pytesseract
 
image = Image.open('English.png')
content = pytesseract.image_to_string(image, lang='chi_sim')   # 解析圖檔
print(content)      
Python 技術篇-3行代碼搞定圖像文字識别,pytesseract庫實作

有什麼問題可以評論區留言!

喜歡的點個贊❤吧!