如何在C#项目中实现和执行OCR?

Ber*_*eer 30 c# ocr

我一直在寻找一段时间以及所有我见过的OCR库请求.我想知道如何实现最纯净,易于安装和使用OCR库以及安装到C#项目的详细信息.

如果可行,我只想像通常的dll参考一样实现它...

例:

using org.pdfbox.pdmodel;
using org.pdfbox.util;
Run Code Online (Sandbox Code Playgroud)

还有一个小的OCR代码示例会很好,例如:

public string OCRFromBitmap(Bitmap Bmp)
{
    Bmp.Save(temppath, System.Drawing.Imaging.ImageFormat.Tiff);
    string OcrResult = Analyze(temppath);
    File.Delete(temppath);
    return OcrResult;
}
Run Code Online (Sandbox Code Playgroud)

所以请考虑我对OCR项目并不熟悉,并给我一个答案,比如和假人交谈.

编辑: 我猜人们误解了我的要求.我想知道如何将这些开源OCR库实现到C#项目以及如何使用它们.作为dup给出的链接没有给出我要求的答案.

B.K*_*.K. 82

如果有人在研究这个问题,我一直在尝试不同的选择,以下方法会产生非常好的结果.以下是获取工作示例的步骤:

  1. 为您的项目添加.NET Wrapper for tesseract.它可以通过NuGet包Install-Package Tesseract(https://github.com/charlesw/tesseract)添加.
  2. 转到官方Tesseract项目的下载部分(https://code.google.com/p/tesseract-ocr/ 编辑: 它现在位于:https://github.com/tesseract-ocr/langdata).
  3. 下载首选语言数据,例如:tesseract-ocr-3.02.eng.tar.gz English language data for Tesseract 3.02.
  4. tessdata在项目中创建目录并将语言数据文件放入其中.
  5. 转到Properties新添加的文件并将其设置为在构建时复制.
  6. 添加引用System.Drawing.
  7. 从.NET Wrapper存储库中,在Samples目录中将示例phototest.tif文件复制到项目目录中,并将其设置为在构建时复制.
  8. 在项目中创建以下两个文件(只是为了开始):

Program.cs中

using System;
using Tesseract;
using System.Diagnostics;

namespace ConsoleApplication
{
    class Program
    {
        public static void Main(string[] args)
        {
            var testImagePath = "./phototest.tif";
            if (args.Length > 0)
            {
                testImagePath = args[0];
            }

            try
            {
                var logger = new FormattedConsoleLogger();
                var resultPrinter = new ResultPrinter(logger);
                using (var engine = new TesseractEngine(@"./tessdata", "eng", EngineMode.Default))
                {
                    using (var img = Pix.LoadFromFile(testImagePath))
                    {
                        using (logger.Begin("Process image"))
                        {
                            var i = 1;
                            using (var page = engine.Process(img))
                            {
                                var text = page.GetText();
                                logger.Log("Text: {0}", text);
                                logger.Log("Mean confidence: {0}", page.GetMeanConfidence());

                                using (var iter = page.GetIterator())
                                {
                                    iter.Begin();
                                    do
                                    {
                                        if (i % 2 == 0)
                                        {
                                            using (logger.Begin("Line {0}", i))
                                            {
                                                do
                                                {
                                                    using (logger.Begin("Word Iteration"))
                                                    {
                                                        if (iter.IsAtBeginningOf(PageIteratorLevel.Block))
                                                        {
                                                            logger.Log("New block");
                                                        }
                                                        if (iter.IsAtBeginningOf(PageIteratorLevel.Para))
                                                        {
                                                            logger.Log("New paragraph");
                                                        }
                                                        if (iter.IsAtBeginningOf(PageIteratorLevel.TextLine))
                                                        {
                                                            logger.Log("New line");
                                                        }
                                                        logger.Log("word: " + iter.GetText(PageIteratorLevel.Word));
                                                    }
                                                } while (iter.Next(PageIteratorLevel.TextLine, PageIteratorLevel.Word));
                                            }
                                        }
                                        i++;
                                    } while (iter.Next(PageIteratorLevel.Para, PageIteratorLevel.TextLine));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Trace.TraceError(e.ToString());
                Console.WriteLine("Unexpected Error: " + e.Message);
                Console.WriteLine("Details: ");
                Console.WriteLine(e.ToString());
            }
            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }



        private class ResultPrinter
        {
            readonly FormattedConsoleLogger logger;

            public ResultPrinter(FormattedConsoleLogger logger)
            {
                this.logger = logger;
            }

            public void Print(ResultIterator iter)
            {
                logger.Log("Is beginning of block: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Block));
                logger.Log("Is beginning of para: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Para));
                logger.Log("Is beginning of text line: {0}", iter.IsAtBeginningOf(PageIteratorLevel.TextLine));
                logger.Log("Is beginning of word: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Word));
                logger.Log("Is beginning of symbol: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Symbol));

                logger.Log("Block text: \"{0}\"", iter.GetText(PageIteratorLevel.Block));
                logger.Log("Para text: \"{0}\"", iter.GetText(PageIteratorLevel.Para));
                logger.Log("TextLine text: \"{0}\"", iter.GetText(PageIteratorLevel.TextLine));
                logger.Log("Word text: \"{0}\"", iter.GetText(PageIteratorLevel.Word));
                logger.Log("Symbol text: \"{0}\"", iter.GetText(PageIteratorLevel.Symbol));
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

FormattedConsoleLogger.cs

using System;
using System.Collections.Generic;
using System.Text;
using Tesseract;

namespace ConsoleApplication
{
    public class FormattedConsoleLogger
    {
        const string Tab = "    ";
        private class Scope : DisposableBase
        {
            private int indentLevel;
            private string indent;
            private FormattedConsoleLogger container;

            public Scope(FormattedConsoleLogger container, int indentLevel)
            {
                this.container = container;
                this.indentLevel = indentLevel;
                StringBuilder indent = new StringBuilder();
                for (int i = 0; i < indentLevel; i++)
                {
                    indent.Append(Tab);
                }
                this.indent = indent.ToString();
            }

            public void Log(string format, object[] args)
            {
                var message = String.Format(format, args);
                StringBuilder indentedMessage = new StringBuilder(message.Length + indent.Length * 10);
                int i = 0;
                bool isNewLine = true;
                while (i < message.Length)
                {
                    if (message.Length > i && message[i] == '\r' && message[i + 1] == '\n')
                    {
                        indentedMessage.AppendLine();
                        isNewLine = true;
                        i += 2;
                    }
                    else if (message[i] == '\r' || message[i] == '\n')
                    {
                        indentedMessage.AppendLine();
                        isNewLine = true;
                        i++;
                    }
                    else
                    {
                        if (isNewLine)
                        {
                            indentedMessage.Append(indent);
                            isNewLine = false;
                        }
                        indentedMessage.Append(message[i]);
                        i++;
                    }
                }

                Console.WriteLine(indentedMessage.ToString());

            }

            public Scope Begin()
            {
                return new Scope(container, indentLevel + 1);
            }

            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    var scope = container.scopes.Pop();
                    if (scope != this)
                    {
                        throw new InvalidOperationException("Format scope removed out of order.");
                    }
                }
            }
        }

        private Stack<Scope> scopes = new Stack<Scope>();

        public IDisposable Begin(string title = "", params object[] args)
        {
            Log(title, args);
            Scope scope;
            if (scopes.Count == 0)
            {
                scope = new Scope(this, 1);
            }
            else
            {
                scope = ActiveScope.Begin();
            }
            scopes.Push(scope);
            return scope;
        }

        public void Log(string format, params object[] args)
        {
            if (scopes.Count > 0)
            {
                ActiveScope.Log(format, args);
            }
            else
            {
                Console.WriteLine(String.Format(format, args));
            }
        }

        private Scope ActiveScope
        {
            get
            {
                var top = scopes.Peek();
                if (top == null) throw new InvalidOperationException("No current scope");
                return top;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我希望我可以不止一次投票,因为这是一个很好的指令,让这个东西运行. (4认同)
  • @ BloodyRain2k很高兴您发现它很有用。谢谢你的客气话。 (2认同)
  • 我使用了你上面提到的链接。在 eng 文件夹 (https://github.com/tesseract-ocr/langdata/tree/master/eng) 中缺少一个文件,即 eng.traineddata。也请添加此文件。 (2认同)
  • @MugheesMusaddiq他们不断更改文件,这就是为什么我不愿意放置任何链接,因为它们不能保证是相同的.这更像是如何开始的指南,缺乏链接保证是我在这里粘贴了这么多代码的原因. (2认同)
  • 可以在此处下载旧版本的语言数据:https://sourceforge.net/projects/tesseract-ocr-alt/files/(例如,因为截至目前,NuGet包的版本为3.02,并且唯一的语言数据可用于站点链接bove是3.04;或者可以使用Wayback Machine) (2认同)

Rob*_* P. 10

这是一个:(查看http://hongouru.blogspot.ie/2011/09/c-ocr-optical-character-recognition.htmlhttp://www.codeproject.com/Articles/41709/How-To-使用-Office-2007-OCR-Using-C获取更多信息)

using MODI;
static void Main(string[] args)
{
    DocumentClass myDoc = new DocumentClass();
    myDoc.Create(@"theDocumentName.tiff"); //we work with the .tiff extension
    myDoc.OCR(MiLANGUAGES.miLANG_ENGLISH, true, true);

    foreach (Image anImage in myDoc.Images)
    {
        Console.WriteLine(anImage.Layout.Text); //here we cout to the console.
    }
}
Run Code Online (Sandbox Code Playgroud)


Ben*_*ker 6

我正在使用带有TessNet2的tesseract OCR引擎(一个C#包装器 - http://www.pixel-technology.com/freeware/tessnet2/).

一些基本代码:

using tessnet2;
Run Code Online (Sandbox Code Playgroud)

...

Bitmap image = new Bitmap(@"u:\user files\bwalker\2849257.tif");
            tessnet2.Tesseract ocr = new tessnet2.Tesseract();
            ocr.SetVariable("tessedit_char_whitelist", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.,$-/#&=()\"':?"); // Accepted characters
            ocr.Init(@"C:\Users\bwalker\Documents\Visual Studio 2010\Projects\tessnetWinForms\tessnetWinForms\bin\Release\", "eng", false); // Directory of your tessdata folder
            List<tessnet2.Word> result = ocr.DoOCR(image, System.Drawing.Rectangle.Empty);
            string Results = "";
            foreach (tessnet2.Word word in result)
            {
                Results += word.Confidence + ", " + word.Text + ", " + word.Left + ", " + word.Top + ", " + word.Bottom + ", " + word.Right + "\n";
            }
Run Code Online (Sandbox Code Playgroud)

  • 我实际上在 NuGet 中找到了 tessnet2,不知道为什么我不先看看那里。当我运行它时,它停在 ocr.Init 行。该目录中是否有特定的内容?tessnet2_32.dll 位于我的“tessdata”文件夹中,就像我的应用程序 exe 文件一样。知道它为什么停止吗?它根本没有做任何事情。 (2认同)