Java OCR文字识别(Tess4J)

来源:互联网 发布:已经删除备案域名 编辑:程序博客网 时间:2024/06/06 12:39

       OCR (Optical Character Recognition,光学字符识别)是指电子设备(例如扫描仪或数码相机)检查纸上打印的字符,通过检测暗、亮的模式确定其形状,然后用字符识别方法将形状翻译成计算机文字的过程;即,针对印刷体字符,采用光学的方式将纸质文档中的文字转换成为黑白点阵的图像文件,并通过识别软件将图像中的文字转换成文本格式,供文字处理软件进一步编辑加工的技术。如何除错或利用辅助信息提高识别正确率,是OCR最重要的课题,ICR(Intelligent Character Recognition)的名词也因此而产生。衡量一个OCR系统性能好坏的主要指标有:拒识率、误识率、识别速度、用户界面的友好性,产品的稳定性,易用性及可行性等。

       Tess4J是对google tesseract ocr的java库的一种实现

1.maven添加依赖

<!-- https://mvnrepository.com/artifact/net.sourceforge.tess4j/tess4j --><dependency>    <groupId>net.sourceforge.tess4j</groupId>    <artifactId>tess4j</artifactId>    <version>3.2.1</version></dependency>
2.工具类编辑

/** * tesseract for javaocrOptical Character Recognition,光学字符识别) * 工具类 * @author wind */public class Tess4jUtils {    /**     * 从图片中提取文字,默认设置英文字库,使用classpath目录下的训练库     * @param path     * @return     */    public static String readChar(String path){        // JNA Interface Mapping        ITesseract instance = new Tesseract();        // JNA Direct Mapping        // ITesseract instance = new Tesseract1();        File imageFile = new File(path);        //In case you don't have your own tessdata, let it also be extracted for you        //这样就能使用classpath目录下的训练库了        File tessDataFolder = LoadLibs.extractTessResources("tessdata");        //Set the tessdata path        instance.setDatapath(tessDataFolder.getAbsolutePath());        //英文库识别数字比较准确        instance.setLanguage(Const.ENG);        return getOCRText(instance, imageFile);    }    /**     * 从图片中提取文字     * @param path 图片路径     * @param dataPath 训练库路径     * @param language 语言字库     * @return     */    public static String readChar(String path, String dataPath, String language){        File imageFile = new File(path);        ITesseract instance = new Tesseract();        instance.setDatapath(dataPath);        //英文库识别数字比较准确        instance.setLanguage(language);        return getOCRText(instance, imageFile);    }    /**     * 识别图片文件中的文字     * @param instance     * @param imageFile     * @return     */    private static String getOCRText(ITesseract instance, File imageFile){        String result = null;        try {            result = instance.doOCR(imageFile);        } catch (TesseractException e) {            e.printStackTrace();        }        return result;    }    public static void main(String[] args) {        /*String path = "src/main/resources/image/text.png";        System.out.println(readChar(path));*/        String ch = "src/main/resources/image/ch.png";        System.out.println(readChar(ch, "src/main/resources", Const.CHI_SIM));    }}
注释:中文结果不够准确,需要自己训练字库
具体训练字库,以及完整代码请移步https://github.com/followwwind/javautils

原创粉丝点击