如何在 C# 中除錯 OCR
IronOCR 讓您能在源頭偵測OCR失敗,在字詞和字元層級評估識別質量,並實時監控長時間運行的工作流程。內建工具如診斷文件日誌記錄、型別化例外階層、自信度評分,以及OcrProgress事件支持這些生產管道中的工作流程。
本指南將逐一介紹以下工作範例:啟用診斷日誌記錄、處理類型異常、使用置信度分數驗證輸出、即時監控作業進度以及隔離批次管道中的錯誤。
快速入門:啟用完整 OCR 診斷日誌記錄在第一次Read呼叫之前,於Installation類別上設定LogFilePath和LoggingMode。 只需兩個屬性即可將 Tesseract 初始化、語言包載入和處理詳細資訊擷取到日誌檔案中。
-
1使用 IronOCR 安裝 NuGet Package Manager
-
2複製並運行這段程式碼。
IronOcr.Installation.LogFilePath = "ocr.log"; IronOcr.Installation.LoggingMode = IronOcr.Installation.LoggingModes.All;IronOcr.Installation.LogFilePath = "ocr.log" IronOcr.Installation.LoggingMode = IronOcr.Installation.LoggingModes.AllIronOcr.Installation.LogFilePath = "ocr.log" IronOcr.Installation.LoggingMode = IronOcr.Installation.LoggingModes.All -
3部署到您的生產環境進行測試
立即在您的項目中開始使用 IronOCR,並使用 免費試用
最小工作流程(5 個步驟)
- 下載C#程式庫以除錯OCR
- 將
LogFilePath設定為可寫入檔案路徑 - 將
LoggingMode設定為All以擷取所有診斷信息 - 執行您的 OCR 操作並重現該問題
- 檢查生成的日誌檔案,以查看引擎警告及處理詳情
如何啟用診斷日誌記錄?
Installation類別揭示了三種日誌控制。 在呼叫任何Read方法之前設置這些。
using IronOcr;
// Write logs to a specific file
Installation.LogFilePath = "logs/ocr_diagnostics.log";
// Enable all logging channels: file + debug output
Installation.LoggingMode = Installation.LoggingModes.All;
// Or pipe logs into your existing ILogger pipeline
Installation.CustomLogger = myLoggerInstance;using IronOcr;
// Write logs to a specific file
Installation.LogFilePath = "logs/ocr_diagnostics.log";
// Enable all logging channels: file + debug output
Installation.LoggingMode = Installation.LoggingModes.All;
// Or pipe logs into your existing ILogger pipeline
Installation.CustomLogger = myLoggerInstance;Imports IronOcr
' Write logs to a specific file
Installation.LogFilePath = "logs/ocr_diagnostics.log"
' Enable all logging channels: file + debug output
Installation.LoggingMode = Installation.LoggingModes.All
' Or pipe logs into your existing ILogger pipeline
Installation.CustomLogger = myLoggerInstanceImports IronOcr
' Write logs to a specific file
Installation.LogFilePath = "logs/ocr_diagnostics.log"
' Enable all logging channels: file + debug output
Installation.LoggingMode = Installation.LoggingModes.All
' Or pipe logs into your existing ILogger pipeline
Installation.CustomLogger = myLoggerInstanceLoggingMode接受LoggingModes列舉中的旗標值:
| 模式 | 目標輸出 | 用例 |
|---|---|---|
None | 已停用 | 生產環境搭配外部監控 |
DebugOutputWindow | IDE 除錯輸出視窗 | 在地化開發 |
File | LogFilePath | 伺服器端日誌收集 |
All | DebugOutputWindow + File | 完整診斷擷取 |
CustomLogger屬性支持任何Microsoft.Extensions.Logging.ILogger實作,允許您將OCR診斷導向至Serilog、NLog或管線中的其他結構化日誌接收端。使用ClearLogFiles以在運行之間移除累積的日誌資料。
日誌記錄就緒後,下一步是了解IronOCR可能拋出哪些異常情況以及如何處理每種異常。
IronOCR會拋出哪些異常?
IronOCR 在IronOcr.Exceptions命名空間下定義了型別化例外。 與其進行一刀切式攔截,不如專門針對這些故障類型進行攔截,這樣可以將每種故障類型路由到正確的修復路徑。
| 例外 | 共同事業 | 修正 |
|---|---|---|
IronOcrInputException | 損壞或不支援的圖片/PDF | 在載入 OcrInput 之前驗證檔案 |
IronOcrProductException | OCR 執行期間發生內部引擎錯誤 | 啟用記錄功能、檢查記錄輸出、更新至最新 NuGet 版本 |
IronOcrDictionaryException | 缺少或損毀的 .traineddata 語言檔案 | 重新安裝語言包NuGet或設定LanguagePackDirectory |
IronOcrNativeException | 原生 C++ 互通失敗 | 安裝Visual C++ 執行庫;檢查AVX支持 |
IronOcrLicensingException | 缺少或已過期的授權金鑰 | 在呼叫Read之前設定LicenseKey |
LanguagePackException | 未在預期路徑中找到語言套件 | 請檢查 LanguagePackDirectory 或重新安裝 NuGet 語言套件 |
IronOcrAssemblyVersionMismatchException | 部分更新後組件版本不匹配 | 清除 NuGet 快取、還原套件,並確保所有 IronOCR 套件版本一致 |
使用下列 try-catch 區塊分別處理每種異常類型,套用異常過濾器進行條件日誌記錄。
輸入
由IronOCR Solutions發票至Acme Corporation的單頁供應商發票,透過LoadPdf載入至OcrInput。 它包含四個細項、稅金和總計 - 足夠的文字多樣性給每個例外處理器提供一個現實的練習。
invoice_scan.pdf:供應商發票(#INV-2024-7829),用於依序示範每個類型化的異常處理程序。
using IronOcr;
using IronOcr.Exceptions;
var ocr = new IronTesseract();
try
{
using var input = new OcrInput();
input.LoadPdf("invoice_scan.pdf");
OcrResult result = ocr.Read(input);
Console.WriteLine($"Text: {result.Text}");
Console.WriteLine($"Confidence: {result.Confidence:P1}");
}
catch (IronOcrInputException ex)
{
// File could not be loaded — corrupt, locked, or unsupported format
Console.Error.WriteLine($"Input error: {ex.Message}");
}
catch (IronOcrDictionaryException ex)
{
// Language pack missing — common in containerized deployments
Console.Error.WriteLine($"Language pack error: {ex.Message}");
}
catch (IronOcrNativeException ex) when (ex.Message.Contains("AVX"))
{
// CPU does not support AVX instructions
Console.Error.WriteLine($"Hardware incompatibility: {ex.Message}");
}
catch (IronOcrLicensingException)
{
Console.Error.WriteLine("License key is missing or invalid.");
}
catch (IronOcrProductException ex)
{
// Catch-all for other IronOCR engine errors
Console.Error.WriteLine($"OCR engine error: {ex.Message}");
Console.Error.WriteLine($"Stack trace: {ex.StackTrace}");
}using IronOcr;
using IronOcr.Exceptions;
var ocr = new IronTesseract();
try
{
using var input = new OcrInput();
input.LoadPdf("invoice_scan.pdf");
OcrResult result = ocr.Read(input);
Console.WriteLine($"Text: {result.Text}");
Console.WriteLine($"Confidence: {result.Confidence:P1}");
}
catch (IronOcrInputException ex)
{
// File could not be loaded — corrupt, locked, or unsupported format
Console.Error.WriteLine($"Input error: {ex.Message}");
}
catch (IronOcrDictionaryException ex)
{
// Language pack missing — common in containerized deployments
Console.Error.WriteLine($"Language pack error: {ex.Message}");
}
catch (IronOcrNativeException ex) when (ex.Message.Contains("AVX"))
{
// CPU does not support AVX instructions
Console.Error.WriteLine($"Hardware incompatibility: {ex.Message}");
}
catch (IronOcrLicensingException)
{
Console.Error.WriteLine("License key is missing or invalid.");
}
catch (IronOcrProductException ex)
{
// Catch-all for other IronOCR engine errors
Console.Error.WriteLine($"OCR engine error: {ex.Message}");
Console.Error.WriteLine($"Stack trace: {ex.StackTrace}");
}Imports IronOcr
Imports IronOcr.Exceptions
Dim ocr = New IronTesseract()
Try
Using input = New OcrInput()
input.LoadPdf("invoice_scan.pdf")
Dim result As OcrResult = ocr.Read(input)
Console.WriteLine($"Text: {result.Text}")
Console.WriteLine($"Confidence: {result.Confidence:P1}")
End Using
Catch ex As IronOcrInputException
' File could not be loaded — corrupt, locked, or unsupported format
Console.Error.WriteLine($"Input error: {ex.Message}")
Catch ex As IronOcrDictionaryException
' Language pack missing — common in containerized deployments
Console.Error.WriteLine($"Language pack error: {ex.Message}")
Catch ex As IronOcrNativeException When ex.Message.Contains("AVX")
' CPU does not support AVX instructions
Console.Error.WriteLine($"Hardware incompatibility: {ex.Message}")
Catch ex As IronOcrLicensingException
Console.Error.WriteLine("License key is missing or invalid.")
Catch ex As IronOcrProductException
' Catch-all for other IronOCR engine errors
Console.Error.WriteLine($"OCR engine error: {ex.Message}")
Console.Error.WriteLine($"Stack trace: {ex.StackTrace}")
End TryImports IronOcr
Imports IronOcr.Exceptions
Dim ocr = New IronTesseract()
Try
Using input = New OcrInput()
input.LoadPdf("invoice_scan.pdf")
Dim result As OcrResult = ocr.Read(input)
Console.WriteLine($"Text: {result.Text}")
Console.WriteLine($"Confidence: {result.Confidence:P1}")
End Using
Catch ex As IronOcrInputException
' File could not be loaded — corrupt, locked, or unsupported format
Console.Error.WriteLine($"Input error: {ex.Message}")
Catch ex As IronOcrDictionaryException
' Language pack missing — common in containerized deployments
Console.Error.WriteLine($"Language pack error: {ex.Message}")
Catch ex As IronOcrNativeException When ex.Message.Contains("AVX")
' CPU does not support AVX instructions
Console.Error.WriteLine($"Hardware incompatibility: {ex.Message}")
Catch ex As IronOcrLicensingException
Console.Error.WriteLine("License key is missing or invalid.")
Catch ex As IronOcrProductException
' Catch-all for other IronOCR engine errors
Console.Error.WriteLine($"OCR engine error: {ex.Message}")
Console.Error.WriteLine($"Stack trace: {ex.StackTrace}")
End Try輸出
成功輸出
發票載入正常,引擎傳回字元數和置信度評分。

輸出失敗

按從最具體到最一般的順序排列捕獲塊。 when子句在IronOcrNativeException上篩選AVX相關錯誤,而不捕獲不相關的原生錯誤。 每個處理程序都會記錄異常訊息; 兜底塊也會捕捉堆疊追蹤訊息,以便進行事後分析。
捕捉正確的異常可以告訴你哪裡出了問題,但並不能告訴你引擎在成功運行時表現如何。 為此,可以使用置信度評分。
如何使用置信度分數驗證 OCR 輸出?
每個OcrResult暴露一個Confidence屬性,該值介於0到1之間,代表引擎對所有識別字符的統計確定性平均值。 您可以在結果階層的每個級別上訪問這個:文件、頁面、段落、單詞和字符。
使用閾值門控模式防止低品質結果向下游傳播。
輸入
通過LoadImage加載的具品項明細的熱敏收據,包含折扣、總計和條形碼。 它的窄寬度、等寬字體和淡淡的印刷字體使其成為對每個單字置信度閾值進行實際壓力測試的理想工具。

receipt.png:熱敏收據掃描,用以展示閾值閘門信心驗證和逐字精確度分析
using IronOcr;
var ocr = new IronTesseract();
using var input = new OcrInput();
input.LoadImage("receipt.png");
OcrResult result = ocr.Read(input);
double confidence = result.Confidence;
Console.WriteLine($"Overall confidence: {confidence:P1}");
// Threshold-gated decision
if (confidence >= 0.90)
{
Console.WriteLine("ACCEPT — high confidence, processing result.");
ProcessResult(result.Text);
}
else if (confidence >= 0.70)
{
Console.WriteLine("FLAG — moderate confidence, queuing for review.");
QueueForReview(result.Text, confidence);
}
else
{
Console.WriteLine("REJECT — low confidence, logging for investigation.");
LogRejection("receipt.png", confidence);
}
// Drill into per-page and per-word confidence for diagnostics
foreach (var page in result.Pages)
{
Console.WriteLine($" Page {page.PageNumber}: {page.Confidence:P1}");
var lowConfidenceWords = page.Words
.Where(w => w.Confidence < 0.70)
.ToList();
foreach (var word in lowConfidenceWords)
{
Console.WriteLine($" Low-confidence word: \"{word.Text}\" ({word.Confidence:P1})");
}
}using IronOcr;
var ocr = new IronTesseract();
using var input = new OcrInput();
input.LoadImage("receipt.png");
OcrResult result = ocr.Read(input);
double confidence = result.Confidence;
Console.WriteLine($"Overall confidence: {confidence:P1}");
// Threshold-gated decision
if (confidence >= 0.90)
{
Console.WriteLine("ACCEPT — high confidence, processing result.");
ProcessResult(result.Text);
}
else if (confidence >= 0.70)
{
Console.WriteLine("FLAG — moderate confidence, queuing for review.");
QueueForReview(result.Text, confidence);
}
else
{
Console.WriteLine("REJECT — low confidence, logging for investigation.");
LogRejection("receipt.png", confidence);
}
// Drill into per-page and per-word confidence for diagnostics
foreach (var page in result.Pages)
{
Console.WriteLine($" Page {page.PageNumber}: {page.Confidence:P1}");
var lowConfidenceWords = page.Words
.Where(w => w.Confidence < 0.70)
.ToList();
foreach (var word in lowConfidenceWords)
{
Console.WriteLine($" Low-confidence word: \"{word.Text}\" ({word.Confidence:P1})");
}
}Imports IronOcr
Dim ocr As New IronTesseract()
Using input As New OcrInput()
input.LoadImage("receipt.png")
Dim result As OcrResult = ocr.Read(input)
Dim confidence As Double = result.Confidence
Console.WriteLine($"Overall confidence: {confidence:P1}")
' Threshold-gated decision
If confidence >= 0.9 Then
Console.WriteLine("ACCEPT — high confidence, processing result.")
ProcessResult(result.Text)
ElseIf confidence >= 0.7 Then
Console.WriteLine("FLAG — moderate confidence, queuing for review.")
QueueForReview(result.Text, confidence)
Else
Console.WriteLine("REJECT — low confidence, logging for investigation.")
LogRejection("receipt.png", confidence)
End If
' Drill into per-page and per-word confidence for diagnostics
For Each page In result.Pages
Console.WriteLine($" Page {page.PageNumber}: {page.Confidence:P1}")
Dim lowConfidenceWords = page.Words _
.Where(Function(w) w.Confidence < 0.7) _
.ToList()
For Each word In lowConfidenceWords
Console.WriteLine($" Low-confidence word: ""{word.Text}"" ({word.Confidence:P1})")
Next
Next
End UsingImports IronOcr
Dim ocr As New IronTesseract()
Using input As New OcrInput()
input.LoadImage("receipt.png")
Dim result As OcrResult = ocr.Read(input)
Dim confidence As Double = result.Confidence
Console.WriteLine($"Overall confidence: {confidence:P1}")
' Threshold-gated decision
If confidence >= 0.9 Then
Console.WriteLine("ACCEPT — high confidence, processing result.")
ProcessResult(result.Text)
ElseIf confidence >= 0.7 Then
Console.WriteLine("FLAG — moderate confidence, queuing for review.")
QueueForReview(result.Text, confidence)
Else
Console.WriteLine("REJECT — low confidence, logging for investigation.")
LogRejection("receipt.png", confidence)
End If
' Drill into per-page and per-word confidence for diagnostics
For Each page In result.Pages
Console.WriteLine($" Page {page.PageNumber}: {page.Confidence:P1}")
Dim lowConfidenceWords = page.Words _
.Where(Function(w) w.Confidence < 0.7) _
.ToList()
For Each word In lowConfidenceWords
Console.WriteLine($" Low-confidence word: ""{word.Text}"" ({word.Confidence:P1})")
Next
Next
End Using輸出

此模式對於 OCR 銜接至資料輸入、發票處理或合規工作流程的處理鏈至關重要。 逐字分析可以準確地確定來源影像的哪些區域導致了影像品質下降; 然後您可以套用圖像質量濾鏡或方向校正並重新處理。 若要深入了解信心水平,請參見信心水平如何操作。
對於需要長期從事的工作來說,光有自信是不夠的。 您還需要知道引擎是否仍在取得進展,而OcrProgress事件就派上用場了。
如何即時監控OCR辨識進度?
對於多頁文件,在每頁完成後,OcrProgress事件於IronTesseract上觸發。 OcrProgressEventsArgs對象揭示進度百分比、經過時間、總頁數和已完成頁數。 此範例使用這份三頁的季度報告作為輸入:一份結構化的商業文檔,包括執行摘要、收入明細和營運指標。
輸入
通過LoadPdf加載的三頁Q1 2024財務報告。 第一頁涵蓋了執行摘要和KPI指標,第二頁包含按產品線及地區的收入表,第三頁涵蓋營運處理量 - 每個頁面類型在進度回調中產生可觀察的每頁時間。
quarterly_report.pdf:2024 年第一季三頁財務報告(執行摘要、收入明細、營運指標),用於示範每頁的即時OcrProgress回呼。
using IronOcr;
var ocr = new IronTesseract();
ocr.OcrProgress += (sender, e) =>
{
Console.WriteLine(
$"[OCR] {e.ProgressPercent}% complete | " +
$"Page {e.PagesComplete}/{e.TotalPages} | " +
$"Elapsed: {e.Duration.TotalSeconds:F1}s"
);
};
using var input = new OcrInput();
input.LoadPdf("quarterly_report.pdf");
OcrResult result = ocr.Read(input);
Console.WriteLine($"Finished in {result.Pages.Count()} pages, confidence: {result.Confidence:P1}");using IronOcr;
var ocr = new IronTesseract();
ocr.OcrProgress += (sender, e) =>
{
Console.WriteLine(
$"[OCR] {e.ProgressPercent}% complete | " +
$"Page {e.PagesComplete}/{e.TotalPages} | " +
$"Elapsed: {e.Duration.TotalSeconds:F1}s"
);
};
using var input = new OcrInput();
input.LoadPdf("quarterly_report.pdf");
OcrResult result = ocr.Read(input);
Console.WriteLine($"Finished in {result.Pages.Count()} pages, confidence: {result.Confidence:P1}");Imports IronOcr
Dim ocr As New IronTesseract()
AddHandler ocr.OcrProgress, Sub(sender, e)
Console.WriteLine($"[OCR] {e.ProgressPercent}% complete | " &
$"Page {e.PagesComplete}/{e.TotalPages} | " &
$"Elapsed: {e.Duration.TotalSeconds:F1}s")
End Sub
Using input As New OcrInput()
input.LoadPdf("quarterly_report.pdf")
Dim result As OcrResult = ocr.Read(input)
Console.WriteLine($"Finished in {result.Pages.Count()} pages, confidence: {result.Confidence:P1}")
End UsingImports IronOcr
Dim ocr As New IronTesseract()
AddHandler ocr.OcrProgress, Sub(sender, e)
Console.WriteLine($"[OCR] {e.ProgressPercent}% complete | " &
$"Page {e.PagesComplete}/{e.TotalPages} | " &
$"Elapsed: {e.Duration.TotalSeconds:F1}s")
End Sub
Using input As New OcrInput()
input.LoadPdf("quarterly_report.pdf")
Dim result As OcrResult = ocr.Read(input)
Console.WriteLine($"Finished in {result.Pages.Count()} pages, confidence: {result.Confidence:P1}")
End Using輸出

將此事件連接到您的日誌記錄基礎架構,以追蹤 OCR 作業持續時間並偵測停滯情況。 如果經過的時間超過閾值而進度百分比沒有增加,則管道可以標記該作業以進行調查。 這特別適用於批次PDF處理,以防單個頁面格式錯誤會卡住整個工作流程。
進度監控顯示執行狀態,但如果沒有隔離,檔案級故障仍然可能導致整個批次提前停止。
如何處理批量 OCR 流程中的錯誤?
在生產環境中,單一檔案故障不應該導致整批停止運作。 按文件隔離錯誤,記錄故障及其上下文,並在最後產生總結報告。 該示例處理包含發票、購買訂單、服務合同,另有一個故意損壞的文件觸發錯誤路徑的掃描文件夾。 下面展示的是一個代表性的例子:
輸入
傳遞至Directory.GetFiles的一個PDF資料夾——一張發票,一個採購訂單,一份服務合同,以及一個故意損壞的文件。以下兩個代表性樣本顯示了在單次運行中管道處理的文檔多樣性。
batch-scan-01.pdf:Bright Horizon Ltd.的發票(INV-2024-001)- 成功的OCR通過。
batch-scan-02.pdf:TechSupply Inc.的採購訂單(PO-2024-042)- 在同一次運行中的第二種類型的文件。
using IronOcr;
using IronOcr.Exceptions;
var ocr = new IronTesseract();
Installation.LogFilePath = "batch_debug.log";
Installation.LoggingMode = Installation.LoggingModes.File;
string[] files = Directory.GetFiles("scans/", "*.pdf");
int succeeded = 0, failed = 0;
double totalConfidence = 0;
var failures = new List<(string File, string Error)>();
foreach (string file in files)
{
try
{
using var input = new OcrInput();
input.LoadPdf(file);
OcrResult result = ocr.Read(input);
totalConfidence += result.Confidence;
succeeded++;
Console.WriteLine($"OK: {Path.GetFileName(file)} — {result.Confidence:P1}");
}
catch (IronOcrInputException ex)
{
failed++;
failures.Add((file, $"Input error: {ex.Message}"));
Console.Error.WriteLine($"FAIL: {Path.GetFileName(file)} — {ex.Message}");
}
catch (IronOcrProductException ex)
{
failed++;
failures.Add((file, $"Engine error: {ex.Message}"));
Console.Error.WriteLine($"FAIL: {Path.GetFileName(file)} — {ex.Message}");
}
catch (Exception ex)
{
failed++;
failures.Add((file, $"Unexpected: {ex.Message}"));
Console.Error.WriteLine($"FAIL: {Path.GetFileName(file)} — {ex.GetType().Name}: {ex.Message}");
}
}
// Summary report
Console.WriteLine($"\n--- Batch Summary ---");
Console.WriteLine($"Total: {files.Length} | Passed: {succeeded} | Failed: {failed}");
if (succeeded > 0)
Console.WriteLine($"Average confidence: {totalConfidence / succeeded:P1}");
foreach (var (f, err) in failures)
Console.WriteLine($" {Path.GetFileName(f)}: {err}");using IronOcr;
using IronOcr.Exceptions;
var ocr = new IronTesseract();
Installation.LogFilePath = "batch_debug.log";
Installation.LoggingMode = Installation.LoggingModes.File;
string[] files = Directory.GetFiles("scans/", "*.pdf");
int succeeded = 0, failed = 0;
double totalConfidence = 0;
var failures = new List<(string File, string Error)>();
foreach (string file in files)
{
try
{
using var input = new OcrInput();
input.LoadPdf(file);
OcrResult result = ocr.Read(input);
totalConfidence += result.Confidence;
succeeded++;
Console.WriteLine($"OK: {Path.GetFileName(file)} — {result.Confidence:P1}");
}
catch (IronOcrInputException ex)
{
failed++;
failures.Add((file, $"Input error: {ex.Message}"));
Console.Error.WriteLine($"FAIL: {Path.GetFileName(file)} — {ex.Message}");
}
catch (IronOcrProductException ex)
{
failed++;
failures.Add((file, $"Engine error: {ex.Message}"));
Console.Error.WriteLine($"FAIL: {Path.GetFileName(file)} — {ex.Message}");
}
catch (Exception ex)
{
failed++;
failures.Add((file, $"Unexpected: {ex.Message}"));
Console.Error.WriteLine($"FAIL: {Path.GetFileName(file)} — {ex.GetType().Name}: {ex.Message}");
}
}
// Summary report
Console.WriteLine($"\n--- Batch Summary ---");
Console.WriteLine($"Total: {files.Length} | Passed: {succeeded} | Failed: {failed}");
if (succeeded > 0)
Console.WriteLine($"Average confidence: {totalConfidence / succeeded:P1}");
foreach (var (f, err) in failures)
Console.WriteLine($" {Path.GetFileName(f)}: {err}");Imports IronOcr
Imports IronOcr.Exceptions
Dim ocr As New IronTesseract()
Installation.LogFilePath = "batch_debug.log"
Installation.LoggingMode = Installation.LoggingModes.File
Dim files As String() = Directory.GetFiles("scans/", "*.pdf")
Dim succeeded As Integer = 0, failed As Integer = 0
Dim totalConfidence As Double = 0
Dim failures As New List(Of (File As String, Error As String))()
For Each file As String In files
Try
Using input As New OcrInput()
input.LoadPdf(file)
Dim result As OcrResult = ocr.Read(input)
totalConfidence += result.Confidence
succeeded += 1
Console.WriteLine($"OK: {Path.GetFileName(file)} — {result.Confidence:P1}")
End Using
Catch ex As IronOcrInputException
failed += 1
failures.Add((file, $"Input error: {ex.Message}"))
Console.Error.WriteLine($"FAIL: {Path.GetFileName(file)} — {ex.Message}")
Catch ex As IronOcrProductException
failed += 1
failures.Add((file, $"Engine error: {ex.Message}"))
Console.Error.WriteLine($"FAIL: {Path.GetFileName(file)} — {ex.Message}")
Catch ex As Exception
failed += 1
failures.Add((file, $"Unexpected: {ex.Message}"))
Console.Error.WriteLine($"FAIL: {Path.GetFileName(file)} — {ex.GetType().Name}: {ex.Message}")
End Try
Next
' Summary report
Console.WriteLine(vbCrLf & "--- Batch Summary ---")
Console.WriteLine($"Total: {files.Length} | Passed: {succeeded} | Failed: {failed}")
If succeeded > 0 Then
Console.WriteLine($"Average confidence: {totalConfidence / succeeded:P1}")
End If
For Each failure In failures
Console.WriteLine($" {Path.GetFileName(failure.File)}: {failure.Error}")
NextImports IronOcr
Imports IronOcr.Exceptions
Dim ocr As New IronTesseract()
Installation.LogFilePath = "batch_debug.log"
Installation.LoggingMode = Installation.LoggingModes.File
Dim files As String() = Directory.GetFiles("scans/", "*.pdf")
Dim succeeded As Integer = 0, failed As Integer = 0
Dim totalConfidence As Double = 0
Dim failures As New List(Of (File As String, Error As String))()
For Each file As String In files
Try
Using input As New OcrInput()
input.LoadPdf(file)
Dim result As OcrResult = ocr.Read(input)
totalConfidence += result.Confidence
succeeded += 1
Console.WriteLine($"OK: {Path.GetFileName(file)} — {result.Confidence:P1}")
End Using
Catch ex As IronOcrInputException
failed += 1
failures.Add((file, $"Input error: {ex.Message}"))
Console.Error.WriteLine($"FAIL: {Path.GetFileName(file)} — {ex.Message}")
Catch ex As IronOcrProductException
failed += 1
failures.Add((file, $"Engine error: {ex.Message}"))
Console.Error.WriteLine($"FAIL: {Path.GetFileName(file)} — {ex.Message}")
Catch ex As Exception
failed += 1
failures.Add((file, $"Unexpected: {ex.Message}"))
Console.Error.WriteLine($"FAIL: {Path.GetFileName(file)} — {ex.GetType().Name}: {ex.Message}")
End Try
Next
' Summary report
Console.WriteLine(vbCrLf & "--- Batch Summary ---")
Console.WriteLine($"Total: {files.Length} | Passed: {succeeded} | Failed: {failed}")
If succeeded > 0 Then
Console.WriteLine($"Average confidence: {totalConfidence / succeeded:P1}")
End If
For Each failure In failures
Console.WriteLine($" {Path.GetFileName(failure.File)}: {failure.Error}")
Next輸出

外部 catch 區塊處理意外錯誤,包括共享儲存上的網路逾時、權限問題或大型 TIFF 檔案記憶體不足的情況。 每次失敗都會將檔案路徑和錯誤訊息記錄在摘要中,同時迴圈會繼續處理剩餘的檔案。 位於batch_debug.log的日誌文件捕獲任何觸發內部診斷的文件的引擎級詳細信息。
為了進行服務或網路應用中的非阻塞執行,IronOCR支持ReadAsync,這使用相同的try-catch結構。
如果管道運行沒有錯誤,但提取的文字仍然錯誤,那麼根本原因幾乎總是圖像品質而不是程式碼。 以下是解決之道。
如何調試OCR辨識準確率?
如果置信度分數持續偏低,則問題出在來源影像上,而不是 OCR 引擎。 IronOCR 提供了IronOCR工具來解決這個問題:
- 套用圖片質量濾鏡如銳化、去噪、膨脹和侵蝕以改善文本清晰度
- 使用方向校正自動去偏和旋轉掃描文檔
- 調整DPI設置以處理前的低解析度圖像
- 使用計算機視覺來檢測和分離復雜佈局中的文本區域
- IronOCR工具讓您能夠視覺測試濾鏡組合並匯出最佳C#配置
對於特定於部署的問題,IronOCR 為Azure Function、Docker 和 Linux及一般環境設置維護專用的故障排除指南。
接下來我該去哪裡?
既然您已經了解如何在運行時調試IronOCR ,請探索以下內容:
- 瀏覽OCR結果結構和元數據包括頁面、區塊、段落、單詞和座標
- 在結果層次的每一級別上理解信心水平
- 與
ReadAsync一起使用異步和多執行緒以獲得高吞吐量管線 - 瀏覽完整的API參考以獲取完整的屬性列表
對於生產使用,請記得獲取授權以移除水印並獲得完整功能。
常見問題
如何啟用IronOCR中的診斷日誌記錄?
要在IronOCR中啟用診斷日誌記錄,需在首次 Read 呼叫前設置 Installation 類中的 LogFilePath 和 LoggingMode 屬性。此設置記錄細節如Tesseract初始化和語言包加載。
IronOCR會丟擲哪些常見例外?
常見的例外包括:對於損壞的影像是 IronOcrInputException,針對內部引擎錯誤是 IronOcrProductException,對於缺失的語言文件是 IronOcrDictionaryException,以及缺失授權金鑰是 IronOcrLicensingException。
IronOCR如何處理置信度評分?
IronOCR提供 Confidence 屬性,表示所有識別字元的統計置信度平均值。這可以用來驗證OCR輸出,讓您能在進一步處理前過濾掉低置信度結果。
IronOCR能否實時監控OCR進度?
是的,IronOCR具備 OcrProgress 事件,通過提供已完成頁數和總百分比進度的更新,追蹤多頁文件處理的進程。
如何在使用IronOCR的批次OCR管道中隔離錯誤?
在批次OCR管道中,透過每個文件處理例外,記錄失敗的上下文,並產生總結報告來隔離錯誤。這樣能確保單一失敗不會中斷整個批次。
IronOCR提供哪些預處理工具以提高OCR準確性?
IronOCR提供預處理工具如影像品質過濾(銳化,去噪)、傾斜修正、以及低解析度影像的DPI調整來提高OCR準確性。
開發者如何使用IronOCR處理例外?
開發者可以通過為不同例外類型(如 IronOcrInputException 和 IronOcrProductException)實作特定的catch區塊來處理例外,指示每種例外走適當的補救路徑。
使用IronOCR可以以非同步方式執行OCR操作嗎?
可以,IronOCR支持通過 ReadAsync 執行異步操作,允許在服務或網頁應用中進行非阻塞執行,並採用與同步操作相同的try-catch結構。
IronOCR有哪些可用的日誌記錄模式?
IronOCR支持多種日誌記錄模式,像是 None 禁用日誌記錄、DebugOutputWindow 用於IDE中的調試輸出、File 用於伺服器端收集,以及 All 用於完整的診斷資料捕捉。
如果OCR的置信度評分低應該怎麼辦?
如果OCR的置信度評分低,可能與來源影像有關。使用IronOCR的預處理工具如影像品質過濾和方位修正來改善來源影像的清晰度。
Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。