28

嗨,谁能给我一个简单的例子,最好是在 C# 中测试 Tesseract OCR。我尝试了在这里
找到的演示。我下载英文数据集并解压到 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!但这对我来说是一个非常大的项目。我需要一个像上面这样的简单例子。

4

9 回答 9

19

好的。我在这里找到了解决方案 tessnet2 failed to load the Ans given by Adam

显然我使用了错误版本的 tessdata。我直观地遵循源页面说明,这导致了问题。

它说

快速 Tessnet2 使用

  1. 在此处下载二进制文件,将程序集 Tessnet2.dll 的引用添加到您的 .NET 项目中。

  2. 在此处下载语言数据定义文件并将其放在 tessdata 目录中。Tessdata 目录和你的 exe 必须在同一个目录下。

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

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

于 2013-05-17T14:01:02.970 回答
12

在 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\

于 2016-10-04T13:34:13.197 回答
4

按照这些说明,我能够让它工作。

  • 下载示例代码 正方体示例代码

  • 解压到新位置

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

  • 为该项目安装 Tesseract NuGet 包(或根据我的需要卸载/重新安装) NuGet 正方体

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

  • 运行(按 F5)

  • 你应该得到这个 Windows 控制台输出 在此处输入图像描述

于 2018-01-23T14:02:24.780 回答
1

尝试将行更新为:

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

于 2013-05-17T08:12:08.827 回答
0

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

于 2013-12-17T06:46:26.147 回答
0

这对我有用,我还有 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... 
于 2015-02-03T11:25:27.150 回答
0

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

但是你需要考虑以下几点:

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

希望这会有所帮助

于 2015-04-10T07:28:33.380 回答
0

这是一个很棒的工作示例项目;带有 Leptonica 预处理的 Tesseract OCR 示例 (Visual Studio) 带有 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 解决方案资源管理器中单击您的项目,然后转到项目>属性。

VC++ 目录>包含目录:

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

_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) C/C++>Linker>Input>Additional Dependencies:

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

包括

包括

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

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

tesseract::TessBaseAPI *api = 新的 tesseract::TessBaseAPI(); api->Init("D:\tessdataParentFolder\", ... 示例

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

于 2016-07-08T13:05:27.770 回答
0

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

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

(免责声明:我确实为 Iron Software 工作,但我觉得其他人可以从这些信息中受益,特别是因为它与IronOcr擅长的在 C#中使用Tesseract OCR的问题有关)。

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;
                }
            }
        }
    }
}
}
于 2021-08-24T08:40:41.823 回答