如何用leadtools创建一个OCR驱动的计算器

发布时间:2017/11/07 00:11 发布者:Richard.Ma

返回博客中心

日常工作和业务中会有一些图片中的计算公式等需要计算,这个代码片断显示了LEADTOOLS OCR可以用来检测、识别和执行简单的数学命题,如“2 + 2”。

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();
      }

 

用于测试的图像如下。

resource


关于葡萄城

赋能开发者!葡萄城是专业的集开发工具、商业智能解决方案、低代码开发平台于一身的软件和服务提供商,为超过 75% 的全球财富 500 强企业提供服务。葡萄城专注控件软件领域30年,希望通过模块化的开发控件、灵活的低代码应用开发平台等一系列开发工具、解决方案和服务,帮助开发者快速响应复杂多变的业务需求,最大程度地发挥开发者的才智和潜能,让开发者的 IT 人生更从容更美好。

了解详情,请访问葡萄城官网