CogOCRMaxTool ClassCognex VisionPro
The CogOCRMaxTool (Optical Character Recognition) reads a line of text in an image. The CogOCRMaxTool performs three primary operations: segmentation, classification, and fielding. Segmentation occurs first and uses thresholding techniques to identify which areas in the image appear to contain lines of text. Classification occurs second and is responsible for "reading" any text found by the segmenter. It does this by comparing the images of segmented characters to previously acquired images of known characters in a font. Fielding is the third and final stage of OCRMax. Fielding is an optional step which uses prior information about the text being read to improve or correct the classification results. For more details see the documentation for CogOCRMaxSegmenter, CogOCRMaxClassifier, CogOCRMaxFielding, as well as the OCRMax Theory Guide.
Inheritance Hierarchy

System Object
  System MarshalByRefObject
    System.ComponentModel Component
      Cognex.VisionPro.Implementation CogComponentBase
        Cognex.VisionPro.Implementation CogSerializableComponentBase
          Cognex.VisionPro.Implementation CogSerializableChangedEventComponentBase
            Cognex.VisionPro.Implementation CogToolBase
              Cognex.VisionPro.OCRMax CogOCRMaxTool

Namespace: Cognex.VisionPro.OCRMax
Assembly: Cognex.VisionPro.OCRMax (in Cognex.VisionPro.OCRMax.dll) Version: 65.1.0.0
Syntax

[SerializableAttribute]
public class CogOCRMaxTool : CogToolBase

The CogOCRMaxTool type exposes the following members.

Constructors

  NameDescription
Public methodCogOCRMaxTool 
Construct a default CogOCRMaxTool object.
Public methodCogOCRMaxTool(CogOCRMaxTool)
Constructs a deep copy of the supplied CogOCRMaxTool object.
Protected methodCogOCRMaxTool(SerializationInfo, StreamingContext)
Serialization constructor for CogOCRMaxTool.
Top
Methods

  NameDescription
Public methodAutoCorrect

For use with OCRMAXTool Tuning

AutoCorrect() makes educated guesses at a "correct" tune record by trying different OCRMax tool parameters and looking for parameters that produce a result string which matches the expected result string contained in the input record.

A "correct" record contains an image, a region, and the correct string of character codes in the image. A "correct" record also contains the mark and cell rects which identify the location of each character in the image.

Public methodAutoTune

For use with OCRMaxTool Tuning

Tunes the OCRMax Tool. Tuning searches for parameters that produce a line result which matches correctRecord which is known to be correct.

AutoTune takes into account previously AutoTuned records and current tool parameters when tuning.

Protected methodCheckRunConditions
Check for run conditions including data binding.
(Inherited from CogToolBase.)
Protected methodCheckRunConditionsNoThrow
Check for run conditions including data binding, returning an exception for the first problem encountered.
(Inherited from CogToolBase.)
Public methodClone
Returns a deep copy of this class instance.
(Overrides CogToolBase Clone .)
Public methodCreateCurrentRecord
Creates a new set of records that represents the tool's current state.
(Inherited from CogToolBase.)
Public methodCreateLastRunRecord
Creates a new set of records that represents the tool's last-run state.
(Inherited from CogToolBase.)
Public methodCreateObjRef
Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
(Inherited from MarshalByRefObject.)
Public methodDispose 
Releases all resources used by the Component.
(Inherited from Component.)
Protected methodDispose(Boolean)
Releases the unmanaged resources used by the Component and optionally releases the managed resources.
(Inherited from Component.)
Public methodEquals
Determines whether the specified Object is equal to the current Object.
(Inherited from Object.)
Public methodExecuteOperators
Cognex Internal Use Only
Protected methodFinalize
Releases unmanaged resources and performs other cleanup operations before the Component is reclaimed by garbage collection.
(Inherited from Component.)
Protected methodGetAttributes
Implements the corresponding member of the ICustomTypeDescriptor interface. May be overridden in derived classes to provide custom type information.
(Inherited from CogComponentBase.)
Protected methodGetClassName
Implements the corresponding member of the ICustomTypeDescriptor interface. May be overridden in derived classes to provide custom type information.
(Inherited from CogComponentBase.)
Protected methodGetComponentName
Implements the corresponding member of the ICustomTypeDescriptor interface. May be overridden in derived classes to provide custom type information.
(Inherited from CogComponentBase.)
Protected methodGetConverter
Implements the corresponding member of the ICustomTypeDescriptor interface. May be overridden in derived classes to provide custom type information.
(Inherited from CogComponentBase.)
Protected methodGetDefaultEvent
Implements the corresponding member of the ICustomTypeDescriptor interface. May be overridden in derived classes to provide custom type information.
(Inherited from CogComponentBase.)
Protected methodGetDefaultProperty
Implements the corresponding member of the ICustomTypeDescriptor interface. May be overridden in derived classes to provide custom type information.
(Inherited from CogComponentBase.)
Protected methodGetEditor
Implements the corresponding member of the ICustomTypeDescriptor interface. May be overridden in derived classes to provide custom type information.
(Inherited from CogComponentBase.)
Protected methodGetEvents 
Implements the corresponding member of the ICustomTypeDescriptor interface. May be overridden in derived classes to provide custom type information.
(Inherited from CogComponentBase.)
Protected methodGetEvents( Attribute )
Implements the corresponding member of the ICustomTypeDescriptor interface. May be overridden in derived classes to provide custom type information.
(Inherited from CogComponentBase.)
Public methodGetHashCode
Serves as a hash function for a particular type.
(Inherited from Object.)
Public methodGetLifetimeService
Retrieves the current lifetime service object that controls the lifetime policy for this instance.
(Inherited from MarshalByRefObject.)
Protected methodGetObjectData
Implements the GetObjectData method of the ISerializable interface.
(Inherited from CogSerializableComponentBase.)
Protected methodGetProperties 
Implements the corresponding member of the ICustomTypeDescriptor interface. May be overridden in derived classes to provide custom type information.
(Inherited from CogComponentBase.)
Protected methodGetProperties( Attribute )
Implements the corresponding member of the ICustomTypeDescriptor interface. May be overridden in derived classes to provide custom type information.
(Inherited from CogComponentBase.)
Protected methodGetPropertyOwner
Implements the corresponding member of the ICustomTypeDescriptor interface. May be overridden in derived classes to provide custom type information.
(Inherited from CogComponentBase.)
Protected methodGetService
Returns an object that represents a service provided by the Component or by its Container.
(Inherited from Component.)
Public methodGetType
Gets the Type of the current instance.
(Inherited from Object.)
Public methodInitializeLifetimeService
Obtains a lifetime service object to control the lifetime policy for this instance.
(Inherited from MarshalByRefObject.)
Protected methodInternalCreateCurrentRecord
Implementation of the tool's current record generation.
(Overrides CogToolBase InternalCreateCurrentRecord(ICogRecord, Int32).)
Protected methodInternalCreateLastRunRecord
Implementation of the tool's last run record generation.
(Overrides CogToolBase InternalCreateLastRunRecord(ICogRecord, Int32, Int32).)
Protected methodInternalRun
Implementation of the tool's run algorithm.
(Overrides CogToolBase InternalRun(String ).)
Protected methodMemberwiseClone 
Creates a shallow copy of the current Object.
(Inherited from Object.)
Protected methodMemberwiseClone(Boolean)
Creates a shallow copy of the current MarshalByRefObject object.
(Inherited from MarshalByRefObject.)
Protected methodOnChanged(Int64)
This method should be called internally whenever the object's state may have changed.
(Inherited from CogSerializableChangedEventComponentBase.)
Protected methodOnChanged(CogChangedEventArgs)
This method may be called internally whenever a derived object's state may have changed and the derived object expresses this change via a derived CogChangedEventArgs class.
(Inherited from CogSerializableChangedEventComponentBase.)
Public methodOnDeserialization
Called to complete the deserialziation of the OCRMaxTool
(Overrides CogToolBase OnDeserialization(Object).)
Protected methodOnFontOrParamsChanged
Protected methodOnRan
Raises the Ran event.
(Inherited from CogToolBase.)
Protected methodOnRunning
Raises the Running event.
(Inherited from CogToolBase.)
Public methodResumeAndRaiseChangedEvent
Re-enables raising of the Changed event after SuspendChangedEvent has been called, and raises the Changed event if the ChangedEventSuspended count is reduced to zero and any changes were made while events were suspended. Must be called once for each call to SuspendChangedEvent.
(Inherited from CogSerializableChangedEventComponentBase.)
Public methodRun
Runs the tool using the current parameter settings.
(Overrides CogToolBase Run .)
Protected methodSetRunStatus
Cognex Internal use only.
(Inherited from CogToolBase.)
Protected methodStartTracking
Starts listening to events on sub objects
Public methodSuspendChangedEvent
Temporarily suspends the raising of the Changed event. May be called more than once, and a corresponding call to ResumeAndRaiseChangedEvent must be made for each call to SuspendChangedEvent.
(Inherited from CogSerializableChangedEventComponentBase.)
Public methodToString
Returns a String containing the name of the Component, if any. This method should not be overridden.
(Inherited from Component.)
Public methodTune
Tunes the OCRMax Tool based on the collection of Tune Records contained in the TuneData property and the current tool parameters.

Tuning searches for OCRMax parameters that produce line results that match the tune records in TuneData (which are known to be correct).

Public methodUpdateToolFromCachedMembers
COGNEX INTERNAL USE ONLY
Top
Fields

  NameDescription
Protected fieldCurrentRecordEnable_
Gets or sets the flags specifying the records to include based on the tool's current state. The derived class exposes this as a strongly- typed enum property.
(Inherited from CogToolBase.)
Protected fieldLastRunLastRunRecordDiagEnable_
Gets or sets the flags specifying the records to create during the next invocation of the Run method.
(Inherited from CogToolBase.)
Protected fieldLastRunRecordDiagEnable_
Gets or sets the flags specifying the diagnostics records to include based on the tool's last-run state. The derived class exposes this as a strongly-typed enum property.
(Inherited from CogToolBase.)
Protected fieldLastRunRecordEnable_
Gets or sets the flags specifying the records to include based on the tool's last-run state. The derived class exposes this as a strongly- typed enum property.
(Inherited from CogToolBase.)
Protected fieldProcessingTimeAdjustment_
Gets or sets the amount to offset reported tool processing time.
(Inherited from CogToolBase.)
Public fieldStatic memberSfClassifier
This bit will be set in the EventArgs of a Changed event every time the value returned by Classifier may have changed.
Public fieldStatic memberSfClassifierRunParams
This bit will be set in the EventArgs of a Changed event every time the value returned by ClassifierRunParams may have changed.
Public fieldStatic memberSfCurrentRecordEnable
This bit will be set in the EventArgs of a Changed event every time the value returned by CurrentRecordEnable may have changed.
Public fieldStatic memberSfFielding
This bit will be set in the EventArgs of a Changed event every time the value returned by Fielding may have changed.
Public fieldStatic memberSfFieldingEnabled
This bit will be set in the EventArgs of a Changed event every time the value returned by FieldingEnabled may have changed.
Public fieldStatic memberSfInputImage
This bit will be set in the EventArgs of a Changed event every time the value returned by InputImage may have changed.
Public fieldStatic memberSfLastRunRecordDiagEnable
This bit will be set in the EventArgs of a Changed event every time the value returned by LastRunRecordDiagEnable may have changed.
Public fieldStatic memberSfLastRunRecordEnable
This bit will be set in the EventArgs of a Changed event every time the value returned by LastRunRecordEnable may have changed.
Public fieldStatic memberSfLineResult
This bit will be set in the EventArgs of a Changed event every time the value returned by LineResult may have changed.
Protected fieldStatic memberSfNextSf
Public fieldStatic memberSfRegion
This bit will be set in the EventArgs of a Changed event every time the value returned by Region may have changed.
Public fieldStatic memberSfSegmenter
This bit will be set in the EventArgs of a Changed event every time the value returned by Segmenter may have changed.
Public fieldStatic memberSfSwapCharSet
This bit will be set in the EventArgs of a Changed event every time the value returned by SwapCharSet may have changed.
Public fieldStatic memberSfTimeout
This bit will be set in the EventArgs of a Changed event every time the value returned by Timeout may have changed.
Public fieldStatic memberSfTimeoutEnabled
This bit will be set in the EventArgs of a Changed event every time the value returned by TimeoutEnabled may have changed.
Public fieldStatic memberSfTuneData
This bit will be set in the EventArgs of a Changed event every time the value returned by TuneData may have changed.
Public fieldStatic memberSfTuneParams
This bit will be set in the EventArgs of a Changed event every time the value returned by TuneParams may have changed.
Public fieldStatic memberSfUnknownCharacterMarker
This bit will be set in the EventArgs of a Changed event every time the value returned by UnknownCharacterMarker may have changed.
Top
Properties

  NameDescription
Protected propertyCanRaiseEvents
Gets a value indicating whether the component can raise an event.
(Inherited from Component.)
Public propertyChangedEventSuspended
If nonzero, indicates that the raising of the Changed event has been suspended. This value is incremented when SuspendChangedEvent is called and decremented when ResumeAndRaiseChangedEvent is called.
(Inherited from CogSerializableChangedEventComponentBase.)
Public propertyClassifier
Classification is the second main step in performing OCRMax. Classification takes in a CogOCRMaxChar produced by the segmenter and returns the best matching character, the score of that best matching character, and the confidence of that best matching character. By classifying all of the segmented characters in a line of text, the classifier determines the result string for the whole line. See the OCRMax Theory Guide for more information.
Public propertyClassifierRunParams
Parameters which control how the classification step is run.
Public propertyContainer
Gets the IContainer that contains the Component.
(Inherited from Component.)
Public propertyCurrentRecordEnable
Enable creation of records by bitwise ORing the appropriate CogOCRMaxCurrentRecordConstants.
Public propertyDataBindings
Gets the data bindings for the tool.
(Inherited from CogToolBase.)
Protected propertyDesignMode
Gets a value that indicates whether the Component is currently in design mode.
(Inherited from Component.)
Protected propertyEvents
Gets the list of event handlers that are attached to this Component.
(Inherited from Component.)
Public propertyFailOnInvalidDataBinding
Specifies that the Run method is to fail if executed while one or more data bindings are invalid.
(Inherited from CogToolBase.)
Public propertyFielding
The Fielding operator. Fielding can be used to improve the classifier results based on prior knowledge of the string being read.
Public propertyFieldingEnabled
Enable or disable the fielding operation
Public propertyHasChanged (Inherited from CogSerializableChangedEventComponentBase.)
Public propertyInputImage
Gets or sets the image on which to run OCRMax.
Public propertyLastRunRecordDiagEnable
Enable creation of records by bitwise ORing the appropriate CogOCRMaxLastRunRecordDiagConstants.
Public propertyLastRunRecordEnable
Enable creation of records by bitwise ORing the appropriate CogOCRMaxLastRunRecordConstants.
Public propertyLineResult
Gets the result of running the OCRMax tool.
Public propertyName
Gets or sets a user-supplied name for the tool.
(Inherited from CogToolBase.)
Public propertyRegion
Gets or sets the optional region which determines where the tool should look for text.
Public propertyRunStatus
Gets general information about the last call to the tool's Run function. Note that serious errors that occur within the tool's Run method may only be detected by examining the RunStatus after calling Run. It is the user's responsibility to examine the tool's RunStatus after calling Run.
(Inherited from CogToolBase.)
Public propertySegmenter
Character Segmentation is the first step performed by the CogOCRMaxTool. Segmentation takes an image as input and extracts a set of segmented character images (CogOCRMaxChar(s)). For example, if an image contains the line of text "ABCD", then character segmentation produces four separate images (CogOCRMaxChar(s)), each of which is an image of a single character. Character segmentation does not know anything about actually determining which letter a character image corresponds to; in the above example, it has no way of knowing that the first image corresponds to the letter "A". See the OCRMax Theory Guide for more information.
Public propertySite
Gets or sets the ISite of the Component.
(Inherited from Component.)
Public propertyStateFlags
Returns the complete set of state flags supported on this object. The flags may be indexed by name as shown in the following C# code snippet: if (changedObject.StateFlags["Color"] & eventArgs.StateFlags) { ... }
(Inherited from CogSerializableChangedEventComponentBase.)
Public propertySwapCharSet
The set of characters which have been predetermined to be "swappable" (They appear similar and are hard to distinguish, e.g. '0' (zero) and 'O' (capital oh)).
Public propertyTimeout
Gets or sets the timeout value used by this tool in milliseconds.
Public propertyTimeoutEnabled
Enables the timeout mechanism.
Public propertyTuneData
A collection of CogOCRMaxTuneRecords used to tune the CogOCRMaxTool.
Public propertyTuneParams
Parameters which control the behavior of OCRMax AutoCorrect(), AutoTune(), and Tune() functions.
Public propertyUnknownCharacterMarker
A string which will be used to identify the unknown character code in result strings generated by this tool.
Public propertyUserData
Gets a CogDictionary object that can be used to store application-specific information.
(Inherited from CogToolBase.)
Top
Events

  NameDescription
Public eventChanged
This event is raised when one or more parts of the object's state may have changed.
(Inherited from CogSerializableChangedEventComponentBase.)
Public eventDisposed
Occurs when the component is disposed by a call to the Dispose  method.
(Inherited from Component.)
Public eventRan
Event that is raised at the end of the tool's Run method.
(Inherited from CogToolBase.)
Public eventRunning
Event that is raised at the start of the tool's Run method.
(Inherited from CogToolBase.)
Top
Examples

Imports System.Drawing
Imports Cognex.VisionPro
Imports Cognex.VisionPro.OCRMax

Module CogOCRMaxExample

  Sub Main()

    Dim OCRMaxTool As New CogOCRMaxTool()

    ' Load an image containing the text to read.
    Dim bmp As New Bitmap(System.Environment.GetEnvironmentVariable("VPRO_ROOT") & "\images\alphanumbers.bmp")

    Dim image As New CogImage8Grey(bmp)

    ' Create a rectangle that surrounds the text 
    ' "ABCDEFGHIJKLMNOPQRSTUVWXYZ" in the image.
    Dim rect As New CogRectangleAffine()
    rect.SetOriginLengthsRotationSkew(340, 748, 1010, 93, 0, 0)

    ' Set the image and search region of the tool.
    OCRMaxTool.InputImage = image
    OCRMaxTool.Region = rect

    ' Segment the characters in the image.
    OCRMaxTool.Run()

    If OCRMaxTool.RunStatus.Result <> CogToolResultConstants.Accept OrElse OCRMaxTool.LineResult.Count <> 26 Then
      Console.WriteLine("Initial segmentation failed. " + OCRMaxTool.RunStatus.Message)
      Return
    End If

    ' Get an array of Unicode UTF-32 character codes
    ' which represent a string of all the letters in the 
    ' english alphabet.
    Dim alphabetString As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    Dim alphabetCharCodes As Integer() = CogOCRMaxChar.GetCharCodesFromString(alphabetString)

    ' Label each segmented character with the correct
    ' character code and add it to the classifier's font.
    For i As Integer = 0 To OCRMaxTool.LineResult.Count - 1
      Dim c As CogOCRMaxChar = OCRMaxTool.LineResult(i).GetCharacter()
      c.CharacterCode = alphabetCharCodes(i)
      OCRMaxTool.Classifier.Font.Add(c)
    Next

    Try
      ' Train the classifier based on the font.
      OCRMaxTool.Classifier.Train()
    Catch ex As Exception
      Console.WriteLine("Failed to train classifier characters: " & ex.Message)
    End Try

    ' Run the (now trained) tool again.
    OCRMaxTool.Run()

    If OCRMaxTool.RunStatus.Result <> CogToolResultConstants.Accept Then
      Console.WriteLine("OCRMax tool failed: " + OCRMaxTool.RunStatus.Message)
      Return
    End If

    If OCRMaxTool.LineResult.Status <> CogOCRMaxLineResultStatusConstants.Read Then
      Console.WriteLine("OCRMax tool failed to read the line of text.")
      Return
    End If

    ' Print out the read string.
    Console.WriteLine("OCRMax Tool read the string: " + OCRMaxTool.LineResult.ResultString)
  End Sub
End Module
using System;
using System.Drawing;
using Cognex.VisionPro;
using Cognex.VisionPro.OCRMax;

class CogOCRMaxExample
{
  static void Main()
  {
    CogOCRMaxTool OCRMaxTool = new CogOCRMaxTool();

    // Load an image containing the text to read.
    Bitmap bmp = new Bitmap(
      System.Environment.GetEnvironmentVariable("VPRO_ROOT") +
      @"\images\alphanumbers.bmp");

    CogImage8Grey image = new CogImage8Grey(bmp);

    // Create a rectangle that surrounds the text  
    // "ABCDEFGHIJKLMNOPQRSTUVWXYZ" in the image.
    CogRectangleAffine rect = new CogRectangleAffine();
    rect.SetOriginLengthsRotationSkew(340, 748, 1010, 93, 0, 0);

    // Set the image and search region of the tool.
    OCRMaxTool.InputImage = image;
    OCRMaxTool.Region = rect;

    // Segment the characters in the image.
    OCRMaxTool.Run();

    if (OCRMaxTool.RunStatus.Result != CogToolResultConstants.Accept ||
        OCRMaxTool.LineResult.Count != 26)
    {
      Console.WriteLine(
        "Initial segmentation failed. " + OCRMaxTool.RunStatus.Message);
      return;
    }

    // Get an array of Unicode UTF-32 character codes 
    // which represent a string of all the letters in the  
    // english alphabet. 
    string alphabetString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    int[] alphabetCharCodes =
      CogOCRMaxChar.GetCharCodesFromString(alphabetString);

    // Label each segmented character with the correct 
    // character code and add it to the classifier's font. 
    for (int i = 0; i < OCRMaxTool.LineResult.Count; i++)
    {
      CogOCRMaxChar c = OCRMaxTool.LineResult[i].GetCharacter();
      c.CharacterCode = alphabetCharCodes[i];
      OCRMaxTool.Classifier.Font.Add(c);
    }

    try
    {
      // Train the classifier based on the font.
      OCRMaxTool.Classifier.Train();
    }
    catch (Exception ex)
    {
      Console.WriteLine(
        "Failed to train classifier characters: " + ex.Message);
    }

    // Run the (now trained) tool again.
    OCRMaxTool.Run();

    if (OCRMaxTool.RunStatus.Result != CogToolResultConstants.Accept)
    {
      Console.WriteLine("OCRMax tool failed: " + OCRMaxTool.RunStatus.Message);
      return;
    }

    if (OCRMaxTool.LineResult.Status != CogOCRMaxLineResultStatusConstants.Read)
    {
      Console.WriteLine("OCRMax tool failed to read the line of text.");
      return;
    }

    // Print out the read string.
    Console.WriteLine("OCRMax Tool read the string: " + OCRMaxTool.LineResult.ResultString);
  }
}
See Also