C#でのOCRのデバッグ方法
IronOCR を使用すると、OCRの失敗をソースで検出し、認識品質を単語レベルや文字レベルで評価し、長時間実行されるジョブをリアルタイムで監視できます。診断ファイルロギング、タイプ別例外階層、結果ごとの信頼度スコアリング、および OcrProgress イベントなどの組み込みツールが、本番用パイプラインでこれらのワークフローをサポートします。
このガイドでは、診断ログの有効化、型付き例外の処理、信頼度スコアによる出力の検証、ジョブの進行状況のリアルタイム監視、バッチパイプラインにおけるエラーの分離など、それぞれの動作例を順を追って説明します。
クイックスタート: フルOCR診断ログを有効にする最初のRead呼び出しの前に、InstallationクラスでLogFilePathとLoggingModeを設定します。 Tesseractの初期化、言語パックの読み込み、および処理の詳細をログファイルに記録するには、たった2つのプロパティを設定するだけで済みます。
-
1IronOCR を 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すべてに設定してください。 - OCR操作を実行し、問題を再現します
- 生成されたログファイルを検査して、エンジンの警告と処理の詳細を見ます
診断ログを有効にするにはどうすればよいですか?
Installationクラスには3つのロギング制御が公開されています。 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名前空間の下にタイプ別例外を定義しています。 包括的なキャッチブロックではなく、これらのエラーを個別にキャッチすることで、それぞれのエラータイプを適切な修復パスにルーティングできます。
| 例外 | 共通の原因 | 修正方法 |
|---|---|---|
IronOcrInput例外 | 壊れたまたはサポートされていない画像/PDF | ファイルをOcrInputに読み込む前に検証 |
IronOcrProduct例外 | OCR実行中の内部エンジンエラー | ログを有効にし、ログ出力を確認し、最新のNuGetバージョンに更新 |
IronOcrDictionary例外 | 欠落または壊れた.traineddata言語ファイル | 言語パックのNuGetを再インストールするか、 LanguagePackDirectoryを設定してください。 |
IronOcrNativeException | ネイティブC++の相互運用の失敗 | Visual C++ 再頒布可能パッケージ をインストールし、AVXサポートを確認してください |
IronOcrLicensing例外 | 欠落または期限切れのライセンスキー | Readを呼び出す前にLicenseKeyを設定してください。 |
LanguagePack例外 | 想定されたパスに言語パックが見つかりません | LanguagePackDirectoryを確認するか、NuGet言語パッケージを再インストール |
IronOcrAssemblyVersionMismatch例外 | 部分的な更新後のアセンブリバージョンの不一致 | NuGetキャッシュをクリアし、パッケージを復元して、すべてのIronOCRパッケージが一致していることを確認 |
以下のtry-catchブロックを使用して、各例外タイプを個別に処理し、条件付きログ記録のために例外フィルタを適用します。
入力
IronOCR SolutionsからAcme Corporationへの1ページのベンダー請求書がLoadPdf経由でOcrInputにロードされます。 それは4つのライン項目、税、および合計金額を含み、それぞれの例外ハンドラに現実的な演習を提供するのに十分なテキストの多様性を持っています。
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出力
成功時の出力
請求書は正常に読み込まれ、エンジンは文字数と信頼度スコアを返します。

出力失敗

キャッチブロックは、最も具体的なものから最も一般的なものへと順に並べなさい。 IronOcrNativeExceptionのwhen句は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の進行状況をリアルタイムで監視するにはどうすればよいですか?
複数ページのドキュメントの場合、IronTesseractのOcrProgressイベントは各ページ完了後に発生します。 OcrProgressEventsArgsオブジェクトは、進行状況のパーセント、経過時間、総ページ数、および完了したページを公開します。 この例では、3ページにわたる四半期報告書を入力として使用します。これは、エグゼクティブサマリー、収益内訳、および業務指標を含む構造化されたビジネス文書です。
入力
2024年第1四半期の3ページの財務報告はLoadPdfでロードされています。 1ページ目にはKPIメトリクスを含むエグゼクティブサマリーが含まれ、2ページ目には製品ラインと地域ごとの収益表が含まれ、3ページ目には運用処理量が記載されています。各ページタイプは異なるページごとのタイミングを生成し、その進行コールバックで確認できます。
quarterly_report.pdf: 2024年第1四半期の3ページにわたる財務報告書(エグゼクティブサマリー、収益内訳、運用指標)で、ページごとのリアルタイムの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フォルダ - 請求書、注文書、サービス契約、および意図的に破損したファイルが含まれています。以下の2つの代表的なサンプルは、1回の実行でパイプラインが処理するドキュメントの多様さを示しています。
batch-scan-01.pdf: Bright Horizon Ltd.の請求書 (INV-2024-001) - OCR検査成功。
batch-scan-02.pdf: TechSupply Inc.の注文書 (PO-2024-042) - 同じ実行での2番目のドキュメントタイプ。
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は、この問題を解決するための前処理ツールを提供しています。
- テキストの明瞭さを向上させるために、シャープ、ノイズ除去、膨張、収縮などの画像品質フィルターを適用します
- スキャンしたドキュメントを自動的にデスクして回転するために、方向補正を使用します
- 処理前に低解像度画像の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イベントがあり、マルチページドキュメントの処理進捗を追跡し、完了したページ数と全体の進行率についての更新を提供します。
IronOCRを使用してバッチOCRパイプラインでエラーをどのように分離できますか?
バッチOCRパイプラインでは、ファイルごとに例外を処理し、失敗のコンテキストを記録し、要約レポートを生成することでエラーを分離します。これにより、単一の失敗がバッチ全体を停止させないようにします。
IronOCRがOCRの精度を向上させるために提供する前処理ツールはどれですか?
IronOCRは、画像品質フィルター(シャープ化、ノイズ除去)、傾き補正によりスキャンされた文書の傾きを修正し、低解像度画像に対するDPI調整を行うことでOCRの精度を向上させる前処理ツールを提供しています。
IronOCRを使用して開発者が例外をどのように処理できるか?
開発者は、IronOcrInputExceptionやIronOcrProductExceptionなどの異なる例外タイプに対して具体的なキャッチブロックを実装し、各例外を適切な修復パスに導くことで例外を処理することができます。
IronOCRで非同期にOCR操作を実行することは可能ですか?
はい、IronOCRは非同期操作をReadAsyncを介してサポートしており、サービスやウェブアプリケーションでのブロックしない実行を可能にします。また、同期操作と同じtry-catch構造を使用します。
IronOCRで利用可能なロギングモードは何ですか?
IronOCRは、無効化されたロギングのためのNone、IDEでのデバッグ出力に対するDebugOutputWindow、サーバーサイド収集のためのFile、および完全な診断キャプチャのためのAllなど、さまざまなロギングモードをサポートしています。
OCRの信頼性スコアが低い場合はどうすればいいですか?
OCRの信頼性スコアが低い場合、問題は入力画像にある可能性があります。IronOCRの前処理ツールを使用して、画像品質フィルターや傾き補正を行い、入力画像の鮮明さを改善してください。
Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。