hirakun-jpの日記

日記を書きます

画像中の数字を取得する2

前回記事画像中の数字を取得する - hirakun-jpの日記で使ったTesseractのラッパーとは別のものを使ってみた。

これです。 www.nuget.org

バージョンも4.0.0に上げて(前回は3.0.2)使ってみたけど、前より精度いい感じ。

string langPath = @"C:\Users\dev\Excel_Service\tessdata\tessdata_best";
            //string langPath = @"C:\Users\dev\Excel_Service\tessdata\special";
            string langStr = "eng";
            //string langStr = "equ";
            //string langStr = "jpn";
            string imgFile = @"C:\Users\dev\Excel_Service\images\num_example_oanda_web_002.png";
            //string imgFile = @"C:\Users\dev\Excel_Service\images\num_example_oanda_web_001.png";
            //string imgFile = @"C:\Users\dev\Excel_Service\images\num_example_MT4_001.png";
            //string imgFile = @"C:\Users\dev\Excel_Service\images\num_example_MT4_001_gray.png";
            //string imgFile = @"C:\Users\dev\Excel_Service\images\num_example_MT4_001_gray_reverse.png";
            OcrEngineMode oem = OcrEngineMode.LSTM_ONLY;
            PageSegmentationMode psm = PageSegmentationMode.AUTO_OSD;

            TessBaseAPI tessBaseAPI = new TessBaseAPI();

            // Initialize tesseract-ocr 
            if (!tessBaseAPI.Init(langPath, langStr, oem))
            {
                throw new Exception("Could not initialize tesseract.");
            }

            // Set the Page Segmentation mode
            tessBaseAPI.SetPageSegMode(psm);

            // 数字のみを対象とする
            tessBaseAPI.SetVariable("classify_bln_numeric_mode", "1");
            //tessBaseAPI.SetVariable("tessedit_char_whitelist", "1234567890");

            // 計測開始(今回は画像のセットから測る)
            var sw = new System.Diagnostics.Stopwatch();
            sw.Start();

            // Set the input image
            Pix pix = tessBaseAPI.SetImage(imgFile);

            // Recognize image
            tessBaseAPI.Recognize();

            ResultIterator resultIterator = tessBaseAPI.GetIterator();

            // Extract text from result iterator
            StringBuilder stringBuilder = new StringBuilder();
            PageIteratorLevel pageIteratorLevel = PageIteratorLevel.RIL_PARA;
            do
            {
                stringBuilder.Append(resultIterator.GetUTF8Text(pageIteratorLevel));
            } while (resultIterator.Next(pageIteratorLevel));

            tessBaseAPI.Dispose();
            pix.Dispose();

            // OCR表示
            textBlockOCR.Text = stringBuilder.ToString();

            // 計測終了・処理時間表示
            sw.Stop();
            textBlockTime.Text = sw.ElapsedMilliseconds.ToString() + "ms";
        }

画像データ

f:id:hirakun-jp:20180604165707p:plain

結果

f:id:hirakun-jp:20180605134208p:plain

JavaだとTess4jとかいうラッパー使うみたいだ TessAPI1.TessPageIteratorLevel (Tess4J API)

今回使ったC#のラッパーのWikiはこれ How to use tesseract.net · tvn-cosine/tesseract.net Wiki · GitHub

使ったデータファイルはこれ GitHub - tesseract-ocr/tessdata_best: Best (most accurate) trained LSTM models.

縦書きの日本語とか、数式に特化したやつとかあるみたい!