Java 驗證碼識別庫 Tess4j 學習
【在用java的Jsoup做爬蟲爬取數據時遇到了驗證碼識別的問題(基於maven),找了網上挺多的資料,發現Tess4j可以自動識別驗證碼,在這里簡單記錄下學習過程及遇到的一些問題。】
步驟:
- 把tessreact項目里面的tessdata文件夾提取出來放在某個位置:https://github.com/tesseract-ocr/tesseract
- 需要在步驟一的tessdata文件中加入相關語言包(訓練文件),在這里下載:https://github.com/tesseract-ocr/tessdata ,如果是簡單的英文數字驗證碼,下載 eng.traineddata然后放到文件夾里即可,中文的是chi開頭的traineddata。
- 導入相關依賴,maven相關依賴如下:
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>net.java.dev.jna</groupId> <artifactId>jna</artifactId> <version>4.2.1</version> </dependency> <dependency> <groupId>net.sourceforge.tess4j</groupId> <artifactId>tess4j</artifactId> <version>4.1.1</version> <exclusions> <exclusion> <groupId>com.sun.jna</groupId> <artifactId>jna</artifactId> </exclusion> </exclusions> </dependency> </dependencies>
4,編寫相關代碼(自測可正常運行):
package yanZhengMaTest.pikachu; import java.io.File; import net.sourceforge.tess4j.Tesseract; import net.sourceforge.tess4j.TesseractException; public class Test { public static void main(String[] args) { //驗證碼圖片存儲地址 File imageFile = new File("C:\\Users\\pc\\Desktop\\1.gif"); if(!imageFile.exists()){ System.out.println("圖片不存在");; } Tesseract tessreact = new Tesseract(); tessreact.setDatapath("F:\\Program Files (x86)\\Tesseract-OCR\\tessdata"); String result; try { result = "測驗結果:" + tessreact.doOCR(imageFile); System.out.println(result); } catch (TesseractException e) { e.printStackTrace(); } } }
出現異常及處理:
(本人因為開始的時候沒用maven導入依賴,自己去下載了各種網上要的jar包去導入,遇到了一堆問題,最后卡在了Invalid memory access這個異常上,后來通過換成maven項目並解決了異常)
A.【Exception in thread "main" java.lang.Error: Invalid memory access:】
如果出現類似於 Invalid memory access的異常
(1). 首先你先確定JAVA代碼中:
tessreact.setDatapath("F:\\Program Files (x86)\\Tesseract-OCR\\tessdata");
這里的地址要填你步驟一下載的tessdata文件夾地址。
(2). 如果地址無誤,那可能是你tess4j依賴的版本太低,需重新導入依賴,在pom中修改即可。
B.【Exception in thread “main” java.lang.UnsupportedClassVersionError: net/sourceforge/tess4j/Tesseract:】
發生該異常的原因是JDK版本低於1.7,使用1.7以上即可解決問題。
C.【出現圖片非法異常】:可能是你圖片有問題,換張圖片試試,下載的圖片不要去修改它的后綴,否則也可能報錯。
痛的領悟:
不要直接用java項目自己去導入相關jar包,直接用maven項目去加入依賴包就好,否則可能會出現一堆莫名其妙的異常,個人覺得是因為maven項目依賴包導入時還會導入其他jar包,java項目則需要自己去補增一些jar包,在此建議用maven。
附:
tess4j相關視頻:http://tphangout.com/how-to-use-the-tesseract-api-to-perform-ocr-in-your-java-code/
Tesseract-orc-setup下載地址(非必要):https://digi.bib.uni-mannheim.de/tesseract/
Tesseract-orc-setup安裝過程(非必要):https://jingyan.baidu.com/article/219f4bf788addfde442d38fe.html
Tesseract-orc環境配置(非必要):https://www.cnblogs.com/jianqingwang/p/6978724.html
可識別驗證碼示例:http://es.bnuz.edu.cn/checkcode.aspx?0.33556625493951997/
