Take the following steps to create and run a program that shows how to interactively draw zones on an OCR page and how to recognize these zones. Remember, the purpose of the tutorials is to provide you with a quick and easy way to generate an OCR program.
Start Visual Studio 2005 or 2008.
Choose File->New->Project from the menu.
In the New Project dialog box, choose either "Visual C# Projects" or "VB Projects" in the Projects Type List, and choose "Windows Application" or "Windows Forms Application" depending on your Visual Studio version from the Templates List.
Type the project name as "OcrTutorial2" in the Project Name field, and then choose OK. If desired, type a new location for your project or select a directory using the Browse button, and then choose OK.
In the "Solution Explorer" window, right-click on the "References" folder, and select "Add Reference..." from the context menu. In the "Add Reference" dialog box, select the ".NET" tab and browse to LEADTOOLS For .NET "<LEADTOOLS_INSTALLDIR>\Bin\DotNet4\Win32" folder and select the following DLLs:
Note: The Leadtools.Codecs.*.dll references added are for the BMP, JPG, CMP, TIF and FAX image file formats. Add any additional file format codec DLL if required in your application.
Switch to Form1 code view (Right-click Form1 in the solution explorer then select View Code) and add the following lines at the beginning of the file after any using or Imports section if there are any:
using Leadtools;using Leadtools.Codecs;using Leadtools.Drawing;using Leadtools.Controls;using Leadtools.Forms.Common;using Leadtools.Ocr;using Leadtools.Document.Writer;
Imports LeadtoolsImports Leadtools.CodecsImports Leadtools.DrawingImports Leadtools.ControlsImports Leadtools.Forms.CommonImports Leadtools.OcrImports Leadtools.Document.Writer
Add the following private variables to the Form1 class:
// Image viewer instanceprivate ImageViewer _imageViewer;// The OCR engine instanceprivate IOcrEngine _ocrEngine;// The OCR pageprivate IOcrPage _ocrPage;// Recognition results (characters with bounds information)private IOcrZoneCharacters _zoneCharacters;
' Image viewer instancePrivate _imageViewer As ImageViewer' The OCR engine instancePrivate _ocrEngine As IOcrEngine' The OCR pagePrivate _ocrPage As IOcrPage' Recognition results (characters with bounds information)Private _zoneCharacters As IOcrZoneCharacters
Override Form1OnLoad and add the following code:
protected override void OnLoad(EventArgs e){string MY_LICENSE_FILE = @"C:\LEADTOOLS 20\Support\Common\License\leadtools.lic";string MY_DEVELOPER_KEY = System.IO.File.ReadAllText(@"C:\LEADTOOLS 20\Support\Common\License\leadtools.lic.key");RasterSupport.SetLicense(MY_LICENSE_FILE, MY_DEVELOPER_KEY);// Add the image viewer to the form_imageViewer = new ImageViewer();_imageViewer.Dock = DockStyle.Fill;Controls.Add(_imageViewer);_imageViewer.BringToFront();// Show images using their true size_imageViewer.UseDpi = true;// Add ability to pan/zoom using the left mouse buttonImageViewerPanZoomInteractiveMode panZoomMode = new ImageViewerPanZoomInteractiveMode();panZoomMode.MouseButtons = MouseButtons.Left;_imageViewer.InteractiveModes.Add(panZoomMode);// Add a rubber band mode to the right mouse buttonImageViewerRubberBandInteractiveMode rubbBandMode = new ImageViewerRubberBandInteractiveMode();rubbBandMode.MouseButtons = MouseButtons.Right;// Hook to the rubber-band completed event so we can recognize that arearubbBandMode.RubberBandCompleted += rubbBandMode_RubberBandCompleted;_imageViewer.InteractiveModes.Add(rubbBandMode);// Initialize the OCR engine_ocrEngine = OcrEngineManager.CreateEngine(OcrEngineType.LEAD, false);// Startup the engine_ocrEngine.Startup(null, null, null, @"C:\LEADTOOLS 20\Bin\Common\OcrLEADRuntime");// Create the OCR page from an imagestring fileName = @"C:\Users\Public\Documents\LEADTOOLS Images\Ocr1.tif";RasterImage rasterImage = _ocrEngine.RasterCodecsInstance.Load(fileName, 1);_ocrPage = _ocrEngine.CreatePage(rasterImage, OcrImageSharingMode.AutoDispose);// Show this image in the viewer_imageViewer.Image = _ocrPage.GetRasterImage();Text = "Left click and drag to pan, CTRL-Left and drag click to zoom, right click and draw to draw the selection rectangle";// Hook to the post render event of the viewer so we can render the recognition result on the page_imageViewer.PostRender += _imageViewer_PostRender;base.OnLoad(e);}
Protected Overrides Sub OnLoad(e As EventArgs)' Requires a license file that unlocks 1D barcode read functionality.Dim MY_LICENSE_FILE As String = "C:\LEADTOOLS 20\Support\Common\License\leadtools.lic"Dim MY_DEVELOPER_KEY As String = System.IO.File.ReadAllText("C:\LEADTOOLS 20\Support\Common\License\leadtools.lic.key")RasterSupport.SetLicense(MY_LICENSE_FILE, MY_DEVELOPER_KEY)' Add the image viewer to the form_imageViewer = New ImageViewer()_imageViewer.Dock = DockStyle.FillControls.Add(_imageViewer)_imageViewer.BringToFront()' Show images using their true size_imageViewer.UseDpi = True' Add ability to pan/zoom using the left mouse buttonDim panZoomMode As New ImageViewerPanZoomInteractiveMode()panZoomMode.MouseButtons = MouseButtons.Left_imageViewer.InteractiveModes.Add(panZoomMode)' Add a rubber band mode to the right mouse buttonDim rubbBandMode As New ImageViewerRubberBandInteractiveMode()rubbBandMode.MouseButtons = MouseButtons.Right' Hook to the rubber-band completed event so we can recognize that areaAddHandler rubbBandMode.RubberBandCompleted, AddressOf rubbBandMode_RubberBandCompleted_imageViewer.InteractiveModes.Add(rubbBandMode)' Initialize the OCR engine_ocrEngine = OcrEngineManager.CreateEngine(OcrEngineType.LEAD, False)' Startup the engine_ocrEngine.Startup(Nothing, Nothing, Nothing, "C:\LEADTOOLS 20\Bin\Common\OcrLEADRuntime")' Create the OCR page from an imageDim fileName As String = "C:\Users\Public\Documents\LEADTOOLS Images\Ocr1.tif"Dim rasterImage As RasterImage = _ocrEngine.RasterCodecsInstance.Load(fileName, 1)_ocrPage = _ocrEngine.CreatePage(rasterImage, OcrImageSharingMode.AutoDispose)' Show this image in the viewer_imageViewer.Image = _ocrPage.GetRasterImage()Text = "Left click and drag to pan, CTRL-Left and drag click to zoom, right click and draw to draw the selection rectangle"' Hook to the post render event of the viewer so we can render the recognition result on the pageAddHandler _imageViewer.PostRender, AddressOf _imageViewer_PostRenderMyBase.OnLoad(e)End Sub
Override Form1OnFormClosed and add the following code:
protected override void OnFormClosed(FormClosedEventArgs e){// Destroy the page_ocrPage.Dispose();// And the engine_ocrEngine.Dispose();base.OnFormClosed(e);}
Protected Overrides Sub OnFormClosed(e As FormClosedEventArgs)' Destroy the page_ocrPage.Dispose()' And the engine_ocrEngine.Dispose()MyBase.OnFormClosed(e)End Sub
Add the following code to handle the rubber band completed event. Draw the zone and recognize it:
private void rubbBandMode_RubberBandCompleted(object sender, ImageViewerRubberBandEventArgs e){// Use has drawn a selection rectangle// Remove current zone from the page_ocrPage.Zones.Clear();// Add the new zone. The points from rubber band is in control coordinates, need to convert them to imageLeadRect bounds = LeadRect.FromLTRB(e.Points[0].X, e.Points[0].Y, e.Points[1].X, e.Points[1].Y);bounds = _imageViewer.ConvertRect(null, ImageViewerCoordinateType.Control, ImageViewerCoordinateType.Image, bounds);// Add a new text zone from these coordinatesOcrZone ocrZone = new OcrZone();ocrZone.ZoneType = OcrZoneType.Text;ocrZone.Bounds = bounds;_ocrPage.Zones.Add(ocrZone);// Recognize the page to get the text of the zone_ocrPage.Recognize(null);// Get the recognized charactersIOcrPageCharacters pageCharacters = _ocrPage.GetRecognizedCharacters();_zoneCharacters = pageCharacters[0];// Refresh the viewer so we render the character bounds and positions_imageViewer.Refresh();// Show the result in a message boxstring text = _ocrPage.GetText(0);if (string.IsNullOrEmpty(text))text = "[Nothing found]";MessageBox.Show(this, text);}
Private Sub rubbBandMode_RubberBandCompleted(sender As Object, e As ImageViewerRubberBandEventArgs)' Use has drawn a selection rectangle' Remove the current zone from the page_ocrPage.Zones.Clear()' Add the new zone. The points from rubber band is in control coordinates, need to convert them to imageDim bounds As LeadRect = LeadRect.FromLTRB(e.Points(0).X, e.Points(0).Y, e.Points(1).X, e.Points(1).Y)bounds = _imageViewer.ConvertRect(Nothing, ImageViewerCoordinateType.Control, ImageViewerCoordinateType.Image, bounds)' Add a new text zone from these coordinatesDim ocrZone As New OcrZone()ocrZone.ZoneType = OcrZoneType.TextocrZone.Bounds = bounds_ocrPage.Zones.Add(ocrZone)' Recognize the page to get the text of the zone_ocrPage.Recognize(Nothing)' Get the recognized charactersDim pageCharacters As IOcrPageCharacters = _ocrPage.GetRecognizedCharacters()_zoneCharacters = pageCharacters(0)' Refresh the viewer so we render the character bounds and positions_imageViewer.Refresh()' Show the result in a message boxDim text As String = _ocrPage.GetText(0)If String.IsNullOrEmpty(text) Thentext = "[Nothing found]"End IfMessageBox.Show(Me, text)End Sub
Finally (optional) add the following code to handle the image viewer post render event. Render the characters:
private void _imageViewer_PostRender(object sender, ImageViewerRenderEventArgs e){// Draw the recognition results (if we have any)if (_zoneCharacters == null)return;Graphics graphics = e.PaintEventArgs.Graphics;using (Brush characterBrush = new SolidBrush(Color.FromArgb(128, Color.Black))){foreach (OcrCharacter character in _zoneCharacters){// Get the character boundaryLeadRect bounds = character.Bounds;// Convert the bound to what we see in the viewer// Note that this demo does not have rotation; otherwise, you need to use the four corner pointsbounds = _imageViewer.ConvertRect(null, ImageViewerCoordinateType.Image, ImageViewerCoordinateType.Control, bounds);// Highlight the character area on the pagegraphics.FillRectangle(characterBrush, bounds.X, bounds.Y, bounds.Width, bounds.Height);graphics.DrawRectangle(Pens.Black, bounds.X, bounds.Y, bounds.Width - 1, bounds.Height - 1);// Finally draw the character code it selfgraphics.DrawString(new string(new char[] { character.Code }), this.Font, Brushes.White, bounds.X, bounds.Y);}}}
Private Sub _imageViewer_PostRender(sender As Object, e As ImageViewerRenderEventArgs)' Draw the recognition results (if we have any)If IsNothing(_zoneCharacters) Then ReturnDim graphics As Graphics = e.PaintEventArgs.GraphicsUsing characterBrush As New SolidBrush(Color.FromArgb(128, Color.Black))For Each character As OcrCharacter In _zoneCharacters' Get the character boundaryDim bounds As LeadRect = character.Bounds' Convert the bound to what we see in the viewer' Note that this demo does not have rotation; otherwise, you need to use the four corner pointsbounds = _imageViewer.ConvertRect(Nothing, ImageViewerCoordinateType.Image, ImageViewerCoordinateType.Control, bounds)' Highlight the character area on the pagegraphics.FillRectangle(characterBrush, bounds.X, bounds.Y, bounds.Width, bounds.Height)graphics.DrawRectangle(Pens.Black, bounds.X, bounds.Y, bounds.Width - 1, bounds.Height - 1)' Finally draw the character code it selfgraphics.DrawString(New String(New Char() {character.Code}), Me.Font, Brushes.White, bounds.X, bounds.Y)NextEnd UsingEnd Sub
Save this project to use for testing other code samples.
OCR Tutorial - Working with Pages
OCR Tutorial - Recognizing Pages
OCR Tutorial - Adding and Painting Zones
OCR Tutorial - Scanning to Searchable PDF
Getting Started (Guide to Example Programs)
Programming with LEADTOOLS .NET OCR
An Overview of OCR Recognition Modules
Creating an OCR Engine Instance
Starting and Shutting Down the OCR Engine
Multi-Threading with LEADTOOLS OCR
OCR Spell Language Dictionaries
Using OMR in LEADTOOLS .NET OCR