原文地址:http://blog.csdn.net/lanfan_11/article/details/45558573
原文已經寫的很詳細了,結合自己操作中的一些錯誤和感悟,整理了一下,形成了下面的文章。
-----------------------------------------------------------------------------------------------------------------
測試中需要將圖片上的數字提取出來,和數據庫的數字比較,判斷圖片上的數字是否正確。
網上查了下相關資料,了解到pytesser是谷歌OCR開源項目的一個模塊,在Python中導入這個模塊即可將圖片中的文字轉換成文本。
pytesser調用了tesseract。當在Python中調用pytesser模塊時,pytesser又用tesseract識別圖片中的文字。故安裝的時候不需要安裝tesseract。
具體安裝步驟如下:
首先,安裝Python2.7版本
然后,安裝PIL工具,下載的地址是:http://www.pythonware.com/products/pil/,pytesser的使用需要PIL庫的支持。 選擇安裝python對應的版本。
接着下載pytesser,下載的地址是:http://code.google.com/p/pytesser/downloads/list
由於code.google.com網站關閉了,所以,只能在csdn上下載了。下面是csdn的下載網址:http://download.csdn.net/download/pyliang_2008/5564135
最后,安裝pytesser :
1、解壓pytesser ,將解壓后的文件復制到Python安裝目錄的Lib\site-packages下,直接使用,比如我的安裝目錄是:C:\Python27\Lib\site-packages。
2、把2個目錄添加到環境變量之中。 注:若不添加環境變量,僅僅是執行第3步,執行import pytesser的時候可以導入成功,但是不能使用模塊的任何函數,使用時會報函數錯誤。
C:\Python27\Lib\site-packages
C:\Python27\Lib\site-packages\pytesser-v0.0.1
3、還要在C:\Python27\Lib\site-packages下面添加.pth 文件(pytesser-v0.0.1.pth),這個文件里面,只有 “pytesser-v0.0.1”字符串。
注:若只執行第2步,不執行第3步,則import pytesser時會提示沒有此模塊。
另外: 為了美觀,可以將pytesser-v0.0.1修改為pytesser。但是對應的相關位置都需要進行修改。
完成以上步驟之后,就可以編寫圖片文本識別的Python腳本了。
新建一個test.py的文件,復制下面的代碼:
- from pytesser import *
- im = Image.open('D:\\fonts_test.png')
- print im
- bg = Image.new("RGB",im.size,(255,255,255)) #轉換圖片格式,不轉換提示錯誤
- print bg
- bg.paste(im,im)
- print im
- text = image_to_string(bg)
- print text
- #以下代碼存在問題,未調試通過。
- text = image_file_to_string('fonts_test.png', graceful_errors=True)
- print "Using image_file_to_string():"
- print text
將pytesser路徑下的fonts_test.png 圖片復制到test.py的存放位置,可以執行下試試效果。