Java OCR tesseract 图片识别技术(二)

一、前面已经测试过了tesseract的dos方式调用,接下来使用java代码方式调用tesseract工具识别验证码。

package com.cyn.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class OCRUtil {

    //OCR的都是命令方式调用
    public static String getImgText(String imgPath) {  
        String result = "";  
        BufferedReader br = null;
        //中文识别   -l chi_sim -psm 7 nobatch
        String ocrLangData="outputbase nobatch digits";//识别语言
        String outPath = imgPath.substring(0, imgPath.lastIndexOf("."));
        File file = new File(outPath + ".txt");
        try {
            //dos执行
            Runtime runtime = Runtime.getRuntime();  
            String command = "tesseract " + imgPath + " " + outPath +" "+ ocrLangData;  
            Process ps = runtime.exec(command);  
            ps.waitFor();  
            // 读取文件  
            br = new BufferedReader(new FileReader(file));  
            String temp = "";  
            StringBuffer sb = new StringBuffer();  
            while ((temp = br.readLine()) != null) {  
                sb.append(temp);  
            }
            // 文字识别结果  
            result = sb.toString();
        } catch (Exception e) {  
            System.out.println("识别图片异常!");
            e.printStackTrace();  
        }finally{
            try {
                br.close();
                //读取完后删除文件
                file.delete();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;  
    } 

    //测试
    public static void main(String[] args) {
        getImgTxtList("E:\\TestCode");
    }

    //处理一个文件夹中的所有验证码
    public static void getImgTxtList(String filepath){
        File file = new File(filepath);
        File [] fileList = file.listFiles();
        for(File f:fileList){
            String imgpath=f.getAbsolutePath();
            if(imgpath.endsWith("jpg")||imgpath.endsWith("png")||imgpath.endsWith("bmp")){
                String resultTxt = getImgText(imgpath);
                System.out.println("result: "+resultTxt);
            }
        }
    }

上面的代码作用是将E:\TestCode文件夹下的所有图片文件加以识别。在java代码中调用dos命令使用tesseract工具。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值