Getting Started with OCR in C# and VB.Net - WBCB: The Valley's CW |

Getting Started with OCR in C# and VB.Net

Posted:

 

Getting Started with OCR in C# and VB.Net

IronOCR is a C# software library allowing .NET platform software developers to recognize and read text from images and PDF documents. It converts images to text. As a bonus, Iron OCR can also read barcodes and QR codes and return them to the developer.

Installation

The first thing we have to do is install our OCR library into a Visual Studio project. To do this, we can choose one of two approaches:

  1. The easiest way to http://ironsoftware.com/csharp/ocr is using NuGet Package Manager for Visual-Studio. The package name is “IronOcr”
  2. Download the IronOcr DLL directly from our homepage.
 PM > Install-Package IronOcr

Why Choose IronOCR?

Iron OCR is an easy-to-install, complete and well-documented .NET software library. Iron OCR shines when working with real world images and imperfect documents such as photographs, or scans of low resolution which may have digital noise or imperfections. Other free OCR libraries for the .NET platform such as Tesseract do not perform so well on these real world use cases.

Iron OCR provides an excellent balance of performance against accuracy for image-to-text conversion in .NET.

Automated OCR

The Iron OCR Automated OCR class is the easiest way for developers to get started with optical character recognition in .NET. The Auto OCR class automatically detects image properties and adjusts for them, making best guesses about the most appropriate settings to read that document. It automatically corrects for digital noise, rotation, perspective, and even low-resolution documents.

The code sample below shows how easy it is to read text from an image using C# or VB .NET.

  1. using System;
  2. using IronOcr;
  3. //..
  4. var Ocr = new AutoOcr();
  5. var Result = Ocr.Read(@"C:\path\to\any\image.png");
  6. Console.WriteLine(Result.Text);

The same approach can similarly be used to extract text from a PDF document.

  1. using System;
  2. using IronOcr;
  3. var Ocr = new IronOcr.AutoOcr();
  4. var Results = Ocr.ReadPdf(@"C:\Users\Me\Desktop\Invoice.pdf");
  5. var Barcodes = Results.Barcodes;
  6. var Text = Results.Text;
  7. Console.WriteLine(Text);

Advanced OCR

The Iron OCR Advanced OCR class gives the developer granular control over the OCR operation, allowing them to achieve the highest degree of accuracy for very specific use cases.

  1. using IronOcr;
  2. //..
  3. var Ocr = new AdvancedOcr()
  4. {
  5. CleanBackgroundNoise = true,
  6. EnhanceContrast = true,
  7. EnhanceResolution = true,
  8. Language = IronOcr.Languages.English.OcrLanguagePack,
  9. Strategy = IronOcr.AdvancedOcr.OcrStrategy.Advanced,
  10. ColorSpace = AdvancedOcr.OcrColorSpace.Color,
  11. DetectWhiteTextOnDarkBackgrounds = true,
  12. InputImageType = AdvancedOcr.InputTypes.AutoDetect,
  13. RotateAndStraighten = true,
  14. ReadBarCodes = true,
  15. ColorDepth = 4
  16. };
  17. var testImage = @"C:\path\to\scan.tiff";
  18. var Results = Ocr.Read(testImage);
  19. var Barcodes = Results.Barcodes.Select(b => b.Value);
  20. Console.WriteLine(Results.Text);
  21. Console.WriteLine("Barcodes:" + String.Join(",", Barcodes));

Iron Advanced OCR can also be used to extract text from pages or entire PDF documents.

  1. using IronOcr;
  2. var Ocr = new AdvancedOcr()
  3. {
  4. CleanBackgroundNoise = false,
  5. ColorDepth = 4,
  6. ColorSpace = AdvancedOcr.OcrColorSpace.Color,
  7. EnhanceContrast = false,
  8. DetectWhiteTextOnDarkBackgrounds = false,
  9. RotateAndStraighten = false,
  10. Language = IronOcr.Languages.English.OcrLanguagePack,
  11. EnhanceResolution = false,
  12. InputImageType = AdvancedOcr.InputTypes.Document,
  13. ReadBarCodes = true,
  14. Strategy = AdvancedOcr.OcrStrategy.Fast
  15. };
  16. var PagesToRead = new []{1,2,3};
  17. var Results = Ocr.ReadPdf(@"C:\Users\Me\Desktop\Invoice.pdf", PagesToRead);
  18. var Pages = Results.Pages;
  19. var Barcodes = Results.Barcodes;
  20. var FullPdfText = Results.Text;

Advanced OCR settings include:

CleanBackgroundNoise. This is a setting which is somewhat time-consuming; however, it allows the library to automatically clean digital noise, paper crumples, and other imperfections within a digital image which would otherwise render it incapable of being read by other OCR libraries.

EnhanceContrast is a setting which causes Iron OCR to automatically increase the contrast of text against the background of an image, increasing the accuracy of OCR and generally increasing performance and the speed of OCR.

EnhanceResolution is a setting which will automatically detect low-resolution images (which are under 275 dpi) and automatically upscale the image and then sharpen all of the text so it can be read perfectly by an OCR library. Although this operation is in itself time-consuming, it generally reduces the overall time for an OCR operation on an image.

Language Iron OCR supports 22 international language packs, and the language setting can be used to select one or more multiple languages to be applied for an OCR operation.

Strategy Iron OCR supports two strategies. We may choose to either go for a fast and less accurate scan of a document, or use an advanced strategy which uses some artificial intelligence models to automatically improve the accuracy of OCR text by looking at the statistical relationship of words to one another in a sentence.

ColorSpace is a setting whereby we can choose to OCR in grayscale or color. Generally, grayscale is the best option. However, sometimes when there are texts or backgrounds of similar hue but very different color, a full-color color space will provide better results.

DetectWhiteTextOnDarkBackgrounds. Generally, all OCR libraries expect to see black text on white backgrounds. This setting allows Iron OCR to automatically detect negatives, or dark pages with white text, and read them.

InputImageType. This setting allows the developer to guide the OCR library as to whether it is looking at a full document or a snippet, such as a screenshot.

RotateAndStraighten is an advanced setting which allows Iron OCR the unique ability to read documents which are not only rotated, but perhaps containing perspective, such as photographs of text documents.

ReadBarcodes is a useful feature which allows Iron OCR to automatically read barcodes and QR codes on pages as it also reads text, without adding a large additional time burden.

ColorDepth. This setting determines how many bits per pixel the OCR library will use to determine the depth of a color. A higher color depth may increase OCR quality, but will also increase the time required for the OCR operation to complete.

Language Packs

Iron OCR has support for 22 international languages. By default, only English is installed. You can install additional languages via NuGet or by downloading DLLs from our Language Packs page.

  1. var Ocr = new AutoOcr()
  2. {
  3. Language = IronOcr.Languages.Arabic.OcrLanguagePack,
  4. };
  5. var results = Ocr.Read(@"path\to\arabic\document.png");

Likewise for AdvancedOcr:

  1. var Ocr = new AdvancedOcr()
  2. {
  3. Language = IronOcr.Languages.Arabic.OcrLanguagePack,
  4. //...
  5. };
  6. var results = Ocr.Read(@"path\to\arabic\document.png");

Barcodes and QR

A bonus feature of Iron OCR is it can read barcodes and QR codes from documents while it is scanning for text. Instances of the OcrResult.OcrBarcode Class give the developer detailed information about each scanned barcode.

  1. using IronOcr;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Drawing; //Add Assembly Reference
  5. // We can delve deep into OCR results as an object model of
  6. // Pages, Barcodes, Paragraphs, Lines, Words and Characters
  7. var Ocr = new AdvancedOcr()
  8. {
  9. ReadBarCodes = true,
  10. Strategy = AdvancedOcr.OcrStrategy.Fast,
  11. InputImageType = AdvancedOcr.InputTypes.Document
  12. };
  13. var Results = Ocr.Read(@"path\to\document.pdf");
  14. foreach (var Page in Results.Pages)
  15. {
  16. // page object
  17. foreach (var Barcode in Page.Barcodes){
  18. Console.WriteLine("Barcode of type {0} with value {1} found on page {2}", Barcode.Format.ToString(), Barcode.Value, Barcode.PageNumber);
  19. // location and an image of teh barcode may also be returned as required
  20. }
  21. }

Crop Regions

All of Iron OCR’s scanning and reading methods provide the ability to add a crop region, or to specify exactly which part of a page or pages we wish to read text from. This is very useful when we are looking at standardized forms and can save an awful lot of time and improve efficiency.

To use crop regions, we will need to add a system reference to the System.Drawing DLL so that we can use the System.Drawing.Rectangle object.

  1. using IronOcr;
  2. using System;
  3. using System.Drawing; //Add Assembly Reference
  4. // How to read just a rectangular portion of an image or PDF
  5. var Ocr = new AutoOcr();
  6. var X = 100; //px
  7. var Y = 225;
  8. var Width = 300;
  9. var Height = 125;
  10. var CropArea = new Rectangle(X,Y,Width,Height);
  11. var Result = Ocr.Read(@"C:\path\to\image.png", CropArea );
  12. // This approach works equally well with IronOcr.AdvancedOCR and PDF documents
  13. Console.WriteLine(Result.Text);

Getting Detailed Results Objects from IronOCR

Iron OCR returns an OCR result object for each OCR operation. Generally, developers only use the text property of this object to get the text scanned from the image. However, the OCR results object is much more advanced than this.

In the code sample below, we can see how we may iterate an OCR results object to look at the paragraphs, lines, words and characters of text which have been read during OCR, inspect them for statistical accuracy, and even look at them as images on a page by page basis.

  1. using IronOcr;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Drawing; //Add Assembly Reference
  5. // We can delve deep into OCR results as an object model of
  6. // Pages, Barcodes, Paragraphs, Lines, Words and Characters
  7. var Ocr = new AdvancedOcr()
  8. {
  9. Language = IronOcr.Languages.English.OcrLanguagePack,
  10. ColorSpace = AdvancedOcr.OcrColorSpace.GrayScale,
  11. EnhanceResolution = true,
  12. EnhanceContrast = true,
  13. CleanBackgroundNoise = true,
  14. ColorDepth = 4,
  15. RotateAndStraighten = false,
  16. DetectWhiteTextOnDarkBackgrounds = false,
  17. ReadBarCodes = true,
  18. Strategy = AdvancedOcr.OcrStrategy.Fast,
  19. InputImageType = AdvancedOcr.InputTypes.Document
  20. };
  21. var results = Ocr.Read(@"path\to\document.png");
  22. foreach (var page in results.Pages)
  23. {
  24. // page object
  25. int page_number = page.PageNumber;
  26. String page_text = page.Text;
  27. int page_wordcount = page.WordCount;
  28. List<OcrResult.OcrBarcode> barcodes = page.Barcodes;
  29. System.Drawing.Image page_image = page.Image;
  30. int page_width_px = page.Width;
  31. int page_height_px = page.Height;
  32. foreach (var paragraph in page.Paragraphs)
  33. {
  34. // pages -> paragraphs
  35. int paragraph_number = paragraph.ParagraphNumber;
  36. String paragraph_text = paragraph.Text;
  37. System.Drawing.Image paragraph_image = paragraph.Image;
  38. int paragraph_x_location = paragraph.X;
  39. int paragraph_y_location = paragraph.Y;
  40. int paragraph_width = paragraph.Width;
  41. int paragraph_height = paragraph.Height;
  42. double paragraph_ocr_accuracy = paragraph.Confidence;
  43. string paragraph_font_name = paragraph.FontName;
  44. double paragraph_font_size = paragraph.FontSize;
  45. OcrResult.TextFlow paragrapth_text_direction = paragraph.TextDirection;
  46. double paragrapth_rotation_degrees = paragraph.TextOrientation;
  47. foreach (var line in paragraph.Lines)
  48. {
  49. // pages -> paragraphs -> lines
  50. int line_number = line.LineNumber;
  51. String line_text = line.Text;
  52. System.Drawing.Image line_image = line.Image;
  53. int line_x_location = line.X;
  54. int line_y_location = line.Y;
  55. int line_width = line.Width;
  56. int line_height = line.Height;
  57. double line_ocr_accuracy = line.Confidence;
  58. double line_skew = line.BaselineAngle;
  59. double line_offset = line.BaselineOffset;
  60. foreach (var word in line.Words)
  61. {
  62. // pages -> paragraphs -> lines -> words
  63. int word_number = word.WordNumber;
  64. String word_text = word.Text;
  65. System.Drawing.Image word_image = word.Image;
  66. int word_x_location = word.X;
  67. int word_y_location = word.Y;
  68. int word_width = word.Width;
  69. int word_height = word.Height;
  70. double word_ocr_accuracy = word.Confidence;
  71. String word_font_name = word.FontName;
  72. double word_font_size = word.FontSize;
  73. bool word_is_bold = word.FontIsBold;
  74. bool word_is_fixed_width_font = word.FontIsFixedWidth;
  75. bool word_is_italic = word.FontIsItalic;
  76. bool word_is_serif_font = word.FontIsSerif;
  77. bool word_is_underlined = word.FontIsUnderlined;
  78. foreach (var character in word.Characters)
  79. {
  80. // pages -> paragraphs -> lines -> words -> characters
  81. int character_number = character.CharacterNumber;
  82. String character_text = character.Text;
  83. System.Drawing.Image character_image = character.Image;
  84. int character_x_location = character.X;
  85. int character_y_location = character.Y;
  86. int character_width = character.Width;
  87. int character_height = character.Height;
  88. double character_ocr_accuracy = character.Confidence;
  89. }
  90. }
  91. }
  92. }
  93. }

Performance

Reading (the action of recognizing text from a visual image) is a human art which computers are only just learning to achieve. All OCR is inherently slow, and even on a modern i7 or XEON based server, we can expect OCR to achieve only human reading speeds. This can be a surprise to developers at first, but it’s perfectly normal.

The higher the quality of the input document, the faster the results will come out. It can be counterintuitive that larger documents with higher dpis (of an optimum range from perhaps 250 to 300 dpi) will actually scan faster than smaller image formats.

We will note that wherever possible, Iron OCR will use multithreading to speed up OCR operations on a page by page basis. This is particularly useful when batch processing images or reading multi-page PDF documents.

Learn More

To learn more about OCR in C#, VB, F#, or any other .NET language, please read our community tutorials, which give real world examples of how Iron OCR can be used and may show the nuances of how to get the best out of this library.

A full object reference for .NET developers is also available.

Powered by Frankly
Powered by WorldNow
All content © Copyright 2000 - 2019 WBCB. All Rights Reserved.
For more information on this site, please read our Privacy Policy, and Terms of Service, and Ad Choices.