Tess4J 基础演示

一个 Java OCR 引擎的使用

简介

Tesseract 是一个开源 OCR 引擎,能将图像中的文本转换为可编辑的文本数据。
Tess4J 是基于 Java 的 Tesseract 的封装库,使 Java 开发者能够方便地利用 Tesseract 进行文本识别。

环境配置

Linux

不需要环境配置,大多数 Linux 发行版中都包含 Tesseract。

Windows

下载训练数据

项目构建

  • pom.xml 文件中引入 tess4j 以及日志依赖
  • log4j.properties 作为 log4j 的配置文件
  • 将训练数据文件复制到 src/main/resources/tess4j 文件夹中
  • src/main/resources 中放入需要进行 OCR 操作的图片
  • 新建 Tess4JDemo 类,编写关键代码
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.alioth4j;

import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;

import java.io.File;

/**
 * Tess4j演示
 * @author Alioth4J
 */
public class Tess4JDemo {

    public static void main(String[] args) {
        // 创建 File 对象表示要识别的图像文件
        File imgFile = new File("src/main/resources/example.png");
        // 创建 Tesseract 对象
        Tesseract tess = new Tesseract();
        // 设置训练数据所在位置
        tess.setDatapath("src/main/resources/tess4j");
        // 设置语言:英文 -> eng; 简体中文 -> chi_sim
        tess.setLanguage("chi_sim");
        // 字符串对象用于接收结果
        String imgText = null;
        // 执行 OCR
        try {
            imgText = tess.doOCR(imgFile);
        } catch (TesseractException e) {
            e.printStackTrace();
        }
        // 输出结果
        System.out.println("OCR 结果:");
        System.out.println(imgText);
    }

}

运行项目

  • 运行 Tess4JDemo#main 方法即可
Licensed under CC BY-NC-SA 4.0
Who comes from mountains, rivers, lakes and seas, yet is confined to days, nights, kitchen and love?