Table of Contents

Class TrOCR<T>

Namespace
AiDotNet.Document.OCR.TextRecognition
Assembly
AiDotNet.dll

TrOCR (Transformer-based OCR) for text recognition from cropped images.

public class TrOCR<T> : DocumentNeuralNetworkBase<T>, INeuralNetworkModel<T>, INeuralNetwork<T>, IInterpretableModel<T>, IInputGradientComputable<T>, IDisposable, ITextRecognizer<T>, IDocumentModel<T>, IFullModel<T, Tensor<T>, Tensor<T>>, IModel<Tensor<T>, Tensor<T>, ModelMetadata<T>>, IModelSerializer, ICheckpointableModel, IParameterizable<T, Tensor<T>, Tensor<T>>, IFeatureAware, IFeatureImportance<T>, ICloneable<IFullModel<T, Tensor<T>, Tensor<T>>>, IGradientComputable<T, Tensor<T>, Tensor<T>>, IJitCompilable<T>

Type Parameters

T

The numeric type used for calculations.

Inheritance
TrOCR<T>
Implements
IFullModel<T, Tensor<T>, Tensor<T>>
IModel<Tensor<T>, Tensor<T>, ModelMetadata<T>>
IParameterizable<T, Tensor<T>, Tensor<T>>
ICloneable<IFullModel<T, Tensor<T>, Tensor<T>>>
IGradientComputable<T, Tensor<T>, Tensor<T>>
Inherited Members
Extension Methods

Remarks

TrOCR is an end-to-end text recognition model that uses a Vision Transformer (ViT) encoder and a Transformer decoder (similar to BART/GPT-2) for sequence generation.

For Beginners: TrOCR reads text from images. Given a cropped image of text (like a single word or line), it outputs the actual characters. It works by: 1. The encoder (ViT) analyzes the image and creates feature representations 2. The decoder generates text one character at a time, using attention to focus on relevant image regions

Example usage:

var trocr = new TrOCR<float>(architecture);
var result = trocr.RecognizeText(croppedTextImage);
Console.WriteLine($"Text: {result.Text}, Confidence: {result.ConfidenceValue}");

Reference: "TrOCR: Transformer-based Optical Character Recognition with Pre-trained Models" (AAAI 2022) https://arxiv.org/abs/2109.10282

Constructors

TrOCR(NeuralNetworkArchitecture<T>, ITokenizer?, int, int, int, int, int, int, int, int, int, int, int, IOptimizer<T, Tensor<T>, Tensor<T>>?, ILossFunction<T>?)

Creates a TrOCR model using native layers for training and inference.

public TrOCR(NeuralNetworkArchitecture<T> architecture, ITokenizer? tokenizer = null, int imageHeight = 384, int imageWidth = 384, int maxSequenceLength = 128, int encoderHiddenDim = 768, int decoderHiddenDim = 768, int numEncoderLayers = 12, int numDecoderLayers = 6, int numEncoderHeads = 12, int numDecoderHeads = 12, int patchSize = 16, int vocabSize = 50265, IOptimizer<T, Tensor<T>, Tensor<T>>? optimizer = null, ILossFunction<T>? lossFunction = null)

Parameters

architecture NeuralNetworkArchitecture<T>

The neural network architecture.

tokenizer ITokenizer

Tokenizer for text generation (optional).

imageHeight int

Input image height (default: 384 for TrOCR-base).

imageWidth int

Input image width (default: 384).

maxSequenceLength int

Maximum output sequence length (default: 128).

encoderHiddenDim int

Encoder hidden dimension (default: 768 for base).

decoderHiddenDim int

Decoder hidden dimension (default: 768 for base).

numEncoderLayers int

Number of encoder layers (default: 12).

numDecoderLayers int

Number of decoder layers (default: 6).

numEncoderHeads int

Number of encoder attention heads (default: 12).

numDecoderHeads int

Number of decoder attention heads (default: 12).

patchSize int

ViT patch size (default: 16).

vocabSize int

Vocabulary size (default: 50265 for RoBERTa tokenizer).

optimizer IOptimizer<T, Tensor<T>, Tensor<T>>

Optimizer for training (optional).

lossFunction ILossFunction<T>

Loss function (optional).

Remarks

Default Configuration (TrOCR-Base from AAAI 2022 paper): - Encoder: ViT-Base (12 layers, 768 hidden, 12 heads) - Decoder: 6 layers, 768 hidden, 12 heads - Image size: 384×384 - Patch size: 16

TrOCR(NeuralNetworkArchitecture<T>, string, string, ITokenizer, int, int, int, int, int, int, int, int, int, int, int, IOptimizer<T, Tensor<T>, Tensor<T>>?, ILossFunction<T>?)

Creates a TrOCR model using pre-trained ONNX models for inference.

public TrOCR(NeuralNetworkArchitecture<T> architecture, string encoderPath, string decoderPath, ITokenizer tokenizer, int imageHeight = 384, int imageWidth = 384, int maxSequenceLength = 128, int encoderHiddenDim = 768, int decoderHiddenDim = 768, int numEncoderLayers = 12, int numDecoderLayers = 6, int numEncoderHeads = 12, int numDecoderHeads = 12, int patchSize = 16, int vocabSize = 50265, IOptimizer<T, Tensor<T>, Tensor<T>>? optimizer = null, ILossFunction<T>? lossFunction = null)

Parameters

architecture NeuralNetworkArchitecture<T>

The neural network architecture.

encoderPath string

Path to the ONNX encoder model.

decoderPath string

Path to the ONNX decoder model.

tokenizer ITokenizer

Tokenizer for text generation.

imageHeight int

Input image height (default: 384 for TrOCR-base).

imageWidth int

Input image width (default: 384).

maxSequenceLength int

Maximum output sequence length (default: 128).

encoderHiddenDim int

Encoder hidden dimension (default: 768 for base).

decoderHiddenDim int

Decoder hidden dimension (default: 768 for base).

numEncoderLayers int

Number of encoder layers (default: 12).

numDecoderLayers int

Number of decoder layers (default: 6).

numEncoderHeads int

Number of encoder attention heads (default: 12).

numDecoderHeads int

Number of decoder attention heads (default: 12).

patchSize int

ViT patch size (default: 16).

vocabSize int

Vocabulary size (default: 50265 for RoBERTa tokenizer).

optimizer IOptimizer<T, Tensor<T>, Tensor<T>>

Optimizer for training (optional).

lossFunction ILossFunction<T>

Loss function (optional).

Exceptions

ArgumentNullException

Thrown if paths or tokenizer is null.

FileNotFoundException

Thrown if ONNX model files don't exist.

Properties

ExpectedImageSize

Gets the expected input image size (assumes square images).

public int ExpectedImageSize { get; }

Property Value

int

Remarks

Common values: 224 (ViT base), 384, 448, 512, 768, 1024. Input images will be resized to [ImageSize x ImageSize] before processing.

RequiresOCR

Gets whether this model requires OCR preprocessing.

public override bool RequiresOCR { get; }

Property Value

bool

Remarks

Layout-aware models (LayoutLM, etc.) require OCR to provide text and bounding boxes. OCR-free models (Donut, Pix2Struct) process raw pixels directly.

SupportedCharacters

Gets the supported character set (alphabet) for this recognizer.

public string SupportedCharacters { get; }

Property Value

string

SupportedDocumentTypes

Gets the supported document types for this model.

public override DocumentType SupportedDocumentTypes { get; }

Property Value

DocumentType

SupportsAttentionVisualization

Gets whether this recognizer supports attention visualization.

public bool SupportsAttentionVisualization { get; }

Property Value

bool

Methods

ApplyDefaultPostprocessing(Tensor<T>)

Applies TrOCR's industry-standard postprocessing: pass-through (encoder-decoder outputs are already final).

protected override Tensor<T> ApplyDefaultPostprocessing(Tensor<T> modelOutput)

Parameters

modelOutput Tensor<T>

Returns

Tensor<T>

ApplyDefaultPreprocessing(Tensor<T>)

Applies TrOCR's industry-standard preprocessing: normalize to [-1, 1].

protected override Tensor<T> ApplyDefaultPreprocessing(Tensor<T> rawImage)

Parameters

rawImage Tensor<T>

Returns

Tensor<T>

Remarks

TrOCR (Transformer-based OCR) uses mean=0.5, std=0.5 normalization (same as DeiT/BEiT) from Microsoft paper.

CreateNewInstance()

Creates a new instance of the same type as this neural network.

protected override IFullModel<T, Tensor<T>, Tensor<T>> CreateNewInstance()

Returns

IFullModel<T, Tensor<T>, Tensor<T>>

A new instance of the same neural network type.

Remarks

For Beginners: This creates a blank version of the same type of neural network.

It's used internally by methods like DeepCopy and Clone to create the right type of network before copying the data into it.

DeserializeNetworkSpecificData(BinaryReader)

Deserializes network-specific data that was not covered by the general deserialization process.

protected override void DeserializeNetworkSpecificData(BinaryReader reader)

Parameters

reader BinaryReader

The BinaryReader to read the data from.

Remarks

This method is called at the end of the general deserialization process to allow derived classes to read any additional data specific to their implementation.

For Beginners: Continuing the suitcase analogy, this is like unpacking that special compartment. After the main deserialization method has unpacked the common items (layers, parameters), this method allows each specific type of neural network to unpack its own unique items that were stored during serialization.

Dispose(bool)

Disposes of resources used by this model.

protected override void Dispose(bool disposing)

Parameters

disposing bool

True if disposing managed resources.

EncodeDocument(Tensor<T>)

Processes a document image and returns encoded features.

public Tensor<T> EncodeDocument(Tensor<T> documentImage)

Parameters

documentImage Tensor<T>

The document image tensor [batch, channels, height, width] or [channels, height, width].

Returns

Tensor<T>

Encoded document features suitable for downstream tasks.

Remarks

For Beginners: This method converts a document image into a numerical representation (feature vector) that captures the document's content and structure. These features can then be used for tasks like classification, QA, or information extraction.

GetAttentionWeights()

Gets the attention weights for visualization (if supported).

public Tensor<T>? GetAttentionWeights()

Returns

Tensor<T>

Attention tensor showing which image regions influenced each character.

GetCharacterProbabilities()

Gets the character-level probabilities for the last recognition.

public Tensor<T> GetCharacterProbabilities()

Returns

Tensor<T>

Tensor of shape [sequence_length, vocab_size] with probabilities.

GetModelMetadata()

Gets the metadata for this neural network model.

public override ModelMetadata<T> GetModelMetadata()

Returns

ModelMetadata<T>

A ModelMetaData object containing information about the model.

GetModelSummary()

Gets a summary of the model architecture.

public string GetModelSummary()

Returns

string

A string describing the model's architecture, parameters, and capabilities.

InitializeLayers()

Initializes the layers of the neural network based on the architecture.

protected override void InitializeLayers()

Remarks

For Beginners: This method sets up all the layers in your neural network according to the architecture you've defined. It's like assembling the parts of your network before you can use it.

Predict(Tensor<T>)

Makes a prediction using the neural network.

public override Tensor<T> Predict(Tensor<T> input)

Parameters

input Tensor<T>

The input data to process.

Returns

Tensor<T>

The network's prediction.

Remarks

For Beginners: This is the main method you'll use to get results from your trained neural network. You provide some input data (like an image or text), and the network processes it through all its layers to produce an output (like a classification or prediction).

RecognizeText(Tensor<T>)

Recognizes text from a cropped image region.

public TextRecognitionResult<T> RecognizeText(Tensor<T> croppedImage)

Parameters

croppedImage Tensor<T>

Cropped image containing text (from text detector).

Returns

TextRecognitionResult<T>

Recognition result with text and confidence.

RecognizeTextBatch(IEnumerable<Tensor<T>>)

Recognizes text from multiple cropped image regions (batch processing).

public IEnumerable<TextRecognitionResult<T>> RecognizeTextBatch(IEnumerable<Tensor<T>> croppedImages)

Parameters

croppedImages IEnumerable<Tensor<T>>

List of cropped images containing text.

Returns

IEnumerable<TextRecognitionResult<T>>

List of recognition results.

SerializeNetworkSpecificData(BinaryWriter)

Serializes network-specific data that is not covered by the general serialization process.

protected override void SerializeNetworkSpecificData(BinaryWriter writer)

Parameters

writer BinaryWriter

The BinaryWriter to write the data to.

Remarks

This method is called at the end of the general serialization process to allow derived classes to write any additional data specific to their implementation.

For Beginners: Think of this as packing a special compartment in your suitcase. While the main serialization method packs the common items (layers, parameters), this method allows each specific type of neural network to pack its own unique items that other networks might not have.

Train(Tensor<T>, Tensor<T>)

Trains the neural network on a single input-output pair.

public override void Train(Tensor<T> input, Tensor<T> expectedOutput)

Parameters

input Tensor<T>

The input data.

expectedOutput Tensor<T>

The expected output for the given input.

Remarks

This method performs one training step on the neural network using the provided input and expected output. It updates the network's parameters to reduce the error between the network's prediction and the expected output.

For Beginners: This is how your neural network learns. You provide: - An input (what the network should process) - The expected output (what the correct answer should be)

The network then:

  1. Makes a prediction based on the input
  2. Compares its prediction to the expected output
  3. Calculates how wrong it was (the loss)
  4. Adjusts its internal values to do better next time

After training, you can get the loss value using the GetLastLoss() method to see how well the network is learning.

UpdateParameters(Vector<T>)

Updates the network's parameters with new values.

public override void UpdateParameters(Vector<T> gradients)

Parameters

gradients Vector<T>

Remarks

For Beginners: During training, a neural network's internal values (parameters) get adjusted to improve its performance. This method allows you to update all those values at once by providing a complete set of new parameters.

This is typically used by optimization algorithms that calculate better parameter values based on training data.

ValidateInputShape(Tensor<T>)

Validates that an input tensor has the correct shape for this model.

public void ValidateInputShape(Tensor<T> documentImage)

Parameters

documentImage Tensor<T>

The tensor to validate.

Exceptions

ArgumentException

Thrown if the tensor shape is invalid.