什么都不必说–简单图片金额识别OCR

什么都不必说–简单图片金额识别OCR

大家好,又见面了,我是你们的朋友全栈君。

需求 获取图片中金额
复制代码

1.添加maven

  <!--图片识别-->
        <dependency>
            <groupId>net.sourceforge.tess4j</groupId>
            <artifactId>tess4j</artifactId>
            <version>2.0.1</version>
            <exclusions>
                <exclusion>
                    <groupId>com.sun.jna</groupId>
                    <artifactId>jna</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
复制代码

2.安装tessdata

brew install tesseract 
复制代码

3.工具类

public class OCRUtil {
    private static String  tessdataPath;
    private static String STRING_TESS_VARIABLE_KEY = "tessedit_char_whitelist";
    private static String STRING_TESS_VARIABLE_VALUE = "0123456789.¥";
    private static String STRING_TESS_NAME = "tessdata";

    private ITesseract instance;

    private static OCRUtil ocrUtil;

    private OCRUtil(ITesseract instance){
        this.instance = instance;
    }

    private static final LogUtil logUtil  = LogUtil.init(OCRUtil.class);

    //必须加锁,在高并发情况下会出现jvm崩坏情况
    public  synchronized String getAmount(BufferedImage bi) throws IOException {
        long start = System.currentTimeMillis();
        try {

            String ocrResult = instance.doOCR(bi);
            if(StringUtil.isEmpty(ocrResult)){
                return null;
            }
            if(ocrResult.indexOf("¥") == -1){
                return null;
            }
            logUtil.i("金额识别 为:%s\n金额识别耗时:%s毫秒",ocrResult,System.currentTimeMillis()-start);
            return ocrResult.replace("\n","").substring(ocrResult.indexOf("¥") + 1).trim();
        } catch (TesseractException e) {
            System.err.println(e.getMessage());
        }
        return null;
    }

    public static synchronized OCRUtil init(){

        if(null == ocrUtil){
            ITesseract instance = new Tesseract(); // JNA Direct Mapping
            instance.setTessVariable(STRING_TESS_VARIABLE_KEY, STRING_TESS_VARIABLE_VALUE);
//            File tessDataFolder = LoadLibs.extractTessResources(STRING_TESS_NAME);
//            logUtil.d(tessDataFolder.getAbsolutePath());
            //从外部获取tessdataPath或者查询tessdata所在位置
            instance.setDatapath(tessdataPath);
            ocrUtil = new OCRUtil(instance);
        }

        return ocrUtil;

    }

}

复制代码

转载于:https://juejin.im/post/5b39d1bb6fb9a00e43467df9

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/107444.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号