【示例教程】如何用leadtools建立一個OCR驅動的計算器

Leadtools 19總套包下載>>>測試

平常工做和業務中會有一些圖片中的計算公式等須要計算,這個代碼片段顯示了LEADTOOLS OCR能夠用來檢測、識別和執行簡單的數學命題,如「2 + 2」。code

static void SimpleOCRCalculator(string filePath)
      {
         RasterCodecs codecs = new RasterCodecs();

         RasterImage image = codecs.Load(filePath);

         string[] calculations;
         using (IOcrEngine engine = OcrEngineManager.CreateEngine(OcrEngineType.Advantage, false))
         {
            engine.Startup(null, null, null, null);
            IOcrPage page = engine.CreatePage(image, OcrImageSharingMode.None);

            page.AutoZone(null);
            page.Recognize(null);

            calculations = new string[page.Zones.Count];

            for (int i = 0; i < page.Zones.Count; i++)
            {
               calculations[i] = page.GetText(i);
            }

            engine.Shutdown();
         }

         Dictionary<string, Action<double, double>> operands = new Dictionary<string, Action<double, double>>();
         operands.Add("+", new Action<double, double>(delegate(double a, double b) { double ans = a + b; Console.WriteLine("{0} + {1} = {2}", a, b, ans); }));
         operands.Add("-", new Action<double, double>(delegate(double a, double b) { double ans = a - b; Console.WriteLine("{0} - {1} = {2}", a, b, ans); }));
         operands.Add("x", new Action<double, double>(delegate(double a, double b) { double ans = a * b; Console.WriteLine("{0} * {1} = {2}", a, b, ans); }));
         operands.Add("/", new Action<double, double>(delegate(double a, double b) { double ans = a / b; Console.WriteLine("{0} / {1} = {2}", a, b, ans); }));

         for (int i = 0; i < calculations.Length; i++)
         {
            string equation = Regex.Replace(calculations[i], @"\n|\r| ", "");
            string[] ops = new string[] { "+", "-", "x", "/" };

            for (int j = 0; j < ops.Length; j++)
            {
               int index = equation.IndexOf(ops[j]);

               if (index > 0 && index < equation.Length)
               {
                  string op1 = equation.Substring(0, index);
                  string op2 = equation.Substring(index + 1);

                  double arg1 = double.Parse(op1);
                  double arg2 = double.Parse(op2);

                  operands[ops[j]](arg1, arg2);

                  break;
               }
            }
         }

         codecs.Dispose();
         image.Dispose();
      }

 

用於測試的圖像以下。blog

resource

相關文章
相關標籤/搜索