一:首先搭建springboot 架構
這個就不展示了,大家自己搭建即可
二:引用 tess4j API
<!-- https://mvnrepository.com/artifact/net.sourceforge.tess4j/tess4j -->
<dependency>
<groupId>net.sourceforge.tess4j</groupId>
<artifactId>tess4j</artifactId>
<version>4.3.1</version>
</dependency>
三:直接上代碼
package com.**.util.ocr;
import net.sourceforge.tess4j.Tesseract;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
/**
* @Class Tess4jOCRAPI
* @Author 作者姓名
* @Version 1.0
* @Date 創建時間:2020-06-16 22:31
* @Copyright Copyright by
* @Direction 類說明
*/
public class Tess4jOCRAPI {
public static Logger logger = LoggerFactory.getLogger( Tess4jOCRAPI.class );
/**
* TODO 圖片識別-通過圖片並指定語言,獲取識別結果
* @param srImage 圖片路徑
* @param ZH_CN 是否使用中文訓練字庫,true-是
* @return 識別結果
*/
public static String FindOCR(String srImage, boolean ZH_CN) {
try {
double start=System.currentTimeMillis();
File imageFile = new File(srImage);
if (!imageFile.exists()) {
return "圖片不存在";
}
BufferedImage textImage = ImageIO.read(imageFile);
Tesseract instance = new Tesseract();
//windows 需要配置環境變量有TESSDATA_PREFIX = C:\Program Files\Tesseract-Tess4jOCRAPI\tessdata 注意:配置完成後需要重啓系統
//Linux同理
instance.setDatapath( System.getenv("TESSDATA_PREFIX") ); //設置訓練字庫的位置
if (ZH_CN)
instance.setLanguage("chi_sim");//中文識別
else
instance.setLanguage("eng"); //英文識別
String result = null;
result = instance.doOCR(textImage);
double end = System.currentTimeMillis();
logger.info("本次識別耗時:{} ms " , (end-start) );
return result;
} catch (Exception e) {
e.printStackTrace();
return "發生未知錯誤";
}
}
public static void main(String[] args) throws Exception {
//1.1 只需要安裝完並做好基礎配置即可 - 第一篇即可
String path = "G:\\360MoveData\\Users\\Administrator\\Desktop\\OCR\\樣本\\30621.png" ;
File remoteFile = new File(path);
String result=FindOCR( remoteFile.toString() ,false );
System.out.println(result);
//1.2 只需要安裝完並做好基礎配置即可 - 第一篇+第二篇 即可
path = "G:\\360MoveData\\Users\\Administrator\\Desktop\\OCR\\樣本\\books.jpg" ;
remoteFile = new File(path);
result=FindOCR( remoteFile.toString() ,true );
System.out.println(result);
}
}
四:運行看效果
標準的圖片識別準確度不錯的,但是這個效率很不好看。