【问题标题】:Tesseract OCR simple example正方体 OCR 简单示例
【发布时间】:2013-05-11 23:49:57
【问题描述】:

您好,谁能给我一个测试 Tesseract OCR 的简单示例 最好在 C# 中。
我尝试了找到here 的演示。 我下载英文数据集并解压到 C 盘。并修改代码如下:

string path = @"C:\pic\mytext.jpg";
Bitmap image = new Bitmap(path);
Tesseract ocr = new Tesseract();
ocr.SetVariable("tessedit_char_whitelist", "0123456789"); // If digit only
ocr.Init(@"C:\tessdata\", "eng", false); // To use correct tessdata
List<tessnet2.Word> result = ocr.DoOCR(image, Rectangle.Empty);
foreach (tessnet2.Word word in result)
    Console.WriteLine("{0} : {1}", word.Confidence, word.Text);

不幸的是,代码不起作用。程序在 "ocr.Init(..." 行终止。即使使用 try-catch,我什至无法获得异常。

我能够运行vietocr!但这对我来说是一个非常大的项目。我需要一个像上面这样的简单例子。

【问题讨论】:

  • 你所说的“它不起作用”是什么意思,它是崩溃还是只是不做你想做的事?
  • 好吧,程序刚刚关闭,没有任何错误或异常。它将输出写入控制台。所以我做了配音并逐行进行。发现程序在第5行退出 -> ocr.Init(@"C:\tessdata\", "eng", false);
  • 您可以单步执行该函数并找出导致程序退出的原因。
  • C盘下加载tessdata会不会有权限问题?可以改变路径再试一次。
  • 函数在 tessnet dll 中。我进不去!它是一台 Windows 7 机器,我以管理员身份登录。我不明白为什么会有权限问题。我什至没有其他驱动器

标签: c# ocr tesseract


【解决方案1】:

好的。我在这里找到了解决方案 tessnet2 fails to load 亚当给出的答案

显然我使用了错误版本的 tessdata。我直观地遵循了the source page 指令,这导致了问题。

它说

快速 Tessnet2 使用

  1. Download binary here,将程序集 Tessnet2.dll 的引用添加到您的 .NET 项目中。

  2. 下载语言数据定义文件here,放到tessdata目录下。 Tessdata 目录和你的 exe 必须在 同一个目录。

下载二进制文件后,当你点击链接下载语言文件时,有很多语言文件。但它们都不是正确的版本。您需要选择所有版本并转到下一页以获得正确的版本(tesseract-2.00.eng)!他们应该将下载二进制链接更新到版本 3,或者将版本 2 语言文件放在第一页。或者至少大胆地提一下这个版本问题很重要的事实!

反正我找到了。 谢谢大家。

【讨论】:

  • @ Will Robinson,我也遇到了同样的问题。我已经尝试了您的上述程序...但仍然遇到您遇到的相同问题..首先,我已经从您的链接下载了二进制文件并在我的桌面中提取。然后从Release32文件夹中添加tessnet2_32.dll文件的引用。其次,我已经从您的链接中下载了LDD文件,并将该文件提取到我的桌面中。它有一个名为tessdata的目录并将其放入在我的项目 bin\debug 文件夹中(我的项目 exe 也在这个文件夹中)。但是直到现在都面临同样的问题......请帮我解决这个问题......
  • 您是否尝试下载正确版本的 tessdata? tesseract-2.00.eng 一直在列表的第二页。
  • @Will Robinson:我的 VS 是 2008,Windows XP(32 位)。我按照您的指示进行了操作,但没有成功。它运行到“tessocr.Init ...”这一行,然后VS停止执行,没有任何错误消息或异常。作为一种解决方法,我下载了包含英语语言包的 tesseract-3.00 (code.google.com/p/tesseract-ocr/downloads/…) 版本。
【解决方案2】:

在 C# 中测试 Tesseract OCR 的简单示例:

    public static string GetText(Bitmap imgsource)
    {
        var ocrtext = string.Empty;
        using (var engine = new TesseractEngine(@"./tessdata", "eng", EngineMode.Default))
        {
            using (var img = PixConverter.ToPix(imgsource))
            {
                using (var page = engine.Process(img))
                {
                    ocrtext = page.GetText();
                }
            }
        }

        return ocrtext;
    }

信息:tessdata 文件夹必须存在于存储库中:bin\Debug\

【讨论】:

  • 我运行了这段代码,它显示“无法找到 x86 平台的库 \"liblept172.dll\"。”调试时。错误发生在第一个 using 语句处。我找到了liblept172.ddl并把它复制到了bin文件夹,实际上我复制了很多地方都没有用。我正在使用 NuGet 的 Tesseract v3.0.2。我找不到 tessnet2,因为互联网上指向它的所有链接似乎都已损坏。
  • 这里的PixConverter 是什么? Tesseract 包中似乎没有任何具有此类名称的类。
【解决方案3】:

我可以通过关注这些instructions 来让它工作。

  • 下载sample code

  • 解压到新位置

  • 打开 ~\tesseract-samples-master\src\Tesseract.Samples.sln(我用的是 Visual Studio 2017)

  • 为该项目安装 Tesseract NuGet 包(或者我必须卸载/重新安装)

  • 取消注释 Tesseract.Samples.Program.cs 中最后两行有意义的行: Console.Write("Press any key to continue . . . "); Console.ReadKey(true);

  • 运行(按 F5)

  • 你应该得到这个 Windows 控制台输出

【讨论】:

    【解决方案4】:

    尝试将行更新为:

    ocr.Init(@"C:\", "eng", false); // 这里的路径应该是tessdata的父文件夹

    【讨论】:

    • 只是累了。还是一样的问题。
    【解决方案5】:

    我有同样的问题,现在解决了。我有 tesseract2,在这个 32 位和 64 位文件夹下,我将文件 64 位文件夹(因为我的系统是 64 位)复制到主文件夹(“Tesseract2”)和 bin/Debug 文件夹下。现在我的解决方案运行良好。

    【讨论】:

      【解决方案6】:

      就我而言,除了正确的字符识别之外,我已经完成了所有这些工作。

      但你需要考虑以下几点:

      • 使用正确的 tessnet2 库
      • 使用正确的 tessdata 语言版本
      • tessdata 应该位于应用程序文件夹之外的某个位置,您可以在其中将完整路径放入 init 参数中。使用ocr.Init(@"c:\tessdata", "eng", true);
      • 调试会让你头疼。然后你需要更新你的 app.config 用这个。 (我不能把xml代码放在这里。给我你的email我会email给你)

      希望这会有所帮助

      【讨论】:

        【解决方案7】:

        这是一个很棒的工作示例项目; Tesseract OCR Sample (Visual Studio) with Leptonica Preprocessing 具有 Leptonica 预处理的 Tesseract OCR 示例 (Visual Studio)

        Tesseract OCR 3.02.02 API 可能会造成混淆,因此本文将指导您将 Tesseract 和 Leptonica dll 包含到 Visual Studio C++ 项目中,并提供一个示例文件,该文件采用图像路径进行预处理和 OCR。 Leptonica 中的预处理脚本将输入图像转换为黑白书籍般的文本。

        设置

        要将其包含在您自己的项目中,您需要引用头文件和 lib 并复制 tessdata 文件夹和 dll。

        将 tesseract-include 文件夹复制到项目的根文件夹。现在在 Visual Studio 解决方案资源管理器中单击您的项目,然后转到 Project>Properties。

        VC++ 目录>包含目录:

        ..\tesseract-include\tesseract;..\tesseract-include\leptonica;$(IncludePath) C/C++>预处理器>预处理器定义:

        _CRT_SECURE_NO_WARNINGS;%(预处理器定义) C/C++>链接器>输入>附加依赖:

        ..\tesseract-include\libtesseract302.lib;..\tesseract-include\liblept168.lib;%(AdditionalDependencies) 现在您可以在项目文件中包含标头:

        包括

        包括

        现在将 tesseract-include 中的两个 dll 文件和 Debug 中的 tessdata 文件夹复制到项目的输出目录中。

        初始化 tesseract 时,如果 tessdata 文件夹的父文件夹 (!important) 还不是可执行文件的当前目录,则需要指定它的位置。您可以复制我的脚本,假设 tessdata 已安装在可执行文件的文件夹中。

        tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI(); api->Init("D:\tessdataParentFolder\", ... 样本

        您可以编译提供的示例,该示例需要使用图像路径的一个命令行参数。 preprocess() 函数使用 Leptonica 创建图像的黑白书状副本,这使得 tesseract 以 90% 的准确率工作。 ocr() 函数显示了 Tesseract API 返回字符串输出的功能。 toClipboard() 可用于将文本保存到 Windows 上的剪贴板。您可以将这些复制到您自己的项目中。

        【讨论】:

          【解决方案8】:

          这对我有用,我还有 3-4 个 PDF 到文本提取器,如果一个不工作,另一个将......特别是 tesseract 这段代码可以在 Windows 7、8、Server 2008 上使用。希望对你有帮助

              do
              {
              // Sleep or Pause the Thread for 1 sec, if service is running too fast...
              Thread.Sleep(millisecondsTimeout: 1000);
              Guid tempGuid = ToSeqGuid();
              string newFileName = tempGuid.ToString().Split('-')[0];
              string outputFileName = appPath + "\\pdf2png\\" + fileNameithoutExtension + "-" + newFileName +
                                      ".png";
              extractor.SaveCurrentImageToFile(outputFileName, ImageFormat.Png);
              // Create text file here using Tesseract
              foreach (var file in Directory.GetFiles(appPath + "\\pdf2png"))
              {
                  try
                  {
                      var pngFileName = Path.GetFileNameWithoutExtension(file);
                      string[] myArguments =
                      {
                          "/C tesseract ", file,
                          " " + appPath + "\\png2text\\" + pngFileName
                      }; // /C for closing process automatically whent completes
                      string strParam = String.Join(" ", myArguments);
          
                      var myCmdProcess = new Process();
                      var theProcess = new ProcessStartInfo("cmd.exe", strParam)
                      {
                          CreateNoWindow = true,
                          UseShellExecute = false,
                          RedirectStandardOutput = true,
                          RedirectStandardError = true,
                          WindowStyle = ProcessWindowStyle.Minimized
                      }; // Keep the cmd.exe window minimized
                      myCmdProcess.StartInfo = theProcess;
                      myCmdProcess.Exited += myCmdProcess_Exited;
                      myCmdProcess.Start();
          
                      //if (process)
                      {
                          /*
                          MessageBox.Show("cmd.exe process started: " + Environment.NewLine +
                                          "Process Name: " + myCmdProcess.ProcessName +
                                          Environment.NewLine + " Process Id: " + myCmdProcess.Id
                                          + Environment.NewLine + "process.Handle: " +
                                          myCmdProcess.Handle);
                          */
                          Process.EnterDebugMode();
                          //ShowWindow(hWnd: process.Handle, nCmdShow: 2);
                          /*
                          MessageBox.Show("After EnterDebugMode() cmd.exe process Exited: " +
                                          Environment.NewLine +
                                          "Process Name: " + myCmdProcess.ProcessName +
                                          Environment.NewLine + " Process Id: " + myCmdProcess.Id
                                          + Environment.NewLine + "process.Handle: " +
                                          myCmdProcess.Handle);
                          */
                          myCmdProcess.WaitForExit(60000);
                          /*
                          MessageBox.Show("After WaitForExit() cmd.exe process Exited: " +
                                          Environment.NewLine +
                                          "Process Name: " + myCmdProcess.ProcessName +
                                          Environment.NewLine + " Process Id: " + myCmdProcess.Id
                                          + Environment.NewLine + "process.Handle: " +
                                          myCmdProcess.Handle);
                          */
                          myCmdProcess.Refresh();
                          Process.LeaveDebugMode();
                          //myCmdProcess.Dispose();
                          /*
                          MessageBox.Show("After LeaveDebugMode() cmd.exe process Exited: " +
                                          Environment.NewLine);
                          */
                      }
          
          
                      //process.Kill();
                      // Waits for the process to complete task and exites automatically
                      Thread.Sleep(millisecondsTimeout: 1000);
          
                      // This works fine in Windows 7 Environment, and not in Windows 8
                      // Try following code block
                      // Check, if process is not comletey exited
          
                      if (!myCmdProcess.HasExited)
                      {
                          //process.WaitForExit(2000); // Try to wait for exit 2 more seconds
                          /*
                          MessageBox.Show(" Process of cmd.exe was exited by WaitForExit(); Method " +
                                          Environment.NewLine);
                          */
                          try
                          {
                              // If not, then Kill the process
                              myCmdProcess.Kill();
                              //myCmdProcess.Dispose();
                              //if (!myCmdProcess.HasExited)
                              //{
                              //    myCmdProcess.Kill();
                              //}
          
                              MessageBox.Show(" Process of cmd.exe exited ( Killed ) successfully " +
                                              Environment.NewLine);
                          }
                          catch (System.ComponentModel.Win32Exception ex)
                          {
                              MessageBox.Show(
                                  " Exception: System.ComponentModel.Win32Exception " +
                                  ex.ErrorCode + Environment.NewLine);
                          }
                          catch (NotSupportedException notSupporEx)
                          {
                              MessageBox.Show(" Exception: NotSupportedException " +
                                              notSupporEx.Message +
                                              Environment.NewLine);
                          }
                          catch (InvalidOperationException invalidOperation)
                          {
                              MessageBox.Show(
                                  " Exception: InvalidOperationException " +
                                  invalidOperation.Message + Environment.NewLine);
                              foreach (
                                  var textFile in Directory.GetFiles(appPath + "\\png2text", "*.txt",
                                      SearchOption.AllDirectories))
                              {
                                  loggingInfo += textFile +
                                                 " In Reading Text from generated text file by Tesseract " +
                                                 Environment.NewLine;
                                  strBldr.Append(File.ReadAllText(textFile));
                              }
                              // Delete text file after reading text here
                              Directory.GetFiles(appPath + "\\pdf2png").ToList().ForEach(File.Delete);
                              Directory.GetFiles(appPath + "\\png2text").ToList().ForEach(File.Delete);
                          }
                      }
                  }
                  catch (Exception exception)
                  {
                      MessageBox.Show(
                          " Cought Exception in Generating image do{...}while{...} function " +
                          Environment.NewLine + exception.Message + Environment.NewLine);
                  }
              }
              // Delete png image here
              Directory.GetFiles(appPath + "\\pdf2png").ToList().ForEach(File.Delete);
              Thread.Sleep(millisecondsTimeout: 1000);
              // Read text from text file here
              foreach (var textFile in Directory.GetFiles(appPath + "\\png2text", "*.txt",
                  SearchOption.AllDirectories))
              {
                  loggingInfo += textFile +
                                 " In Reading Text from generated text file by Tesseract " +
                                 Environment.NewLine;
                  strBldr.Append(File.ReadAllText(textFile));
              }
              // Delete text file after reading text here
              Directory.GetFiles(appPath + "\\png2text").ToList().ForEach(File.Delete);
          } while (extractor.GetNextImage()); // Advance image enumeration... 
          

          【讨论】:

          • 可以在 code.google.com Tesseract OCR 开源引擎上进行设置。
          【解决方案9】:

          诚然,当 Tesseract 3 是可用版本时,这是一个较老的问题,但它出现在我的搜索结果中,同时寻找相关问题和问题以及其他答案,突出了实际获取困难的仍然有效问题已安装 Tesseract,更不用说将其配置为正常工作了。

          在 IronOcr 中有一个更简单的解决方案(并使用更新的 Tesseract 5 引擎)为您完成所有工作。

          (免责声明:我确实为 Iron Software 工作,但我觉得其他人可以从这些信息中受益,尤其是涉及到使用 IronOcr 擅长的 Tesseract OCR in C# 的问题)。

          using IronOcr;
          var Ocr = new IronTesseract(); // nothing to configure
          Ocr.Configuration.WhiteListCharacters = "0123456789"; // If digit only
          using (var Input = new OcrInput(@"example.tiff"))
          {
          OcrResult Result = Ocr.Read(Input);
          foreach (var Page in Result.Pages)
          {
              // Page object
              int PageNumber = Page.PageNumber;
              string PageText = Page.Text;
              int PageWordCount = Page.WordCount;
              // null if we dont set Ocr.Configuration.ReadBarCodes = true;
              OcrResult.Barcode[] Barcodes = Page.Barcodes;
              System.Drawing.Bitmap PageImage = Page.ToBitmap(Input);
              int PageWidth = Page.Width;
              int PageHeight = Page.Height;
              foreach (var Paragraph in Page.Paragraphs)
              {
                  // Pages -> Paragraphs
                  int ParagraphNumber = Paragraph.ParagraphNumber;
                  String ParagraphText = Paragraph.Text;
                  System.Drawing.Bitmap ParagraphImage = Paragraph.ToBitmap(Input);
                  int ParagraphX_location = Paragraph.X;
                  int ParagraphY_location = Paragraph.Y;
                  int ParagraphWidth = Paragraph.Width;
                  int ParagraphHeight = Paragraph.Height;
                  double ParagraphOcrAccuracy = Paragraph.Confidence;
                  OcrResult.TextFlow paragrapthText_direction = Paragraph.TextDirection;
                  foreach (var Line in Paragraph.Lines)
                  {
                      // Pages -> Paragraphs -> Lines
                      int LineNumber = Line.LineNumber;
                      String LineText = Line.Text;
                      System.Drawing.Bitmap LineImage = Line.ToBitmap(Input); ;
                      int LineX_location = Line.X;
                      int LineY_location = Line.Y;
                      int LineWidth = Line.Width;
                      int LineHeight = Line.Height;
                      double LineOcrAccuracy = Line.Confidence;
                      double LineSkew = Line.BaselineAngle;
                      double LineOffset = Line.BaselineOffset;
                      foreach (var Word in Line.Words)
                      {
                          // Pages -> Paragraphs -> Lines -> Words
                          int WordNumber = Word.WordNumber;
                          String WordText = Word.Text;
                          System.Drawing.Image WordImage = Word.ToBitmap(Input);
                          int WordX_location = Word.X;
                          int WordY_location = Word.Y;
                          int WordWidth = Word.Width;
                          int WordHeight = Word.Height;
                          double WordOcrAccuracy = Word.Confidence;
                          if (Word.Font != null)
                          {
                              // Word.Font is only set when using Tesseract Engine Modes rather than LTSM
                              String FontName = Word.Font.FontName;
                              double FontSize = Word.Font.FontSize;
                              bool IsBold = Word.Font.IsBold;
                              bool IsFixedWidth = Word.Font.IsFixedWidth;
                              bool IsItalic = Word.Font.IsItalic;
                              bool IsSerif = Word.Font.IsSerif;
                              bool IsUnderLined = Word.Font.IsUnderlined;
                              bool IsFancy = Word.Font.IsCaligraphic;
                          }
                          foreach (var Character in Word.Characters)
                          {
                              // Pages -> Paragraphs -> Lines -> Words -> Characters
                              int CharacterNumber = Character.CharacterNumber;
                              String CharacterText = Character.Text;
                              System.Drawing.Bitmap CharacterImage = Character.ToBitmap(Input);
                              int CharacterX_location = Character.X;
                              int CharacterY_location = Character.Y;
                              int CharacterWidth = Character.Width;
                              int CharacterHeight = Character.Height;
                              double CharacterOcrAccuracy = Character.Confidence;
                              // Output alternative symbols choices and their probability.
                              // Very useful for spellchecking
                              OcrResult.Choice[] Choices = Character.Choices;
                          }
                      }
                  }
              }
          }
          }
          

          【讨论】:

          • 确认 - 工作
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-08-10
          • 2015-04-21
          • 2013-02-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多