Bsa.Pdf.Ocr
1.0.42
dotnet add package Bsa.Pdf.Ocr --version 1.0.42
NuGet\Install-Package Bsa.Pdf.Ocr -Version 1.0.42
<PackageReference Include="Bsa.Pdf.Ocr" Version="1.0.42" />
<PackageVersion Include="Bsa.Pdf.Ocr" Version="1.0.42" />
<PackageReference Include="Bsa.Pdf.Ocr" />
paket add Bsa.Pdf.Ocr --version 1.0.42
#r "nuget: Bsa.Pdf.Ocr, 1.0.42"
#:package Bsa.Pdf.Ocr@1.0.42
#addin nuget:?package=Bsa.Pdf.Ocr&version=1.0.42
#tool nuget:?package=Bsa.Pdf.Ocr&version=1.0.42
Bsa.Pdf.Ocr
Optical character recognition (OCR) in pure C#. The library runs PaddleOCR models in ONNX format with its own ONNX engine — no ONNX Runtime, OpenCV or any other native library. It works wherever .NET runs: Windows, Linux, macOS, x64 and ARM64.
- Text line detection with a DB model, line recognition with a CTC model (PP-OCRv3…v5, any PaddleOCR alphabet).
- Reading order, vertical lines, pages rotated by 180°.
- The position of every line (four corners) and every word — for example, to build an invisible PDF text layer.
- Vectorized math (
System.Numerics.Vector) and all processor cores. - Target frameworks: .NET 6, .NET 8, .NET 10.
Documentation in Russian: README.ru.md in the package.
Installation
dotnet add package Bsa.Pdf.Ocr
Models
Models are not included in the package. Three files are needed:
| File | What it is |
|---|---|
det.onnx |
Text line detection model (DB), for example PP-OCRv5 mobile det (about 5 MB) |
rec.onnx |
Line recognition model (CTC) for the alphabet you need |
dict.txt |
Dictionary of the recognition model: one character per line, in the order of the model classes |
For Russian and English text, PP-OCRv5 eslav (East Slavic languages) works well:
- det:
https://huggingface.co/pitapo/rapidocr/resolve/main/onnx/PP-OCRv5/det/ch_PP-OCRv5_mobile_det.onnx - rec:
https://huggingface.co/monkt/paddleocr-onnx/resolve/main/languages/eslav/rec.onnx - dictionary:
https://huggingface.co/monkt/paddleocr-onnx/resolve/main/languages/eslav/dict.txt
For other languages take rec.onnx and dict.txt from the neighbouring languages/ folders (Latin, Chinese,
Arabic…); the detection model is shared. PaddleOCR models are distributed under the Apache 2.0 license.
The files can be placed in a folder or packed into a single ocr-models.zip archive (files may be in any folder of
the archive). The archive is read into memory and is never extracted to disk.
Quick start
using System;
using System.Threading;
using Bsa.Pdf.Ocr;
// Models from a folder: det.onnx, rec.onnx, dict.txt.
var engine = new OcrEngine(OcrModelFiles.InDirectory(@"C:\models\ocr"), new OcrOptions());
// BGR pixels, 3 bytes per pixel, rows without padding.
var image = new OcrImage(width, height, bgrPixels);
foreach (var line in engine.Recognize(image, CancellationToken.None))
{
Console.WriteLine($"{line.Confidence:P0} {line.Text}");
}
Models are loaded once in the constructor, so create one OcrEngine for the whole application. An instance can be
called from several threads at the same time.
Models from an archive or from memory
// The ocr-models.zip archive.
var engine = new OcrEngine(OcrModelArchive.Read(@"C:\models\ocr-models.zip"), new OcrOptions());
// Models embedded in your assembly or downloaded from the network.
var data = new OcrModelData(detectionBytes, recognitionBytes, dictionaryText);
var engine2 = new OcrEngine(data, new OcrOptions());
OcrModelFiles.InDirectory(dir).Exist() and OcrModelArchive.InDirectory(dir) help to check that the models are in place.
Where to get pixels
OcrImage takes BGR (the channel order PaddleOCR models were trained on). If your imaging library returns BGRA
(PDFium, SkiaSharp with SKColorType.Bgra8888, WPF/WinForms Format32bppArgb), use OcrImage.FromBgra —
transparency is blended with a white background:
var image = OcrImage.FromBgra(width, height, stride, bgraPixels);
For RGB/RGBA swap the first and third byte of every pixel.
Page resolution of about 200–300 dpi works best: small text at 100 dpi is recognized worse, and more than 300 dpi only slows down line detection.
Result
Analyze returns the lines and the time of each stage:
var result = engine.Analyze(image, cancellationToken);
Console.WriteLine($"Detection {result.Timings.Detection.TotalSeconds:F1} s, recognition {result.Timings.Recognition.TotalSeconds:F1} s");
if (result.Timings.UpsideDown) Console.WriteLine("The page was upside down");
foreach (var line in result.Lines)
{
// Line box corners in pixels: start top, end top, end bottom, start bottom.
var (start, end) = (line.Corners[0], line.Corners[1]);
foreach (var word in line.Words)
{
// Word position — a fraction of the line length from its start (0) to its end (1).
var x = start.X + (end.X - start.X) * word.Start;
var y = start.Y + (end.Y - start.Y) * word.Start;
Console.WriteLine($"{word.Text} @ ({x:F0}, {y:F0})");
}
}
| Type | Contents |
|---|---|
OcrLine |
Text, Confidence (0…1), Corners (4 points; from the first to the second is the text direction), Words |
OcrWord |
Text, Start, End — fractions of the line length |
OcrTimings |
Detection, Recognition, Total, UpsideDown |
Lines come in reading order: top to bottom, left to right within a row.
Options (OcrOptions)
| Option | Default | Effect |
|---|---|---|
DetectionMaxSide |
1536 | Largest image side for line detection (a multiple of 32). Smaller is faster, but small text gets lost |
BinaryThreshold |
0.3 | "Text here" threshold on the detection map |
BoxThreshold |
0.6 | Minimum mean probability of a region to count as a line |
UnclipRatio |
1.5 | How much to expand a detected region |
MinBoxSide |
3 | Minimum line side, pixels |
RecognitionHeight |
48 | Line height at the recognition model input if the model does not define it (usually it does: v3 — 48, older — 32) |
RecognitionMinWidth / RecognitionMaxWidth |
320 / 3200 | Width of the recognition model input |
DetectUpsideDown |
true | Check for a 180° rotation (the 6 longest lines are read both ways) |
MinConfidence |
0.5 | Lines with lower confidence are dropped |
var options = new OcrOptions { DetectionMaxSide = 1024, MinConfidence = 0.7, DetectUpsideDown = false };
Cancellation
All methods take a CancellationToken: cancellation is checked between the nodes of the model graph and between
lines, so a long recognition of a large page stops quickly (OperationCanceledException).
The ONNX engine on its own
The engine can run other small models too, as long as they use only supported operators (convolutions, pooling, normalization, element-wise and matrix operations, reshaping, Resize; float and int64 tensors):
using Bsa.Pdf.Ocr.Runtime;
using Bsa.Pdf.Ocr.Tensors;
var session = InferenceSession.Load("model.onnx");
var input = Tensor.FromFloats(new[] { 1, 3, 224, 224 }, pixels);
var outputs = session.Run(new Dictionary<string, Tensor> { [session.InputNames[0]] = input }, CancellationToken.None);
var scores = outputs[session.OutputNames[0]].Floats;
If the model contains unsupported operators, the session constructor throws NotSupportedException listing their names.
Performance
Line detection takes most of the time and depends on DetectionMaxSide; lines are recognized in parallel on all
processor cores. See OcrResult.Timings for the stage timings on your own pages.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net6.0 is compatible. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- No dependencies.
-
net6.0
- No dependencies.
-
net8.0
- No dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.