
從TesseractOCR遷移到IronOCR
此指南帶領.NET開發人員完全遷移從TesseractOCR NuGet套件(Sicos1977/Kees van Spelde 分支)到IronOCR。 它涵蓋了完整的替換路徑:移除外部預處理依賴項、啟用原生PDF輸入和可搜尋的PDF輸出、更新命名空間和API調用,以及驗證遷移的整合。 不需要閱讀比較文章。
為何從TesseractOCR遷移
TesseractOCR是一個目標於現代.NET的積極維護的社群包裝器,並捆綁了Tesseract 5原生庫。 從舊的包裝器升級到它可以解決框架相容性問題。 但這並無法解決位於包裝器層以下的架構差距。 當這些差距在生產中浮現時,遷移的討論便開始。
預處理完全在庫外進行。 TesseractOCR呼叫engine.Process(image)處理您提供的任何像素。 傾斜的掃描、低對比的傳真、一張收據的手機照片——它們全部送入Tesseract引擎原生。 恢復可用的輸出需要新增SixLabors.ImageSharp、SkiaSharp或類似的影像庫,並撰寫依每種文件型別調整參數的手動過濾器鏈,通過臨時文件路由預處理的影像,因為TesseractOCR.Pix.Image需要文件路徑。 標準的.NET影像庫完全不提供去傾斜功能——這需要從零實現霍夫變換角度檢測算法,通常需要另外50至100行。 這並不是一次性設置成本;每當新的文件型別進入管道時,這種成本就會重現。
PDF輸入需要第二個庫和臨時文件管道。 TesseractOCR處理影像,而不是PDF。 每個PDF工作流程都需要額外的套件——如Docnet.Core、PdfiumViewer或類似的套件——來將PDF頁面渲染為BGRA字節陣列,其中需要一個輔助方法將這些字節轉換為TesseractOCR可讀的格式,以及包裝整個迴路的臨時文件建立和清理邏輯。結果是在每次PDF OCR操作中環繞約100行的基礎結構程式碼。 受密碼保護的PDF僅在解密後需要第三個庫(iText使用AGPL授權或PDFSharp)。
可搜尋的PDF輸出無法實現。 需要從掃描的文件生成機器可讀PDF的團隊發現,TesseractOCR不提供任何機制。 沒有SaveAsSearchablePdf(),沒有hOCR到PDF的管道,除了提取的文字之外沒有其他輸出格式。 增加這種功能需要一個獨立的PDF庫或完全放棄TesseractOCR。
TIFF多幀文件需要手動頁面迴圈。 在傳真工作流程和文件掃描器中常見的多頁TIFF文件沒有原生的多幀處理功能。 提取所有幀需要使用外部庫載入TIFF,迭代幀,將每個幀保存到臨時文件中,並分別將每個臨時文件通過OCR引擎。
社群大小限制了實際支援的範圍。 TesseractOCR大約有200,000個NuGet下載量。 Stack Overflow、部落格文章和GitHub問題討論串關於.NET Tesseract包裝器的資料一致引用charlesw API——TesseractEngine, Pix.LoadFromFile——而不是Sicos1977 API。 針對TesseractOCR特定問題的實際問題排查會迅速碰到這個瓶頸。
根本問題
TesseractOCR不含預處理和PDF支援。 每個生產文件工作流程最終都需要外部庫才能達到OCR可運行的地步:
// TesseractOCR: three packages, a temp file, and manual byte conversion
// just to OCR one PDF page — before any preprocessing
// dotnet add package TesseractOCR
// dotnet add package Docnet.Core
// dotnet add package SixLabors.ImageSharp (preprocessing)
using var library = DocLib.Instance;
using var docReader = library.GetDocReader(pdfPath, new PageDimensions(200, 200));
using var pageReader = docReader.GetPageReader(0);
var bytes = pageReader.GetImage(); // BGRA — not a format Pix.Image accepts directly
string tempPath = Path.GetTempFileName() + ".png";
SaveBgraAsPng(bytes, pageReader.GetPageWidth(), pageReader.GetPageHeight(), tempPath);
// ^ 30+ line helper method needed here
using var engine = new Engine(@"./tessdata", Language.English, EngineMode.Default);
using var image = TesseractOCR.Pix.Image.LoadFromFile(tempPath);
using var page = engine.Process(image);
string text = page.Text;
File.Delete(tempPath); // hope this succeeds' TesseractOCR: three packages, a temp file, and manual byte conversion
' just to OCR one PDF page — before any preprocessing
' dotnet add package TesseractOCR
' dotnet add package Docnet.Core
' dotnet add package SixLabors.ImageSharp (preprocessing)
Using library = DocLib.Instance
Using docReader = library.GetDocReader(pdfPath, New PageDimensions(200, 200))
Using pageReader = docReader.GetPageReader(0)
Dim bytes = pageReader.GetImage() ' BGRA — not a format Pix.Image accepts directly
Dim tempPath As String = Path.GetTempFileName() & ".png"
SaveBgraAsPng(bytes, pageReader.GetPageWidth(), pageReader.GetPageHeight(), tempPath)
' ^ 30+ line helper method needed here
Using engine = New Engine("./tessdata", Language.English, EngineMode.Default)
Using image = TesseractOCR.Pix.Image.LoadFromFile(tempPath)
Using page = engine.Process(image)
Dim text As String = page.Text
File.Delete(tempPath) ' hope this succeeds
End Using
End Using
End Using
End Using
End Using
End Using' TesseractOCR: three packages, a temp file, and manual byte conversion
' just to OCR one PDF page — before any preprocessing
' dotnet add package TesseractOCR
' dotnet add package Docnet.Core
' dotnet add package SixLabors.ImageSharp (preprocessing)
Using library = DocLib.Instance
Using docReader = library.GetDocReader(pdfPath, New PageDimensions(200, 200))
Using pageReader = docReader.GetPageReader(0)
Dim bytes = pageReader.GetImage() ' BGRA — not a format Pix.Image accepts directly
Dim tempPath As String = Path.GetTempFileName() & ".png"
SaveBgraAsPng(bytes, pageReader.GetPageWidth(), pageReader.GetPageHeight(), tempPath)
' ^ 30+ line helper method needed here
Using engine = New Engine("./tessdata", Language.English, EngineMode.Default)
Using image = TesseractOCR.Pix.Image.LoadFromFile(tempPath)
Using page = engine.Process(image)
Dim text As String = page.Text
File.Delete(tempPath) ' hope this succeeds
End Using
End Using
End Using
End Using
End Using
End Using// IronOCR: one package, three lines, preprocessing automatic
// dotnet add package IronOcr
var ocr = new IronTesseract();
using var input = new OcrInput();
input.LoadPdf(pdfPath);
string text = ocr.Read(input).Text;// IronOCR: one package, three lines, preprocessing automatic
// dotnet add package IronOcr
var ocr = new IronTesseract();
using var input = new OcrInput();
input.LoadPdf(pdfPath);
string text = ocr.Read(input).Text;' IronOCR: one package, three lines, preprocessing automatic
' dotnet add package IronOcr
Dim ocr As New IronTesseract()
Using input As New OcrInput()
input.LoadPdf(pdfPath)
Dim text As String = ocr.Read(input).Text
End Using' IronOCR: one package, three lines, preprocessing automatic
' dotnet add package IronOcr
Dim ocr As New IronTesseract()
Using input As New OcrInput()
input.LoadPdf(pdfPath)
Dim text As String = ocr.Read(input).Text
End Using##IronOCRvs TesseractOCR:功能比較
下表列出了在遷移評估中最重要的功能。
| 功能 | TesseractOCR | IronOCR |
|---|---|---|
| NuGet套件 | TesseractOCR | IronOcr |
| .NET相容性 | .NET 6.0, 7.0, 8.0 | .NET Framework 4.6.2+, .NET Core, .NET 5/6/7/8/9 |
| 許可證 | Apache 2.0(免費) | 商業的(永久的,從$999) |
| Tessdata管理 | 需要(從GitHub手動下載) | 不需要(內部捆綁) |
| 內建預處理 | None | Deskew、去噪、對比度、二值化、銳化、縮放、膨脹、侵蝕、反轉 |
| 深度背景噪聲去除 | 不是 | 是(DeepCleanBackgroundNoise()) |
| 本地PDF輸入 | 否(需要Docnet.Core或類似的) | 是(input.LoadPdf()) |
| 受密碼保護的 PDF | 否(需要第三方庫解密) | 是(單一Password參數) |
| 可搜尋的 PDF 輸出 | 不是 | 是(result.SaveAsSearchablePdf()) |
| 多幀TIFF輸入 | 否(需要外部幀提取) | 是(input.LoadImageFrames()) |
| 流與字節陣列輸入 | 否(需要臨時文件中介) | 是(直接LoadImage(stream), LoadImage(bytes)) |
| 執行緒安全性 | 否(每個執行緒需要一個引擎實例) | 是(單一IronTesseract跨執行緒共享) |
| 基於區域的OCR | 不是 | 是(CropRectangle) |
| OCR期間的條碼讀取 | 不是 | 是(ocr.Configuration.ReadBarCodes = true) |
| 結構化輸出(頁面、單字、坐標) | 否(僅平面文字字串) | 是(Pages, Paragraphs, Lines, Words帶X/Y) |
| 信心得分 | 文件級浮點(0.0–1.0) | 文件和文字級雙精度浮點(0–100) |
| hOCR匯出 | 不是 | 是 |
| 125+語言NuGet包 | 不是 | 是 |
| 跨平台部署 | Windows, Linux, macOS | Windows、Linux、macOS、Docker、Azure、AWS |
| 商業支持 | 否(唯一志願者維護者) | 是 (電子郵件,SLA 選項) |
快速開始:TesseractOCR到IronOCR遷移
步驟1:替換NuGet包
移除TesseractOCR和任何支援該軟體的庫:
dotnet remove package TesseractOCR
dotnet remove package Docnet.Core
dotnet remove package SixLabors.ImageSharp
從NuGet安裝IronOCR:
步驟2:更新命名空間
用IronOCR取代所有TesseractOCR命名空間導入:
// Before (TesseractOCR)
using TesseractOCR;
using TesseractOCR.Enums;
// After (IronOCR)
using IronOcr;// Before (TesseractOCR)
using TesseractOCR;
using TesseractOCR.Enums;
// After (IronOCR)
using IronOcr;' Before (TesseractOCR)
Imports TesseractOCR
Imports TesseractOCR.Enums
' After (IronOCR)
Imports IronOcr' Before (TesseractOCR)
Imports TesseractOCR
Imports TesseractOCR.Enums
' After (IronOCR)
Imports IronOcr步驟3:初始化許可證
在應用啟動時並在任何OCR呼叫之前一次性新增授權初始化:
IronOcr.License.LicenseKey = "YOUR-LICENSE-KEY";IronOcr.License.LicenseKey = "YOUR-LICENSE-KEY";IronOcr.License.LicenseKey = "YOUR-LICENSE-KEY"IronOcr.License.LicenseKey = "YOUR-LICENSE-KEY"免費試用授權可從IronOCR授權頁面取得以供評估。
程式碼遷移範例
更換外部預處理管道
TesseractOCR每次文件質量改進都需要外部影像庫。 以下程式碼示範文件質量可變時團隊撰寫的模式——灰階轉換、對比調整、噪聲降低,以及在OCR運行前進行臨時文件寫入。 校正(糾正傾斜的掃描)在標準.NET影像庫中不可用,需要一個單獨的算法來完成。
TesseractOCR方法:
// Requires: dotnet add package SixLabors.ImageSharp
// Manual preprocessing — parameters must be tuned per document type
// Deskew is NOT in ImageSharp — requires custom Hough transform (~50-100 lines)
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
using TesseractOCR;
using TesseractOCR.Enums;
public string ExtractFromLowQualityScan(string imagePath)
{
using var image = Image.Load(imagePath);
image.Mutate(x => x.Grayscale());
image.Mutate(x => x.Contrast(1.5f)); // manual tuning required
image.Mutate(x => x.GaussianBlur(0.5f)); // noise reduction approximation
image.Mutate(x => x.BinaryThreshold(0.5f)); // threshold requires per-doc adjustment
// Deskew omitted — no built-in support, ~80 lines of additional code
string tempPath = Path.GetTempFileName() + ".png";
try
{
image.Save(tempPath);
using var engine = new Engine(@"./tessdata", Language.English, EngineMode.Default);
using var pix = TesseractOCR.Pix.Image.LoadFromFile(tempPath);
using var page = engine.Process(pix);
return page.Text;
}
finally
{
File.Delete(tempPath);
}
}// Requires: dotnet add package SixLabors.ImageSharp
// Manual preprocessing — parameters must be tuned per document type
// Deskew is NOT in ImageSharp — requires custom Hough transform (~50-100 lines)
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
using TesseractOCR;
using TesseractOCR.Enums;
public string ExtractFromLowQualityScan(string imagePath)
{
using var image = Image.Load(imagePath);
image.Mutate(x => x.Grayscale());
image.Mutate(x => x.Contrast(1.5f)); // manual tuning required
image.Mutate(x => x.GaussianBlur(0.5f)); // noise reduction approximation
image.Mutate(x => x.BinaryThreshold(0.5f)); // threshold requires per-doc adjustment
// Deskew omitted — no built-in support, ~80 lines of additional code
string tempPath = Path.GetTempFileName() + ".png";
try
{
image.Save(tempPath);
using var engine = new Engine(@"./tessdata", Language.English, EngineMode.Default);
using var pix = TesseractOCR.Pix.Image.LoadFromFile(tempPath);
using var page = engine.Process(pix);
return page.Text;
}
finally
{
File.Delete(tempPath);
}
}Imports SixLabors.ImageSharp
Imports SixLabors.ImageSharp.Processing
Imports TesseractOCR
Imports TesseractOCR.Enums
Public Function ExtractFromLowQualityScan(imagePath As String) As String
Using image = Image.Load(imagePath)
image.Mutate(Sub(x) x.Grayscale())
image.Mutate(Sub(x) x.Contrast(1.5F)) ' manual tuning required
image.Mutate(Sub(x) x.GaussianBlur(0.5F)) ' noise reduction approximation
image.Mutate(Sub(x) x.BinaryThreshold(0.5F)) ' threshold requires per-doc adjustment
' Deskew omitted — no built-in support, ~80 lines of additional code
Dim tempPath As String = Path.GetTempFileName() & ".png"
Try
image.Save(tempPath)
Using engine = New Engine("./tessdata", Language.English, EngineMode.Default)
Using pix = TesseractOCR.Pix.Image.LoadFromFile(tempPath)
Using page = engine.Process(pix)
Return page.Text
End Using
End Using
End Using
Finally
File.Delete(tempPath)
End Try
End Using
End FunctionImports SixLabors.ImageSharp
Imports SixLabors.ImageSharp.Processing
Imports TesseractOCR
Imports TesseractOCR.Enums
Public Function ExtractFromLowQualityScan(imagePath As String) As String
Using image = Image.Load(imagePath)
image.Mutate(Sub(x) x.Grayscale())
image.Mutate(Sub(x) x.Contrast(1.5F)) ' manual tuning required
image.Mutate(Sub(x) x.GaussianBlur(0.5F)) ' noise reduction approximation
image.Mutate(Sub(x) x.BinaryThreshold(0.5F)) ' threshold requires per-doc adjustment
' Deskew omitted — no built-in support, ~80 lines of additional code
Dim tempPath As String = Path.GetTempFileName() & ".png"
Try
image.Save(tempPath)
Using engine = New Engine("./tessdata", Language.English, EngineMode.Default)
Using pix = TesseractOCR.Pix.Image.LoadFromFile(tempPath)
Using page = engine.Process(pix)
Return page.Text
End Using
End Using
End Using
Finally
File.Delete(tempPath)
End Try
End Using
End FunctionIronOCR方法:
//不是external imaging library
//不是temp file — OcrInput accepts a path, stream, or byte array directly
// Deskew is built in — automatic angle detection and correction
using IronOcr;
public string ExtractFromLowQualityScan(string imagePath)
{
using var input = new OcrInput();
input.LoadImage(imagePath);
input.Deskew(); // automatic angle correction
input.DeNoise(); // intelligent noise removal
input.Contrast(); // automatic contrast enhancement
input.Binarize(); // clean black-and-white conversion
var ocr = new IronTesseract();
return ocr.Read(input).Text;
}//不是external imaging library
//不是temp file — OcrInput accepts a path, stream, or byte array directly
// Deskew is built in — automatic angle detection and correction
using IronOcr;
public string ExtractFromLowQualityScan(string imagePath)
{
using var input = new OcrInput();
input.LoadImage(imagePath);
input.Deskew(); // automatic angle correction
input.DeNoise(); // intelligent noise removal
input.Contrast(); // automatic contrast enhancement
input.Binarize(); // clean black-and-white conversion
var ocr = new IronTesseract();
return ocr.Read(input).Text;
}Imports IronOcr
Public Function ExtractFromLowQualityScan(imagePath As String) As String
Using input As New OcrInput()
input.LoadImage(imagePath)
input.Deskew() ' automatic angle correction
input.DeNoise() ' intelligent noise removal
input.Contrast() ' automatic contrast enhancement
input.Binarize() ' clean black-and-white conversion
Dim ocr As New IronTesseract()
Return ocr.Read(input).Text
End Using
End FunctionImports IronOcr
Public Function ExtractFromLowQualityScan(imagePath As String) As String
Using input As New OcrInput()
input.LoadImage(imagePath)
input.Deskew() ' automatic angle correction
input.DeNoise() ' intelligent noise removal
input.Contrast() ' automatic contrast enhancement
input.Binarize() ' clean black-and-white conversion
Dim ocr As New IronTesseract()
Return ocr.Read(input).Text
End Using
End Function移除ImageSharp依賴可以完全消除調整周期。 OcrInput預處理管道應用針對文件OCR校準的算法——無需猜測對比度倍數或模糊半徑。 影像過濾器教程和影像質量校正指南涵蓋了每個可用的過濾器,並提供了需要調整預設值的參數選項。
更換多幀TIFF處理
傳真文件、文件掃描器輸出和存檔文件經常作為多頁TIFF文件到達。 TesseractOCR不支援多幀——每個幀必須用外部庫提取、保存到磁碟,再逐一加入引擎。IronOCR能夠在單次調用中載入整個TIFF。
TesseractOCR方法:
// Requires: dotnet add package SixLabors.ImageSharp
// Manual frame extraction — every frame becomes a temp file on disk
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats.Tiff;
using TesseractOCR;
using TesseractOCR.Enums;
public string ExtractFromMultiPageTiff(string tiffPath)
{
var allText = new System.Text.StringBuilder();
var tempFiles = new List<string>();
try
{
using var image = Image.Load(tiffPath);
using var engine = new Engine(@"./tessdata", Language.English, EngineMode.Default);
for (int frameIndex = 0; frameIndex < image.Frames.Count; frameIndex++)
{
// Clone frame and save to temp file — no in-memory path
using var frameImage = image.Frames.CloneFrame(frameIndex);
string tempPath = Path.GetTempFileName() + ".png";
tempFiles.Add(tempPath);
frameImage.SaveAsPng(tempPath);
using var pix = TesseractOCR.Pix.Image.LoadFromFile(tempPath);
using var page = engine.Process(pix);
allText.AppendLine($"=== Frame {frameIndex + 1} ===");
allText.AppendLine(page.Text);
}
}
finally
{
foreach (var f in tempFiles)
try { File.Delete(f); } catch { }
}
return allText.ToString();
}// Requires: dotnet add package SixLabors.ImageSharp
// Manual frame extraction — every frame becomes a temp file on disk
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats.Tiff;
using TesseractOCR;
using TesseractOCR.Enums;
public string ExtractFromMultiPageTiff(string tiffPath)
{
var allText = new System.Text.StringBuilder();
var tempFiles = new List<string>();
try
{
using var image = Image.Load(tiffPath);
using var engine = new Engine(@"./tessdata", Language.English, EngineMode.Default);
for (int frameIndex = 0; frameIndex < image.Frames.Count; frameIndex++)
{
// Clone frame and save to temp file — no in-memory path
using var frameImage = image.Frames.CloneFrame(frameIndex);
string tempPath = Path.GetTempFileName() + ".png";
tempFiles.Add(tempPath);
frameImage.SaveAsPng(tempPath);
using var pix = TesseractOCR.Pix.Image.LoadFromFile(tempPath);
using var page = engine.Process(pix);
allText.AppendLine($"=== Frame {frameIndex + 1} ===");
allText.AppendLine(page.Text);
}
}
finally
{
foreach (var f in tempFiles)
try { File.Delete(f); } catch { }
}
return allText.ToString();
}Imports SixLabors.ImageSharp
Imports SixLabors.ImageSharp.Formats.Tiff
Imports TesseractOCR
Imports TesseractOCR.Enums
Public Function ExtractFromMultiPageTiff(tiffPath As String) As String
Dim allText = New System.Text.StringBuilder()
Dim tempFiles = New List(Of String)()
Try
Using image = Image.Load(tiffPath)
Using engine = New Engine("./tessdata", Language.English, EngineMode.Default)
For frameIndex As Integer = 0 To image.Frames.Count - 1
' Clone frame and save to temp file — no in-memory path
Using frameImage = image.Frames.CloneFrame(frameIndex)
Dim tempPath As String = Path.GetTempFileName() & ".png"
tempFiles.Add(tempPath)
frameImage.SaveAsPng(tempPath)
Using pix = TesseractOCR.Pix.Image.LoadFromFile(tempPath)
Using page = engine.Process(pix)
allText.AppendLine($"=== Frame {frameIndex + 1} ===")
allText.AppendLine(page.Text)
End Using
End Using
End Using
Next
End Using
End Using
Finally
For Each f In tempFiles
Try
File.Delete(f)
Catch
End Try
Next
End Try
Return allText.ToString()
End FunctionImports SixLabors.ImageSharp
Imports SixLabors.ImageSharp.Formats.Tiff
Imports TesseractOCR
Imports TesseractOCR.Enums
Public Function ExtractFromMultiPageTiff(tiffPath As String) As String
Dim allText = New System.Text.StringBuilder()
Dim tempFiles = New List(Of String)()
Try
Using image = Image.Load(tiffPath)
Using engine = New Engine("./tessdata", Language.English, EngineMode.Default)
For frameIndex As Integer = 0 To image.Frames.Count - 1
' Clone frame and save to temp file — no in-memory path
Using frameImage = image.Frames.CloneFrame(frameIndex)
Dim tempPath As String = Path.GetTempFileName() & ".png"
tempFiles.Add(tempPath)
frameImage.SaveAsPng(tempPath)
Using pix = TesseractOCR.Pix.Image.LoadFromFile(tempPath)
Using page = engine.Process(pix)
allText.AppendLine($"=== Frame {frameIndex + 1} ===")
allText.AppendLine(page.Text)
End Using
End Using
End Using
Next
End Using
End Using
Finally
For Each f In tempFiles
Try
File.Delete(f)
Catch
End Try
Next
End Try
Return allText.ToString()
End FunctionIronOCR方法:
//不是external library for frame extraction
// All frames processed in one Read() call — no manual loop required
using IronOcr;
public string ExtractFromMultiPageTiff(string tiffPath)
{
var ocr = new IronTesseract();
using var input = new OcrInput();
input.LoadImageFrames(tiffPath); // loads all frames automatically
var result = ocr.Read(input);
// Access per-page text if needed
foreach (var page in result.Pages)
Console.WriteLine($"Frame {page.PageNumber}: {page.Text}");
return result.Text;
}//不是external library for frame extraction
// All frames processed in one Read() call — no manual loop required
using IronOcr;
public string ExtractFromMultiPageTiff(string tiffPath)
{
var ocr = new IronTesseract();
using var input = new OcrInput();
input.LoadImageFrames(tiffPath); // loads all frames automatically
var result = ocr.Read(input);
// Access per-page text if needed
foreach (var page in result.Pages)
Console.WriteLine($"Frame {page.PageNumber}: {page.Text}");
return result.Text;
}'不是external library for frame extraction
' All frames processed in one Read() call — no manual loop required
Imports IronOcr
Public Function ExtractFromMultiPageTiff(tiffPath As String) As String
Dim ocr = New IronTesseract()
Using input = New OcrInput()
input.LoadImageFrames(tiffPath) ' loads all frames automatically
Dim result = ocr.Read(input)
' Access per-page text if needed
For Each page In result.Pages
Console.WriteLine($"Frame {page.PageNumber}: {page.Text}")
Next
Return result.Text
End Using
End Function'不是external library for frame extraction
' All frames processed in one Read() call — no manual loop required
Imports IronOcr
Public Function ExtractFromMultiPageTiff(tiffPath As String) As String
Dim ocr = New IronTesseract()
Using input = New OcrInput()
input.LoadImageFrames(tiffPath) ' loads all frames automatically
Dim result = ocr.Read(input)
' Access per-page text if needed
For Each page In result.Pages
Console.WriteLine($"Frame {page.PageNumber}: {page.Text}")
Next
Return result.Text
End Using
End Function幀提取迴圈、臨時文件列表、finally 清理區塊——這些都消失了。 對於20頁傳真TIFF,這將約40行程式碼替換為6行。TIFF和GIF輸入指南涵蓋了多幀載入選項,包括選定的幀範圍。
生成可搜尋的PDF輸出
這個情境在TesseractOCR中沒有遷移路徑——根本無法做到。 需要將掃描的PDF轉變為機器可讀、文字可選擇文件(用於搜尋索引、可讀性或存檔),需要生成一個可搜尋的PDF輸出。 TesseractOCR只生成提取的文字。 IronOCR直接生成可搜尋的PDF。
TesseractOCR方法:
//不是path available —TesseractOCRcannot produce any PDF output.
// The closest workaround requires a separate PDF library (iTextSharp AGPL,
// or similar) to overlay extracted text onto the original PDF manually.
// This is 150-300 lines of additional code and introduces AGPL license concerns.
// The best available output from TesseractOCR:
using var engine = new Engine(@"./tessdata", Language.English, EngineMode.Default);
using var pix = TesseractOCR.Pix.Image.LoadFromFile("scanned-page.png");
using var page = engine.Process(pix);
string extractedText = page.Text; // flat string — no PDF output possible
File.WriteAllText("output.txt", extractedText);
// Cannot produce a searchable PDF — no API exists for this//不是path available —TesseractOCRcannot produce any PDF output.
// The closest workaround requires a separate PDF library (iTextSharp AGPL,
// or similar) to overlay extracted text onto the original PDF manually.
// This is 150-300 lines of additional code and introduces AGPL license concerns.
// The best available output from TesseractOCR:
using var engine = new Engine(@"./tessdata", Language.English, EngineMode.Default);
using var pix = TesseractOCR.Pix.Image.LoadFromFile("scanned-page.png");
using var page = engine.Process(pix);
string extractedText = page.Text; // flat string — no PDF output possible
File.WriteAllText("output.txt", extractedText);
// Cannot produce a searchable PDF — no API exists for thisImports IronOcr
'不是path available —TesseractOCRcannot produce any PDF output.
' The closest workaround requires a separate PDF library (iTextSharp AGPL,
' or similar) to overlay extracted text onto the original PDF manually.
' This is 150-300 lines of additional code and introduces AGPL license concerns.
' The best available output from TesseractOCR:
Using engine As New Engine("./tessdata", Language.English, EngineMode.Default)
Using pix As TesseractOCR.Pix.Image = TesseractOCR.Pix.Image.LoadFromFile("scanned-page.png")
Using page As Page = engine.Process(pix)
Dim extractedText As String = page.Text ' flat string — no PDF output possible
File.WriteAllText("output.txt", extractedText)
End Using
End Using
End Using
' Cannot produce a searchable PDF — no API exists for thisImports IronOcr
'不是path available —TesseractOCRcannot produce any PDF output.
' The closest workaround requires a separate PDF library (iTextSharp AGPL,
' or similar) to overlay extracted text onto the original PDF manually.
' This is 150-300 lines of additional code and introduces AGPL license concerns.
' The best available output from TesseractOCR:
Using engine As New Engine("./tessdata", Language.English, EngineMode.Default)
Using pix As TesseractOCR.Pix.Image = TesseractOCR.Pix.Image.LoadFromFile("scanned-page.png")
Using page As Page = engine.Process(pix)
Dim extractedText As String = page.Text ' flat string — no PDF output possible
File.WriteAllText("output.txt", extractedText)
End Using
End Using
End Using
' Cannot produce a searchable PDF — no API exists for thisIronOCR方法:
// Native searchable PDF output — no additional library required
// Input can be a scanned image, a scanned PDF, or a multi-page TIFF
using IronOcr;
public void CreateSearchablePdf(string scannedPdfPath, string outputPath)
{
var ocr = new IronTesseract();
using var input = new OcrInput();
input.LoadPdf(scannedPdfPath);
input.Deskew(); // improve accuracy before generating the output
input.DeNoise();
var result = ocr.Read(input);
result.SaveAsSearchablePdf(outputPath); // searchable, text-selectable PDF
}// Native searchable PDF output — no additional library required
// Input can be a scanned image, a scanned PDF, or a multi-page TIFF
using IronOcr;
public void CreateSearchablePdf(string scannedPdfPath, string outputPath)
{
var ocr = new IronTesseract();
using var input = new OcrInput();
input.LoadPdf(scannedPdfPath);
input.Deskew(); // improve accuracy before generating the output
input.DeNoise();
var result = ocr.Read(input);
result.SaveAsSearchablePdf(outputPath); // searchable, text-selectable PDF
}' Native searchable PDF output — no additional library required
' Input can be a scanned image, a scanned PDF, or a multi-page TIFF
Imports IronOcr
Public Sub CreateSearchablePdf(scannedPdfPath As String, outputPath As String)
Dim ocr = New IronTesseract()
Using input = New OcrInput()
input.LoadPdf(scannedPdfPath)
input.Deskew() ' improve accuracy before generating the output
input.DeNoise()
Dim result = ocr.Read(input)
result.SaveAsSearchablePdf(outputPath) ' searchable, text-selectable PDF
End Using
End Sub' Native searchable PDF output — no additional library required
' Input can be a scanned image, a scanned PDF, or a multi-page TIFF
Imports IronOcr
Public Sub CreateSearchablePdf(scannedPdfPath As String, outputPath As String)
Dim ocr = New IronTesseract()
Using input = New OcrInput()
input.LoadPdf(scannedPdfPath)
input.Deskew() ' improve accuracy before generating the output
input.DeNoise()
Dim result = ocr.Read(input)
result.SaveAsSearchablePdf(outputPath) ' searchable, text-selectable PDF
End Using
End SubSaveAsSearchablePdf()呼叫將OCR文字嵌入PDF作為原始掃描影像後的隱藏層。 文件在視覺上保持不變,但可完全搜尋、選擇和索引。 可搜尋PDF指南涵蓋完整的API,可搜尋PDF範例展示了完整的工作模式。
更換字節陣列輸入並消除臨時文件
TesseractOCR的Pix.Image API接受文件路徑。 當影像資料作為字節陣列——來自資料庫,HTTP多表單上傳,記憶體快取——到達時,TesseractOCR迫使寫入臨時文件後才處理。 IronOCR的OcrInput可以直接接受字節陣列和流,徹底消除了臨時文件步驟。
TesseractOCR方法:
// TesseractOCR.Pix.Image has no byte[] or Stream overload
// Every in-memory image must be written to disk before processing
using TesseractOCR;
using TesseractOCR.Enums;
public string ExtractFromBytes(byte[] imageBytes)
{
// Force a disk write just to satisfy the file-path API
string tempPath = Path.GetTempFileName() + ".png";
try
{
File.WriteAllBytes(tempPath, imageBytes);
using var engine = new Engine(@"./tessdata", Language.English, EngineMode.Default);
using var pix = TesseractOCR.Pix.Image.LoadFromFile(tempPath);
using var page = engine.Process(pix);
return page.Text;
}
finally
{
// Risk: if an exception fires between WriteAllBytes and Delete,
// temp files accumulate on the server disk
if (File.Exists(tempPath))
File.Delete(tempPath);
}
}// TesseractOCR.Pix.Image has no byte[] or Stream overload
// Every in-memory image must be written to disk before processing
using TesseractOCR;
using TesseractOCR.Enums;
public string ExtractFromBytes(byte[] imageBytes)
{
// Force a disk write just to satisfy the file-path API
string tempPath = Path.GetTempFileName() + ".png";
try
{
File.WriteAllBytes(tempPath, imageBytes);
using var engine = new Engine(@"./tessdata", Language.English, EngineMode.Default);
using var pix = TesseractOCR.Pix.Image.LoadFromFile(tempPath);
using var page = engine.Process(pix);
return page.Text;
}
finally
{
// Risk: if an exception fires between WriteAllBytes and Delete,
// temp files accumulate on the server disk
if (File.Exists(tempPath))
File.Delete(tempPath);
}
}' TesseractOCR.Pix.Image has no byte[] or Stream overload
' Every in-memory image must be written to disk before processing
Imports TesseractOCR
Imports TesseractOCR.Enums
Public Function ExtractFromBytes(imageBytes As Byte()) As String
' Force a disk write just to satisfy the file-path API
Dim tempPath As String = Path.GetTempFileName() & ".png"
Try
File.WriteAllBytes(tempPath, imageBytes)
Using engine = New Engine("./tessdata", Language.English, EngineMode.Default)
Using pix = TesseractOCR.Pix.Image.LoadFromFile(tempPath)
Using page = engine.Process(pix)
Return page.Text
End Using
End Using
End Using
Finally
' Risk: if an exception fires between WriteAllBytes and Delete,
' temp files accumulate on the server disk
If File.Exists(tempPath) Then
File.Delete(tempPath)
End If
End Try
End Function' TesseractOCR.Pix.Image has no byte[] or Stream overload
' Every in-memory image must be written to disk before processing
Imports TesseractOCR
Imports TesseractOCR.Enums
Public Function ExtractFromBytes(imageBytes As Byte()) As String
' Force a disk write just to satisfy the file-path API
Dim tempPath As String = Path.GetTempFileName() & ".png"
Try
File.WriteAllBytes(tempPath, imageBytes)
Using engine = New Engine("./tessdata", Language.English, EngineMode.Default)
Using pix = TesseractOCR.Pix.Image.LoadFromFile(tempPath)
Using page = engine.Process(pix)
Return page.Text
End Using
End Using
End Using
Finally
' Risk: if an exception fires between WriteAllBytes and Delete,
' temp files accumulate on the server disk
If File.Exists(tempPath) Then
File.Delete(tempPath)
End If
End Try
End FunctionIronOCR方法:
// OcrInput accepts byte arrays and streams natively
//不是disk write, no temp file cleanup, no cleanup failure risk
using IronOcr;
public string ExtractFromBytes(byte[] imageBytes)
{
var ocr = new IronTesseract();
using var input = new OcrInput();
input.LoadImage(imageBytes); // direct byte array — no temp file
return ocr.Read(input).Text;
}
public string ExtractFromStream(Stream imageStream)
{
var ocr = new IronTesseract();
using var input = new OcrInput();
input.LoadImage(imageStream); // direct stream — no intermediate buffer
return ocr.Read(input).Text;
}// OcrInput accepts byte arrays and streams natively
//不是disk write, no temp file cleanup, no cleanup failure risk
using IronOcr;
public string ExtractFromBytes(byte[] imageBytes)
{
var ocr = new IronTesseract();
using var input = new OcrInput();
input.LoadImage(imageBytes); // direct byte array — no temp file
return ocr.Read(input).Text;
}
public string ExtractFromStream(Stream imageStream)
{
var ocr = new IronTesseract();
using var input = new OcrInput();
input.LoadImage(imageStream); // direct stream — no intermediate buffer
return ocr.Read(input).Text;
}Imports IronOcr
Public Function ExtractFromBytes(imageBytes As Byte()) As String
Dim ocr As New IronTesseract()
Using input As New OcrInput()
input.LoadImage(imageBytes) ' direct byte array — no temp file
Return ocr.Read(input).Text
End Using
End Function
Public Function ExtractFromStream(imageStream As Stream) As String
Dim ocr As New IronTesseract()
Using input As New OcrInput()
input.LoadImage(imageStream) ' direct stream — no intermediate buffer
Return ocr.Read(input).Text
End Using
End FunctionImports IronOcr
Public Function ExtractFromBytes(imageBytes As Byte()) As String
Dim ocr As New IronTesseract()
Using input As New OcrInput()
input.LoadImage(imageBytes) ' direct byte array — no temp file
Return ocr.Read(input).Text
End Using
End Function
Public Function ExtractFromStream(imageStream As Stream) As String
Dim ocr As New IronTesseract()
Using input As New OcrInput()
input.LoadImage(imageStream) ' direct stream — no intermediate buffer
Return ocr.Read(input).Text
End Using
End Function在網路應用中處理上傳的文件文件時,臨時文件模式在負載下會累積磁碟使用量,如果清理程式碼出錯,會引入競爭條件。 流輸入指南和影像輸入指南涵蓋了每種支持的輸入格式,包括MemoryStream, byte[], Bitmap和文件路徑。
帶有結構化資料的字詞級別信心過濾
TesseractOCR返回單一文件級信心分數(page.MeanConfidence,浮點介於0.0到1.0之間)和扁平文字字串。 沒有每個字詞的信心值,無法提供字詞定位和無結構層次。 構建一個標識不確定字詞、提取特定區域或將文字映射到文件坐標的工作流程需要切換到一個根本不同的輸出模型。
TesseractOCR方法:
// Only document-level confidence available
//不是word coordinates, no structural hierarchy
using TesseractOCR;
using TesseractOCR.Enums;
public void ProcessWithConfidence(string imagePath)
{
using var engine = new Engine(@"./tessdata", Language.English, EngineMode.Default);
using var pix = TesseractOCR.Pix.Image.LoadFromFile(imagePath);
using var page = engine.Process(pix);
float docConfidence = page.MeanConfidence; // 0.0 to 1.0 for the whole document
if (docConfidence >= 0.7f)
Console.WriteLine($"Accepted ({docConfidence:P0}): {page.Text}");
else
Console.WriteLine($"Rejected ({docConfidence:P0}): document needs preprocessing");
//不是way to identify WHICH words are uncertain
//不是word coordinates available
}// Only document-level confidence available
//不是word coordinates, no structural hierarchy
using TesseractOCR;
using TesseractOCR.Enums;
public void ProcessWithConfidence(string imagePath)
{
using var engine = new Engine(@"./tessdata", Language.English, EngineMode.Default);
using var pix = TesseractOCR.Pix.Image.LoadFromFile(imagePath);
using var page = engine.Process(pix);
float docConfidence = page.MeanConfidence; // 0.0 to 1.0 for the whole document
if (docConfidence >= 0.7f)
Console.WriteLine($"Accepted ({docConfidence:P0}): {page.Text}");
else
Console.WriteLine($"Rejected ({docConfidence:P0}): document needs preprocessing");
//不是way to identify WHICH words are uncertain
//不是word coordinates available
}' Only document-level confidence available
'不是word coordinates, no structural hierarchy
Imports TesseractOCR
Imports TesseractOCR.Enums
Public Sub ProcessWithConfidence(imagePath As String)
Using engine = New Engine("./tessdata", Language.English, EngineMode.Default)
Using pix = TesseractOCR.Pix.Image.LoadFromFile(imagePath)
Using page = engine.Process(pix)
Dim docConfidence As Single = page.MeanConfidence ' 0.0 to 1.0 for the whole document
If docConfidence >= 0.7F Then
Console.WriteLine($"Accepted ({docConfidence:P0}): {page.Text}")
Else
Console.WriteLine($"Rejected ({docConfidence:P0}): document needs preprocessing")
End If
'不是way to identify WHICH words are uncertain
'不是word coordinates available
End Using
End Using
End Using
End Sub' Only document-level confidence available
'不是word coordinates, no structural hierarchy
Imports TesseractOCR
Imports TesseractOCR.Enums
Public Sub ProcessWithConfidence(imagePath As String)
Using engine = New Engine("./tessdata", Language.English, EngineMode.Default)
Using pix = TesseractOCR.Pix.Image.LoadFromFile(imagePath)
Using page = engine.Process(pix)
Dim docConfidence As Single = page.MeanConfidence ' 0.0 to 1.0 for the whole document
If docConfidence >= 0.7F Then
Console.WriteLine($"Accepted ({docConfidence:P0}): {page.Text}")
Else
Console.WriteLine($"Rejected ({docConfidence:P0}): document needs preprocessing")
End If
'不是way to identify WHICH words are uncertain
'不是word coordinates available
End Using
End Using
End Using
End SubIronOCR方法:
// Per-word confidence and coordinate data
// Filter individual uncertain words without discarding the whole document
using IronOcr;
public void ProcessWithWordLevelConfidence(string imagePath)
{
var ocr = new IronTesseract();
using var input = new OcrInput();
input.LoadImage(imagePath);
var result = ocr.Read(input);
Console.WriteLine($"Document confidence: {result.Confidence}%");
// Iterate words and flag those below threshold
foreach (var page in result.Pages)
{
foreach (var word in page.Words)
{
if (word.Confidence < 70)
{
// Low-confidence word — log position for review
Console.WriteLine(
$"Low confidence word '{word.Text}' ({word.Confidence}%) " +
$"at X:{word.X} Y:{word.Y}");
}
}
}
// Extract only high-confidence text
var reliableWords = result.Pages
.SelectMany(p => p.Words)
.Where(w => w.Confidence >= 70)
.Select(w => w.Text);
Console.WriteLine(string.Join(" ", reliableWords));
}// Per-word confidence and coordinate data
// Filter individual uncertain words without discarding the whole document
using IronOcr;
public void ProcessWithWordLevelConfidence(string imagePath)
{
var ocr = new IronTesseract();
using var input = new OcrInput();
input.LoadImage(imagePath);
var result = ocr.Read(input);
Console.WriteLine($"Document confidence: {result.Confidence}%");
// Iterate words and flag those below threshold
foreach (var page in result.Pages)
{
foreach (var word in page.Words)
{
if (word.Confidence < 70)
{
// Low-confidence word — log position for review
Console.WriteLine(
$"Low confidence word '{word.Text}' ({word.Confidence}%) " +
$"at X:{word.X} Y:{word.Y}");
}
}
}
// Extract only high-confidence text
var reliableWords = result.Pages
.SelectMany(p => p.Words)
.Where(w => w.Confidence >= 70)
.Select(w => w.Text);
Console.WriteLine(string.Join(" ", reliableWords));
}' Per-word confidence and coordinate data
' Filter individual uncertain words without discarding the whole document
Imports IronOcr
Public Sub ProcessWithWordLevelConfidence(imagePath As String)
Dim ocr = New IronTesseract()
Using input = New OcrInput()
input.LoadImage(imagePath)
Dim result = ocr.Read(input)
Console.WriteLine($"Document confidence: {result.Confidence}%")
' Iterate words and flag those below threshold
For Each page In result.Pages
For Each word In page.Words
If word.Confidence < 70 Then
' Low-confidence word — log position for review
Console.WriteLine(
$"Low confidence word '{word.Text}' ({word.Confidence}%) " +
$"at X:{word.X} Y:{word.Y}")
End If
Next
Next
' Extract only high-confidence text
Dim reliableWords = result.Pages.
SelectMany(Function(p) p.Words).
Where(Function(w) w.Confidence >= 70).
Select(Function(w) w.Text)
Console.WriteLine(String.Join(" ", reliableWords))
End Using
End Sub' Per-word confidence and coordinate data
' Filter individual uncertain words without discarding the whole document
Imports IronOcr
Public Sub ProcessWithWordLevelConfidence(imagePath As String)
Dim ocr = New IronTesseract()
Using input = New OcrInput()
input.LoadImage(imagePath)
Dim result = ocr.Read(input)
Console.WriteLine($"Document confidence: {result.Confidence}%")
' Iterate words and flag those below threshold
For Each page In result.Pages
For Each word In page.Words
If word.Confidence < 70 Then
' Low-confidence word — log position for review
Console.WriteLine(
$"Low confidence word '{word.Text}' ({word.Confidence}%) " +
$"at X:{word.X} Y:{word.Y}")
End If
Next
Next
' Extract only high-confidence text
Dim reliableWords = result.Pages.
SelectMany(Function(p) p.Words).
Where(Function(w) w.Confidence >= 70).
Select(Function(w) w.Text)
Console.WriteLine(String.Join(" ", reliableWords))
End Using
End Sub每個字詞的信心過濾對於發票處理、表單提取和任何涉及在不確定文字上行動比標記其需審查更糟糕的工作流程都是至關重要的。 信心分數指南涵蓋了完整的評分模型,讀取結果指南記錄了完整的結構化輸出層次。
##TesseractOCRAPI對IronOCR的映射參考
| TesseractOCR | IronOCR | 注意事項 |
|---|---|---|
new Engine(tessDataPath, Language.English, EngineMode.Default) | new IronTesseract() | 無需tessdata路徑; 無需選擇EngineMode |
TesseractOCR.Pix.Image.LoadFromFile(path) | input.LoadImage(path) | 也接受Stream |
engine.Process(pixImage) | ocr.Read(input) | 返回Page |
page.Text | result.Text | 語義相同 |
page.MeanConfidence(0.0至1.0浮點) | result.Confidence(0至100雙精度) | 比例不同——更新門檻比較 |
Language.English |Language.French | OcrLanguage.English + OcrLanguage.French | 加法運算符,不是位OR |
EngineMode.Default | 不適用 | IronOCR內部選擇模式 |
EngineMode.LstmOnly | 不適用 | 自動 |
TesseractOCR.Exceptions.TesseractException | IronOcr.Exceptions.OcrException | 處理的異常型別較少 |
DllNotFoundException(原生缺失) | 不適用 | IronOCR自帶其本地依賴 |
BadImageFormatException(架構匹配問題) | 不適用 | 內部處理 |
外部Image.Mutate(x => x.Grayscale()) | input.Binarize() | 內建,無外部庫 |
外部Image.Mutate(x => x.Contrast(...)) | input.Contrast() | 自動校準 |
| 外部霍夫變換去傾斜 | input.Deskew() | 內建,單一方法調用 |
外部GaussianBlur噪聲過濾器 | input.DeNoise() | 智能噪聲去除 |
DocLib.GetDocReader(pdfPath, ...) | input.LoadPdf(pdfPath) | 不需要Docnet.Core |
docReader.GetPageReader(i).GetImage() + 臨時文件 | input.LoadPdf(pdfPath) | 整個迴圈被取代 |
input.LoadPdf(encrypted, Password: "...") | 單一參數——不需要第三方庫 | |
| 不適用(無PDF輸出) | result.SaveAsSearchablePdf(outputPath) | TesseractOCR中沒有與此等價的功能 |
| 不適用(無多幀支援) | input.LoadImageFrames(tiffPath) | 多幀TIFF在一次調用中 |
| 不適用(僅限文件路徑) | input.LoadImage(stream) / input.LoadImage(bytes) | 消除臨時文件模式 |
每執行緒Engine實例 | 執行緒間共享的單一IronTesseract | 設計上的執行緒安全 |
page.MeanConfidence(僅文件) | word.Confidence每個單詞 | 可用的字詞級評分 |
常見的遷移問題与解決方案
問題1:遷移後信心閾值中斷
TesseractOCR:if (confidence >= 0.7f)以接受結果的程式碼。
解決方案:IronOCR在0-100比例上回報信心作為雙精度浮點。 將所有現有的門檻值乘以100。門檻70.0。 文件級信心在result.Confidence; 字詞級信心在result.Pages[n].Words。
// Before (TesseractOCR): page.MeanConfidence >= 0.7f
// After (IronOCR):
var result = new IronTesseract().Read("document.png");
if (result.Confidence >= 70.0)
{
Console.WriteLine(result.Text);
}// Before (TesseractOCR): page.MeanConfidence >= 0.7f
// After (IronOCR):
var result = new IronTesseract().Read("document.png");
if (result.Confidence >= 70.0)
{
Console.WriteLine(result.Text);
}Dim Result = New IronTesseract().Read("document.png")
If Result.Confidence >= 70.0 Then
Console.WriteLine(Result.Text)
End IfDim Result = New IronTesseract().Read("document.png")
If Result.Confidence >= 70.0 Then
Console.WriteLine(Result.Text)
End If問題2:遷移後臨時目錄填滿
TesseractOCR:圍繞finally區塊中清理的臨時檔案。 如果finally區塊本身拋出例外,或者程式被強制終止,臨時檔案會堆積。
解決方案:替換所有File.WriteAllBytes(tempPath, bytes) + input.LoadImage(stream)。 一旦無程式碼建立臨時檔案,清理邏輯和臨時儲存的目錄建立可以完全刪除。 搜尋GetTempFileName, GetTempPath, 和SaveBgraAsPng找到所有出現的地方。
grep -rn "GetTempFileName\|GetTempPath\|SaveBgraAsPng" --include="*.cs" .
// Before: byte[] → temp file → Pix.Image.LoadFromFile
// After: byte[] → OcrInput directly
using var input = new OcrInput();
input.LoadImage(imageBytes); // no disk write
var result = ocr.Read(input);// Before: byte[] → temp file → Pix.Image.LoadFromFile
// After: byte[] → OcrInput directly
using var input = new OcrInput();
input.LoadImage(imageBytes); // no disk write
var result = ocr.Read(input);Dim input As New OcrInput()
input.LoadImage(imageBytes) ' no disk write
Dim result = ocr.Read(input)Dim input As New OcrInput()
input.LoadImage(imageBytes) ' no disk write
Dim result = ocr.Read(input)請參閱影像輸入指南以獲取所有支持的輸入格式。
問題3:語言運算符變更引起編譯器錯誤
TesseractOCR:多語言OCR使用位元運算符=Language.English|Language.French。 這是一個[Flags]枚舉型式。
解決方案:IronOCR使用加法運算符:OcrLanguage.English + OcrLanguage.French。 這些看起來相似但運算符不同。 執行OcrLanguage.的查找和替換,結合|語言表達式內的 to +將處理大多數情況。 確認所有自動生成的語言組合也使用+。
// Before (TesseractOCR):
var engine = new Engine(@"./tessdata",
Language.English | Language.French | Language.German,
EngineMode.Default);
// After (IronOCR):
var ocr = new IronTesseract();
ocr.Language = OcrLanguage.English + OcrLanguage.French + OcrLanguage.German;// Before (TesseractOCR):
var engine = new Engine(@"./tessdata",
Language.English | Language.French | Language.German,
EngineMode.Default);
// After (IronOCR):
var ocr = new IronTesseract();
ocr.Language = OcrLanguage.English + OcrLanguage.French + OcrLanguage.German;' Before (TesseractOCR):
Dim engine = New Engine("./tessdata", Language.English Or Language.French Or Language.German, EngineMode.Default)
' After (IronOCR):
Dim ocr = New IronTesseract()
ocr.Language = OcrLanguage.English + OcrLanguage.French + OcrLanguage.German' Before (TesseractOCR):
Dim engine = New Engine("./tessdata", Language.English Or Language.French Or Language.German, EngineMode.Default)
' After (IronOCR):
Dim ocr = New IronTesseract()
ocr.Language = OcrLanguage.English + OcrLanguage.French + OcrLanguage.German問題4:解除安裝後仍然引用Docnet和ImageSharp套件
TesseractOCR:用於PDF工作流程的TesseractOCR專案通常會直接依賴Docnet.Core,並使用SixLabors.ImageSharp或SkiaSharp進行預處理。 切換到IronOCR後,這些套件通常仍保留在.csproj中,因為使用聲明尚未完全刪除。
解決方案:從using Docnet.Core, using SixLabors.ImageSharp和相關命名空間引用。 如果dotnet remove package命令實際執行過。
grep -rn "using Docnet\|using SixLabors\|using SkiaSharp" --include="*.cs" .
移除識別文件的引用,然後刪除用於舊管道的預處理幫助方法(ApplyThreshold等)。
問題5:遷移後Docker映像大小增加
TesseractOCR:某些Docker配置通過apt-get install tesseract-ocr tesseract-ocr-eng安裝Tesseract作為系統包,然後引用那些系統二進制檔案。 這根據語言包增加約30-80MB的映像大小。
解決方案:IronOCR將其Tesseract二進制文件捆綁在NuGet套件中。 Dockerfile的apt-get install tesseract-ocr行不再需要,應予以刪除。 語言包也來自NuGet,而不是apt-get install tesseract-ocr-fra。 Docker部署指南提供經過驗證的基底映像配置和IronOCR在容器中運行所需的確切套件。
# Remove these lines after migration:
# RUN apt-get install -y tesseract-ocr tesseract-ocr-eng tesseract-ocr-fra
# COPY ./tessdata /app/tessdata
問題6:DllNotFoundException捕獲塊成為不可達程式碼
TesseractOCR:生產中的TesseractOCR整合捕獲TesseractOCR.Exceptions.TesseractException, BadImageFormatException(用於架構不匹配)。 這些例外型別是對tessdata和本地二進位檔部署不穩定的防禦性反應。
解決方案:IronOCR包含本地依賴項並在內部管理初始化。 BadImageFormatException不適用。 移除這些捕獲塊。 例外範圍縮小到OCR故障的IOException。
// Before: five exception types to handle
catch (TesseractOCR.Exceptions.TesseractException ex) { ... }
catch (DllNotFoundException ex) { ... }
catch (BadImageFormatException ex) { ... }
catch (OutOfMemoryException ex) { ... }
// After: two exception types
catch (IronOcr.Exceptions.OcrException ex) { ... }
catch (IOException ex) { ... }// Before: five exception types to handle
catch (TesseractOCR.Exceptions.TesseractException ex) { ... }
catch (DllNotFoundException ex) { ... }
catch (BadImageFormatException ex) { ... }
catch (OutOfMemoryException ex) { ... }
// After: two exception types
catch (IronOcr.Exceptions.OcrException ex) { ... }
catch (IOException ex) { ... }' Before: five exception types to handle
Catch ex As TesseractOCR.Exceptions.TesseractException
...
Catch ex As DllNotFoundException
...
Catch ex As BadImageFormatException
...
Catch ex As OutOfMemoryException
...
' After: two exception types
Catch ex As IronOcr.Exceptions.OcrException
...
Catch ex As IOException
...' Before: five exception types to handle
Catch ex As TesseractOCR.Exceptions.TesseractException
...
Catch ex As DllNotFoundException
...
Catch ex As BadImageFormatException
...
Catch ex As OutOfMemoryException
...
' After: two exception types
Catch ex As IronOcr.Exceptions.OcrException
...
Catch ex As IOException
...TesseractOCR遷移檢查清單
遷移前
審核程式碼庫中所有TesseractOCR使用點:
grep -rn "using TesseractOCR" --include="*.cs" .
grep -rn "new Engine(" --include="*.cs" .
grep -rn "Pix\.Image\.LoadFromFile\|engine\.Process\|page\.Text\|MeanConfidence" --include="*.cs" .
grep -rn "Language\." --include="*.cs" .
識別所有將要移除的支援基礎設施:
grep -rn "using Docnet\|using SixLabors\|GetTempFileName\|SaveBgraAsPng" --include="*.cs" .
grep -rn "tessdata" --include="*.cs" .
grep -rn "tessdata" --include="*.csproj" .
grep -rn "tessdata" Dockerfile 2>/dev/null || true
在遷移前紀錄代表性文件樣本的當前準確性基準,以便在遷移後驗證質量。
程式碼遷移
- 執行
dotnet remove package TesseractOCR - 執行
dotnet remove package Docnet.Core(如果存在) - 執行
dotnet remove package SixLabors.ImageSharp(如果新增了預處理) - 執行
dotnet add package IronOcr - 在應用啟動時新增
IronOcr.License.LicenseKey = "YOUR-LICENSE-KEY" - 從
using IronOcr - 使用
new Engine(tessDataPath, Language.English, EngineMode.Default) - 在
TesseractOCR.Pix.Image.LoadFromFile(path) - 用
engine.Process(pixImage) - 用
page.Text - 更新信心閾值比較——將所有0.0–1.0值乘以100以適應IronOCR 0–100比例
- 用
Language.X| Language.YwithOcrLanguage.X + OcrLanguage.Y - 刪除所有預處理幫助方法(
SaveBgraAsPng,手動過濾鍊,臨時文件邏輯) - 用
input.LoadPdfPages(path, start, end)替換Docnet PDF渲染迴圈 - 用
input.LoadImageFrames(tiffPath)替換多幀TIFF迴圈 - 用
File.WriteAllBytes(tempPath, bytes)+LoadFromFile(tempPath) - 更新捕獲區塊——移除
TesseractException,DllNotFoundException,BadImageFormatException - 從專案輸出目錄配置和Docker映像中移除tessdata文件夾
遷移後
確認dotnet build不會產生編譯器錯誤和不可達捕獲警告
對預遷移準確性基準樣本進行OCR測試並比較結果
確認多頁TIFF文件生成正確的提取頁數
確認可搜尋PDF輸出可在PDF查看器中開啟並可選擇文字
測試應用實際資料來源的字節陣列和流輸入路徑
確認字詞級信心值在0–100範圍內(不是0.0–1.0)
執行並行處理測試以確認沒有每執行緒引擎分配警告
部署至目標環境(Docker、Azure、Linux)並確認IronOCR初始化無DllNotFoundException
確認在部署腳本中沒有引用tessdata文件夾或.traineddata文件
遷移至IronOCR的主要好處
預處理變成了一行配置,而不是100行依賴。 遷移後,input.Deskew(), input.Contrast()替代了外部影像庫、手動參數調整和連接兩者的臨時文件寫入。 手機照片、傾斜掃描和低對比的傳真——這些以前需要專用預處理工程師的文件型別——通過內建管道產生可靠的輸出。預處理功能頁面列出所有可用的過濾器。
PDF是一流的輸入和輸出格式。 Docnet依賴,BGRA到PNG轉換助手,臨時文件管理迴圈,用於密碼保護文件的第三方庫——這些都消除了。 系統中接收到的每個PDF都直接進入input.LoadPdf()。 任何需要變得可搜尋的掃描文件都會通過result.SaveAsSearchablePdf()輸出。 需100多行程式碼的TesseractOCR完整PDF管道變成幾個方法調用。 瀏覽PDF OCR用例頁面以獲取支持的完整PDF工作流程範圍。
結構化輸出取代平面文字字串。 result.Pages, result.Paragraphs, result.Lines, 以及result.Words暴露了具有每個元素座標和每個字詞信心分數的文件結構。 以前需要解析啟發式以尋找特定字段的工作流程——發票編號、日期、金額——可以使用字詞級座標和信心過濾來代替。 這是在IronOCR的OCR結果功能上構建可靠表單提取和文件處理管道的基礎。
部署不再需要tessdata協調。 tessdata文件夾,curl下載腳本,Docker .traineddata檔案配置——這些全都消失了。 語言會以NuGet套件的形式發佈,並隨著其他專案依賴一起進行版本管理、恢復及部署,不論目標為開發者工作站、Docker容器、Azure應用服務還是AWS Lambda皆相同。 Azure部署指南和Linux部署指南提供了生產環境的經驗配置。
授權模式是可預期的。 TesseractOCR是免費的,但所需的基礎設施卻不是——包括開發者的預處理實施時間、PDF庫評估、tessdata部署腳本和外部依賴鏈的持續維護。 IronOCR的永久授權($999 Lite,$1,499 Professional,$2,999 Enterprise)是一個一次性的費用,取代了多周的基礎設施工作,並消除了持續的維護表面。 有保證的商業支援回應路徑取代了對單一志願者維護者的GitHub問題隊列的依賴。
相關文章


