Tesseract-OCR引擎
大约 2 分钟
Tesseract-OCR引擎
简介
Tesseract是一个开源的光学字符识别(OCR)引擎,它可以将图像中的文字转换为计算机可读的文本。支持多种语言和书面语言,并且可以在命令行中执行。它是一个流行的开源OCR工具,可以在许多不同的操作系统上运行。
Tess4J是一个基于Tesseract OCR引擎的Java接口,可以用来识别图像中的文本,说白了,就是封装了它的API,让Java可以直接调用。
.traineddata后缀的文件都是训练好的文件- 下面以chi_sim.traineddata为例
Tess4J
依赖
<!-- tess4j -->
<dependency>
<groupId>net.sourceforge.tess4j</groupId>
<artifactId>tess4j</artifactId>
<version>4.5.4</version>
</dependency>
配置
- 训练数据文件夹的路径放在classpath路径下
server:
port: 8888
# 训练数据文件夹的路径
tess4j:
datapath: D:/tessdata
@Configuration
public class TesseractOcrConfiguration {
@Value("${tess4j.datapath}")
private String dataPath;
@Bean
public Tesseract tesseract() {
Tesseract tesseract = new Tesseract();
// 设置训练数据文件夹路径
tesseract.setDatapath(dataPath);
// 设置为中文简体
tesseract.setLanguage("chi_sim");
return tesseract;
}
}
使用
service
public interface OCRService {
String recognizeText(MultipartFile imageFile) throws TesseractException, IOException;
}
@Service
public class OCRServiceImpl implements OCRService {
@Autowired
private Tesseract tesseract;
/**
* 识别图片中的文字
* @param imageFile 图片文件
* @return 文字信息
*/
@Override
public String recognizeText(MultipartFile imageFile) throws TesseractException, IOException {
// 转换
InputStream sbs = new ByteArrayInputStream(imageFile.getBytes());
BufferedImage bufferedImage = ImageIO.read(sbs);
// 对图片进行文字识别
return tesseract.doOCR(bufferedImage);
}
}
controller
@RestController
@RequestMapping("/api")
public class OCRController {
@Autowired
private OCRService ocrService;
@RequestMapping("/ocr")
public String ocr(MultipartFile file) {
try {
return ocrService.recognizeText(file);
} catch (Exception e) {
return null;
}
}
public static void main(String[] args) {
Tesseract tesseract = new Tesseract();
// 设置训练数据文件夹路径
tesseract.setDatapath("C:\\Users\\Administrator\\IdeaProjects\\spring-boot-test\\JAVA-OCR\\src\\main\\resources\\tessdata");
// 设置为中文简体
tesseract.setLanguage("chi_sim");
try {
String result = tesseract.doOCR(new File("D:\\Desktop\\222.png"));
System.out.println(result);
} catch (TesseractException e) {
e.printStackTrace();
}
}
}
