- 下载语言包
https://tesseract-ocr.github.io/tessdoc/Data-Files
chi_sim.traineddata中文语言包 - 使用
2.1 maven
<dependency>
<groupId>net.sourceforge.tess4j</groupId>
<artifactId>tess4j</artifactId>
<version>4.1.1</version>
</dependency>
2.2 使用
public class Main {
/**
* 识别图片中的文字
* @param args
*/
public static void main(String[] args) throws TesseractException {
//读取文件
List<File> pngFiles = getPngFiles("D:\\test");
//识别图片
List<String> textList = scanPNG(pngFiles);
// 打印
textList.forEach(System.out :: println);
}
/**
* 获取文件夹下的所有PNG图片
* @param directoryPath
* @return
*/
public static List<File> getPngFiles(String directoryPath) {
List<File> pngFiles = new ArrayList<>();
File directory = new File(directoryPath);
File[] files = directory.listFiles();
if (files != null) {
for (File file : files) {
if (file.isFile() && file.getName().endsWith(".png")) {
pngFiles.add(file);
}
}
}
return pngFiles;
}
/**
* 将所有图片文件进行文件识别
* @param pngFiles
* @return
* @throws TesseractException
*/
public static List<String> scanPNG(List<File> pngFiles) throws TesseractException {
//创建实例
ITesseract tesseract = new Tesseract();
//设置字体库路径
tesseract.setDatapath("D:\\test");
//设置语言 -->简体中文
tesseract.setLanguage("chi_sim");
List<String> ans = new ArrayList<>();
for (File pngFile : pngFiles) {
String result = tesseract.doOCR(pngFile);
ans.add(result);
}
return ans;
}
}