![5164d7e2e40c557b28a8c0672ac7b6bb.png](https://i-blog.csdnimg.cn/blog_migrate/a7cad501c4a92a4a07a56c834a3f2912.jpeg)
tesseract想必大家都知道(不知道自个查去),tess4j是java对tesseract的封装。
Description: A Java JNA wrapper for Tesseract OCR API. Tess4J is released and distributed under the Apache License, v2.0. ## Features: The library provides optical character recognition (OCR) support for: TIFF, JPEG, GIF, PNG, and BMP image formats Multi-page TIFF images PDF document format
python调用tesseract的案例有很多,网上一搜一大堆,在此也不细说了。
最近有个小需求,需要使用java来提取图片里的文字,首先想到的就是用tess4j,其实tess4j的使用也比较简单,在pom里引入
<dependency>
<groupId>net.sourceforge.tess4j</groupId>
<artifactId>tess4j</artifactId>
<version>4.3.1</version>
</dependency>
测试方法:
@Test
public void test1() {
String path = ""; //我的项目存放路径
File file = new File("WechatIMG1436.png");
ITesseract instance = new Tesseract();
File directory = new File(path);
String courseFile = null;
try {
courseFile = directory.getCanonicalPath();
} catch (IOException e) {
e.printStackTrace();
}
//设置训练库的位置
instance.setDatapath("/tessdata");
instance.setLanguage("chi_sim");//chi_sim :简体中文, eng 根据需求选择语言库
String result = null;
try {
long startTime = System.currentTimeMillis();
result = instance.doOCR(file);
long endTime = System.currentTimeMillis();
System.out.println("Time is:" + (endTime - startTime) + " 毫秒");
} catch (TesseractException e) {
e.printStackTrace();
}
System.out.println("result: ");
System.out.println(result);
}
比较奇特的是上面一段代码在windows里是完全没问题的,在mac下就完全执行不了
![41732835acf2b8b516d230427dcaa349.png](https://i-blog.csdnimg.cn/blog_migrate/ecf71902f383cfb3300756f944bbc173.jpeg)
google了半天,大多在重复瞎扯,什么一会java不支持tesseract都能扯出来,后面在Stack Overflow上看到有人在python下调用tesseract也会报这个错,然后他们的解决方式是在代码里加上
import locale
locale.setlocale(locale.LC_ALL, 'C')
其实就是增加一个环境变量,那么我在java里执行前也加上这个环境变量不就行了。。so,在idea里加了个参数,果然好了。。
![dbf0ee489bc153a38f867e91d26662d5.png](https://i-blog.csdnimg.cn/blog_migrate/4e3951de567edd8679d9e751d710f943.jpeg)
下面是一张图片的测试结果;
![fd5cea3e4265a34b788b0442bbc4e343.png](https://i-blog.csdnimg.cn/blog_migrate/c8cbe4eef909989aeff1b5e41f06ab9f.jpeg)
![0c6c6118f8acfe5743fdfecff9927644.png](https://i-blog.csdnimg.cn/blog_migrate/e8650475a389cb2fcb4bdd2ab472582e.jpeg)
下面是我在python下测试的输出:
![d1ededb3e52d14de0b543c6dd418311c.png](https://i-blog.csdnimg.cn/blog_migrate/0fb58cc480aa58e40f87cc7d8754a107.jpeg)
可以看到识别结果是有区别的,不过这个区别应该是模型文件的不同导致,在java里面指定了一个单独下载的模型文件。