OCRImage Recognition技術的JAVA實現(一),ocr識別技術

來源:互聯網
上載者:User

OCRImage Recognition技術的JAVA實現(一),ocr識別技術
OCRImage Recognition技術的JAVA實現

最近有個需求需要用Image Recognition,學習記錄一下。
目前網路上的開源的Image Recognition技術有很多,例如 OCRE(OCR Easy)、Clara OCR、OCRAD、TESSERACT-OCR 等等,今天本blog將記錄下tesseract-ocr的JAVA實現,後面會記錄研究下Android的使用:

  • TESSERACT-OCR安裝
  • 程式實現
1、TESSERACT-OCR安裝

首先下載EXE安裝包進行安裝,我安裝的版本是“tesseract-ocr-setup-3.05.01.exe”,建議直接安裝在預設路徑。安裝完畢後,目錄下:

其中,檔案夾“tessdata”用於放置語言庫。

程式實現

上一步已經安裝好了TESSERACT-OCR,下面直接貼代碼。

核心代碼 OCRHelper.java:

package com.liping.test;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.List;/** * 圖文識別協助類 * * @author Felix Li * @create 2017-12-19-9:12 */public class OCRHelper {    private final String LANG_OPTION = "-l";    private final String EOL = System.getProperty("line.separator");    /**     *  Tesseract-OCR的安裝路徑     */    private String tessPath = "C://Program Files (x86)//Tesseract-OCR";    //private String tessPath = new File("tesseract").getAbsolutePath();    /**     * @param imageFile   傳入的影像檔     * @param imageFormat 傳入的映像格式     * @return 識別後的字串     */    public String recognizeText(File imageFile) throws Exception {        /**         * 設定輸出檔案的儲存的檔案目錄         */        File outputFile = new File(imageFile.getParentFile(), "output");        StringBuffer strB = new StringBuffer();        List<String> cmd = new ArrayList<String>();        cmd.add(tessPath + "\\tesseract");        cmd.add("");        cmd.add(outputFile.getName());        cmd.add(LANG_OPTION);        cmd.add("chi_sim");        //cmd.add("eng");        ProcessBuilder pb = new ProcessBuilder();        /**         *Sets this process builder's working directory.         */        pb.directory(imageFile.getParentFile());        cmd.set(1, imageFile.getName());        pb.command(cmd);        pb.redirectErrorStream(true);        long startTime = System.currentTimeMillis();        System.out.println("開始時間:" + startTime);        Process process = pb.start();        // tesseract.exe 1.jpg 1 -l chi_sim        //不習慣使用ProcessBuilder的,也可以使用Runtime,效果一致        // Runtime.getRuntime().exec("tesseract.exe 1.jpg 1 -l chi_sim");        /**         * the exit value of the process. By convention, 0 indicates normal         * termination.         *///      System.out.println(cmd.toString());        int w = process.waitFor();        if (w == 0)// 0代表正常退出        {            BufferedReader in = new BufferedReader(new InputStreamReader(                    new FileInputStream(outputFile.getAbsolutePath() + ".txt"),                    "UTF-8"));            String str;            while ((str = in.readLine()) != null) {                strB.append(str).append(EOL);            }            in.close();            long endTime = System.currentTimeMillis();            System.out.println("結束時間:" + endTime);            System.out.println("耗時:" + (endTime - startTime) + "毫秒");        } else {            String msg;            switch (w) {                case 1:                    msg = "Errors accessing files. There may be spaces in your image's filename.";                    break;                case 29:                    msg = "Cannot recognize the image or its selected region.";                    break;                case 31:                    msg = "Unsupported image format.";                    break;                default:                    msg = "Errors occurred.";            }            throw new RuntimeException(msg);        }        new File(outputFile.getAbsolutePath() + ".txt").delete();        return strB.toString().replaceAll("\\s*", "");    }}

測試類別Test.java:

package com.liping.test;import java.io.File;import java.io.IOException;/** * 測試主類 * * @author Felix Li * @create 2017-12-19-9:17 */public class Test {    public static void main(String[] args) {        try {            //圖片檔案:此圖片是需要被識別的圖片             File file = new File("C://Program Files (x86)//Tesseract-OCR//shouye.png");            String recognizeText = new OCRHelper().recognizeText(file);            System.out.print(recognizeText + "\t");        } catch (IOException e) {            e.printStackTrace();        } catch (Exception e) {            e.printStackTrace();        }    }}

以上就是TESSERACT-OCR的JAVA使用。

注意事項
圖片讀出來有的字元可能會亂碼,這是由於識別語言庫的原因,可以訓練語言庫,來提升識別準確率與識別速度,這個以後再講。
有問題的歡迎留言討論!

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.