Java可使用的OCR工具Tess4J使用举例
1.简介
1.1 简单介绍
Lept4J和Tess4J都是基于Tesseract OCR引擎的Java接口,可以用来识别图像中的文本:
- 前者是Leptonica图像处理库的Java封装,提供了图像的加载、处理、分析等功能。
- 后者是Tesseract OCR引擎的Java封装,提供了图像的OCR识别、PDF文档的生成等功能。
Lept4J和Tess4J的区别在于,Lept4J主要负责图像的预处理,而Tess4J主要负责图像的后处理,特点分别是:
- Lept4J支持多种图像格式,可以进行图像的缩放、旋转、裁剪、二值化、降噪等操作,提高图像的质量和识别率。
- Tess4J支持多种语言的识别,可以生成文本、HTML、PDF等格式的输出,提供了多种识别模式和参数设置,满足不同的需求。
根据具体场景和需求,可以选择使用Lept4J或Tess4J,或者结合使用两者,以达到最佳的效果。
1.2 官方说明
官网:https://tess4j.sourceforge.net/
描述:A Java JNA wrapper for Tesseract OCR API.Tess4J is released and distributed under the Apache License, v2.0 and is also available from Maven Central Repository.
特性:The library provides optical character recognition (OCR) support for:
- TIFF, JPEG, GIF, PNG, and BMP image formats
- Multi-page TIFF images
- PDF document format
2.使用举例
2.1 依赖及语言数据包
<!-- https://mvnrepository.com/artifact/net.sourceforge.tess4j/tess4j -->
<dependency>
<groupId>net.sourceforge.tess4j</groupId>
<artifactId>tess4j</artifactId>
<version>5.9.0</version>
</dependency>
语言数据包下载地址:https://github.com/tesseract-ocr/tessdata
2.2 核心代码
/**
* 识别图片字符信息
*
* @param imagePath 图片路径
*/
private static String recognitionString(String imagePath) {
File imageFile = new File(imagePath);
ITesseract instance = new Tesseract();
// 1.语言数据包路径
instance.setDatapath("tessdata");
// 2.加载语言文件名称
instance.setLanguage("chi_sim");
String result = "";
try {
result = instance.doOCR(imageFile);
} catch (TesseractException e) {
e.printStackTrace();
}
return result;
}
2.3 识别身份证信息
2.3.1 核心代码
/**
* 识别身份证信息
*
* @param imagePath 图片路径
*/
private static