如何调试C#中的OCR
IronOCR使您可以在源头检测OCR失败,评估词和字符级别的识别质量,并实时监控长时间运行的作业。内置工具如诊断文件日志记录、类型化异常层次结构、每个结果的置信度评分和OcrProgress事件支持这些在生产流水线中的工作流程。
本指南将逐一介绍以下工作示例:启用诊断日志记录、处理类型异常、使用置信度分数验证输出、实时监控作业进度以及隔离批处理管道中的错误。
快速入门:启用完整 OCR 诊断日志记录在第一次Read调用之前,将LogFilePath和LoggingMode设置在Installation类上。 只需两个属性即可将 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 个步骤)
- 下载用于调试OCR的C#库
- 将
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 + 文件 | 完整的诊断捕获 |
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++ Redistributable;检查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 流程中的错误?
在生产环境中,单个文件故障不应该导致整个批次停止运行。 按文件隔离错误,记录故障及其上下文,并在最后生成总结报告。 此示例处理一个包含发票、采购订单、服务合同以及一个故意损坏文件的扫描文档文件夹以触发错误路径。 下面展示的是一个具有代表性的例子:
输入
一文件夹的PDF传递给Directory.GetFiles - 一个发票、一个采购订单、一个服务合同以及一个故意损坏的文件。下面的两个代表性示例显示了流水线在单次运行中处理的文档多样性。
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的日志文件捕获了任何触发内部诊断的文件的引擎级细节。
对于服务或Web应用程序中的非阻塞执行,IronOCR支持ReadAsync,这使用相同的try-catch结构。
如果管道运行没有错误,但提取的文本仍然错误,那么根本原因几乎总是图像质量而不是代码。 以下是解决之道。
如何调试OCR准确率?
如果置信度得分持续偏低,则问题出在源图像上,而不是 OCR 引擎。IronOCR 提供了IronOCR工具来解决这个问题:
- 应用图像质量过滤器,如锐化、去噪、膨胀和腐蚀,以提高文本清晰度
- 使用方向校正自动对扫描文档进行去斜和旋转
- 在处理之前调整DPI设置以便低分辨率图像
- 使用计算机视觉检测和隔离复杂布局中的文本区域
- IronOCR实用工具让您可以直观地测试过滤器组合并导出最佳C#配置
对于特定于部署的问题,IronOCR为Azure Functions、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事件,其跟踪处理多页文档的进度,提供已完成页数和总体百分比进度的更新。
如何在批量OCR管道中使用IronOCR隔离错误?
在批量OCR管道中,通过处理每个文件的异常、记录失败的上下文信息并生成总结报告来隔离错误。这确保了单次失败不会中止整个批次。
IronOCR提供哪些预处理工具来提高OCR准确性?
IronOCR提供了预处理工具,如图像质量过滤器(锐化、去噪)、用于矫正扫描文档倾斜的方向校正,以及用于低分辨率图像的DPI调整以提高OCR准确性。
开发者如何使用IronOCR处理异常?
开发者可以通过为不同类型的异常(如IronOcrInputException和IronOcrProductException)实现特定的catch块来处理异常,将每种异常引导至合适的补救路径。
是否可以用IronOCR异步执行OCR操作?
是的,IronOCR支持通过ReadAsync进行异步操作,允许在服务或Web应用中进行非阻塞操作,并使用与同步操作相同的try-catch结构。
IronOCR中可用的日志记录模式有哪些?
IronOCR支持多种日志记录模式,如用于禁用日志记录的None、用于在IDE中进行调试输出的DebugOutputWindow、用于服务器端收集的File和用于完整诊断捕获的All。
如果OCR信心评分较低,该怎么办?
如果OCR信心评分较低,问题可能出在源图像。使用IronOCR的预处理工具,如图像质量滤镜和方向校正,以改善源图像清晰度。
Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。