Class CRAFT<T>
- Namespace
- AiDotNet.Document.OCR.TextDetection
- Assembly
- AiDotNet.dll
CRAFT (Character Region Awareness for Text Detection) neural network for character-level text detection.
public class CRAFT<T> : DocumentNeuralNetworkBase<T>, INeuralNetworkModel<T>, INeuralNetwork<T>, IInterpretableModel<T>, IInputGradientComputable<T>, IDisposable, ITextDetector<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
TThe numeric type used for calculations.
- Inheritance
-
CRAFT<T>
- Implements
- Inherited Members
- Extension Methods
Remarks
CRAFT detects text at the character level by predicting character regions and affinity (the relationship between characters) maps. This enables precise detection of text with arbitrary shapes, orientations, and sizes.
For Beginners: CRAFT works by: 1. Finding each character individually (character region) 2. Finding the connections between characters (affinity) 3. Grouping connected characters into words/lines
This approach handles:
- Curved text
- Rotated text
- Dense text regions
- Multiple languages
Example usage:
var model = new CRAFT<float>(architecture);
var result = model.DetectText(documentImage);
foreach (var region in result.TextRegions)
Console.WriteLine($"Text at: ({region.BoundingBox})");
Reference: "Character Region Awareness for Text Detection" (CVPR 2019) https://arxiv.org/abs/1904.01941
Constructors
CRAFT(NeuralNetworkArchitecture<T>, int, int, int, IOptimizer<T, Tensor<T>, Tensor<T>>?, ILossFunction<T>?)
Creates a CRAFT model using native layers for training and inference.
public CRAFT(NeuralNetworkArchitecture<T> architecture, int imageSize = 768, int backboneChannels = 512, int upscaleChannels = 256, IOptimizer<T, Tensor<T>, Tensor<T>>? optimizer = null, ILossFunction<T>? lossFunction = null)
Parameters
architectureNeuralNetworkArchitecture<T>imageSizeintbackboneChannelsintupscaleChannelsintoptimizerIOptimizer<T, Tensor<T>, Tensor<T>>lossFunctionILossFunction<T>
Remarks
Default Configuration (CRAFT from CVPR 2019): - VGG16-BN backbone (modified) - U-Net style upsampling - 2-channel output (character + affinity maps) - Backbone channels: 512 - Image size: 768x768
CRAFT(NeuralNetworkArchitecture<T>, string, int, int, int, IOptimizer<T, Tensor<T>, Tensor<T>>?, ILossFunction<T>?)
Creates a CRAFT model using a pre-trained ONNX model for inference.
public CRAFT(NeuralNetworkArchitecture<T> architecture, string onnxModelPath, int imageSize = 768, int backboneChannels = 512, int upscaleChannels = 256, IOptimizer<T, Tensor<T>, Tensor<T>>? optimizer = null, ILossFunction<T>? lossFunction = null)
Parameters
architectureNeuralNetworkArchitecture<T>onnxModelPathstringimageSizeintbackboneChannelsintupscaleChannelsintoptimizerIOptimizer<T, Tensor<T>, Tensor<T>>lossFunctionILossFunction<T>
Properties
ExpectedImageSize
Gets the expected input image size (assumes square images).
public int ExpectedImageSize { get; }
Property Value
Remarks
Common values: 224 (ViT base), 384, 448, 512, 768, 1024. Input images will be resized to [ImageSize x ImageSize] before processing.
MinTextHeight
Gets the minimum detectable text height in pixels.
public int MinTextHeight { get; }
Property Value
MinTextSize
Gets the minimum supported text size.
public int MinTextSize { get; }
Property Value
RequiresOCR
Gets whether this model requires OCR preprocessing.
public override bool RequiresOCR { get; }
Property Value
Remarks
Layout-aware models (LayoutLM, etc.) require OCR to provide text and bounding boxes. OCR-free models (Donut, Pix2Struct) process raw pixels directly.
SupportedDocumentTypes
Gets the supported document types for this model.
public override DocumentType SupportedDocumentTypes { get; }
Property Value
SupportsCharacterDetection
Gets whether this detector supports character-level detection.
public bool SupportsCharacterDetection { get; }
Property Value
SupportsLineDetection
Gets whether this detector supports line-level detection.
public bool SupportsLineDetection { get; }
Property Value
SupportsPolygonOutput
Gets whether polygon output is supported.
public bool SupportsPolygonOutput { get; }
Property Value
SupportsRotatedText
Gets whether this detector supports rotated text detection.
public bool SupportsRotatedText { get; }
Property Value
SupportsWordDetection
Gets whether this detector supports word-level detection.
public bool SupportsWordDetection { get; }
Property Value
Methods
ApplyDefaultPostprocessing(Tensor<T>)
Applies CRAFT's industry-standard postprocessing: pass-through (character and affinity maps are already final).
protected override Tensor<T> ApplyDefaultPostprocessing(Tensor<T> modelOutput)
Parameters
modelOutputTensor<T>
Returns
- Tensor<T>
ApplyDefaultPreprocessing(Tensor<T>)
Applies CRAFT's industry-standard preprocessing: ImageNet normalization.
protected override Tensor<T> ApplyDefaultPreprocessing(Tensor<T> rawImage)
Parameters
rawImageTensor<T>
Returns
- Tensor<T>
Remarks
CRAFT (Character Region Awareness for Text detection) uses ImageNet normalization with mean=[0.485, 0.456, 0.406] and std=[0.229, 0.224, 0.225] (NAVER 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
readerBinaryReaderThe 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.
DetectText(Tensor<T>)
Detects text regions in an image.
public TextDetectionResult<T> DetectText(Tensor<T> documentImage)
Parameters
documentImageTensor<T>
Returns
- TextDetectionResult<T>
Detection result with text region locations.
DetectText(Tensor<T>, double)
Detects text regions with a custom confidence threshold.
public TextDetectionResult<T> DetectText(Tensor<T> documentImage, double confidenceThreshold)
Parameters
documentImageTensor<T>confidenceThresholddoubleMinimum confidence for a detection (0-1).
Returns
- TextDetectionResult<T>
Detection result with text region locations.
DetectTextBatch(IEnumerable<Tensor<T>>)
public IEnumerable<TextDetectionResult<T>> DetectTextBatch(IEnumerable<Tensor<T>> documentImages)
Parameters
documentImagesIEnumerable<Tensor<T>>
Returns
Dispose(bool)
Disposes of resources used by this model.
protected override void Dispose(bool disposing)
Parameters
disposingboolTrue if disposing managed resources.
EncodeDocument(Tensor<T>)
Processes a document image and returns encoded features.
public Tensor<T> EncodeDocument(Tensor<T> documentImage)
Parameters
documentImageTensor<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.
GetAffinityMap()
Gets the affinity (character connection) heatmap from the last detection.
public Tensor<T> GetAffinityMap()
Returns
- Tensor<T>
Affinity probability map.
GetCharacterMap()
Gets the character region heatmap from the last detection.
public Tensor<T> GetCharacterMap()
Returns
- Tensor<T>
Character region probability map.
GetHeatmap()
public Tensor<T> GetHeatmap()
Returns
- Tensor<T>
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.
GetProbabilityMap(Tensor<T>)
Gets the probability map showing text likelihood at each pixel.
public Tensor<T> GetProbabilityMap(Tensor<T> image)
Parameters
imageTensor<T>The input image tensor.
Returns
- Tensor<T>
Probability map tensor with same spatial dimensions as input.
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
inputTensor<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).
SerializeNetworkSpecificData(BinaryWriter)
Serializes network-specific data that is not covered by the general serialization process.
protected override void SerializeNetworkSpecificData(BinaryWriter writer)
Parameters
writerBinaryWriterThe 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
inputTensor<T>The input data.
expectedOutputTensor<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:
- Makes a prediction based on the input
- Compares its prediction to the expected output
- Calculates how wrong it was (the loss)
- 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
gradientsVector<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
documentImageTensor<T>The tensor to validate.
Exceptions
- ArgumentException
Thrown if the tensor shape is invalid.