C#에서 OCR 디버깅 방법
IronOCR는 소스에서 OCR 실패를 감지하고, 단어 및 문자 수준에서 인식 품질을 평가하며, 실시간으로 장시간 작업을 모니터링할 수 있습니다. 진단 파일 로깅, 유형화된 예외 계층 구조, 결과별 신뢰도 점수 매기기, OcrProgress 이벤트와 같은 내장 도구가 프로덕션 파이프라인에서 이러한 워크플로우를 지원합니다.
이 가이드에서는 진단 로깅 활성화, 유형별 예외 처리, 신뢰도 점수를 사용한 출력 유효성 검사, 실시간 작업 진행 상황 모니터링, 배치 파이프라인 오류 분리 등 각 기능에 대한 실제 작동 예제를 살펴봅니다.
빠른 시작: 전체 OCR 진단 로깅 활성화첫 번째 Read 호출 전에 LogFilePath과 LoggingMode을 Installation 클래스에 설정하십시오. Tesseract 초기화, 언어 팩 로딩 및 처리 세부 정보를 로그 파일에 기록하려면 두 가지 속성만 있으면 됩니다.
-
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쓰기 가능한 파일 경로로 설정하세요.- 전체 진단 정보를 캡처하려면
LoggingModeAll로 설정하십시오. - 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 enum에서 플래그 값을 수용합니다:
| 방법 | 출력 대상 | 사용 사례 |
|---|---|---|
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 솔루션에서 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산출
성공 결과
송장이 깔끔하게 로드되고 엔진은 문자 수와 신뢰도 점수를 반환합니다.

출력 실패

캐치 블록을 가장 구체적인 것부터 가장 일반적인 것 순으로 정렬하세요. 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 진행 상황을 실시간으로 모니터링하려면 어떻게 해야 하나요?
여러 페이지 문서의 경우 OcrProgress 이벤트가 IronTesseract에서 각 페이지가 완료된 후 실행됩니다. OcrProgressEventsArgs 객체는 진행률 백분율, 경과 시간, 총 페이지 수 및 완료된 페이지를 노출합니다. 이 예시에서는 경영진 요약, 매출 분석 및 운영 지표를 포함하는 구조화된 비즈니스 문서인 3페이지 분량의 분기 보고서를 입력으로 사용합니다.
입력
LoadPdf를 통해 로드된 2024년 1분기 재무 보고서 (3페이지) 페이지 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 폴더 - 인보이스, 구매 주문서, 서비스 계약 및 의도적으로 손상된 파일 하나. 아래의 두 가지 대표 샘플은 파이프라인이 단일 실행에서 처리하는 문서 다양성을 보여줍니다.
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산출

외부 예외 처리 블록은 공유 저장소의 네트워크 시간 초과, 권한 문제 또는 대용량 TIFF 파일의 메모리 부족 상황과 같은 예기치 않은 오류를 처리합니다. 각 오류는 파일 경로와 오류 메시지를 요약 보고서에 기록하며, 루프는 나머지 파일을 계속 처리합니다. batch_debug.log의 로그 파일은 내부 진단을 유발하는 모든 파일에 대한 엔진 수준 세부 정보를 캡처합니다.
서비스나 웹 애플리케이션에서의 비차단 실행을 위해 IronOCR는 동일한 try-catch 구조를 사용하는 ReadAsync을 지원합니다.
파이프라인이 오류 없이 실행되었지만 추출된 텍스트가 여전히 잘못된 경우, 근본 원인은 거의 항상 코드보다는 이미지 품질에 있습니다. 이 문제를 해결하는 방법은 다음과 같습니다.
OCR 정확도 문제를 어떻게 해결하나요?
신뢰도 점수가 지속적으로 낮다면 문제는 OCR 엔진이 아니라 원본 이미지에 있습니다. IronOCR 이러한 문제를 해결하기 위한 전처리 도구를 제공합니다.
- 선명화, 잡음 제거, 팽창 및 부식을 통한 이미지 품질 필터 적용으로 텍스트 명료도 향상
- 스캔된 문서를 자동으로 기울이고 회전시키는 방향 수정 사용
- 처리 전에 저해상도 이미지의 DPI 설정 조정
- 복잡한 레이아웃에서 텍스트 영역을 감지하고 분리하기 위한 컴퓨터 비전 사용
- IronOCR 유틸리티는 필터 조합을 시각적으로 테스트하고 최적의 C# 구성을 내보낼 수 있게 합니다
배포 관련 문제의 경우, IronOCR는 Azure Functions, Docker 및 Linux, 그리고 일반 환경 설정에 대한 전용 문제 해결 가이드를 유지 관리합니다.
다음엔 어디로 가야 할까요?
이제 런타임 시 IronOCR 디버깅 방법을 이해했으니 다음을 살펴보세요.
- 페이지, 블록, 단락, 단어 및 좌표를 포함한 OCR 결과 구조 및 메타데이터 탐색
- 결과 계층의 모든 수준에서 신뢰도 점수 이해
- 고처리량 파이프라인을 위한
ReadAsync과 함께 비동기 및 다중 스레딩 사용 - 전체 속성 목록에 대한 전체 API 참조 탐색
프로덕션 사용을 위해 워터마크 제거 및 전체 기능 액세스를 위해 라이선스를 획득하는 것을 잊지 마세요.
자주 묻는 질문
IronOCR에서 진단 로깅을 활성화하려면 어떻게 해야 하나요?
Read 호출 전에 Installation 클래스에서 LogFilePath 및 LoggingMode 속성을 설정하여 IronOCR에서 진단 로깅을 활성화 합니다. 이 설정은 Tesseract 초기화 및 언어 팩 로딩과 같은 세부 사항을 캡처합니다.
IronOCR에서 발생할 수 있는 일반적인 예외는 무엇인가요?
일반적인 예외로는 손상된 이미지에 대한 IronOcrInputException, 내부 엔진 오류에 대한 IronOcrProductException, 누락된 언어 파일에 대한 IronOcrDictionaryException, 누락된 라이선스 키에 대한 IronOcrLicensingException이 있습니다.
IronOCR는 신뢰도 점수를 어떻게 처리하나요?
IronOCR는 인식된 모든 문자의 통계를 평균하여 나타내는 Confidence 속성을 제공합니다. 이를 사용하여 OCR 출력을 검증하고 추가 처리를 하기 전에 낮은 신뢰도의 결과를 필터링할 수 있습니다.
IronOCR는 실시간으로 OCR 진행 상황을 모니터링할 수 있나요?
네, IronOCR는 OcrProgress 이벤트를 통해 여러 페이지 문서 처리를 추적하고 완료된 페이지의 수와 전체 진행률을 업데이트합니다.
IronOCR를 사용하여 배치 OCR 파이프라인에서 오류를 어떻게 격리할 수 있나요?
배치 OCR 파이프라인에서 오류는 파일마다 예외를 처리하고 오류 컨텍스트를 기록하며 요약 보고서를 생성하여 격리됩니다. 이는 단일 오류가 전체 배치를 중단시키지 않도록 보장합니다.
IronOCR는 OCR 정확도를 향상시키기 위해 어떤 사전 처리 도구를 제공하나요?
IronOCR는 OCR 정확도를 향상시키기 위해 이미지 품질 필터 (선명화, 노이즈 제거), 스캔 문서의 비뚤림을 조정하는 방향 교정 및 저해상도 이미지의 DPI 조정을 위한 사전 처리 도구를 제공합니다.
개발자가 IronOCR를 사용하여 예외를 어떻게 처리할 수 있나요?
개발자는 IronOcrInputException 및 IronOcrProductException과 같은 다양한 예외 유형에 대한 특정 catch 블록을 구현하여 IronOCR를 사용하여 예외를 처리하고 각각을 적절한 해결 경로로 유도할 수 있습니다.
IronOCR로 비동기 방식으로 OCR 작업을 실행하는 것이 가능한가요?
네, IronOCR는 ReadAsync를 통해 비동기 작업을 지원하여 서비스나 웹 애플리케이션에서 비차단 실행을 가능하게 하며 동기 작업과 동일한 try-catch 구조를 사용합니다.
IronOCR에서는 어떤 로깅 모드가 가능한가요?
IronOCR는 None로 로깅 비활성화, DebugOutputWindow로 IDE의 디버그 출력, File로 서버 측 수집, 그리고 All로 전체 진단 캡처와 같은 다양한 로깅 모드를 지원합니다.
OCR 신뢰도 점수가 낮으면 어떻게 해야 하나요?
OCR 신뢰도 점수가 낮으면 문제는 원본 이미지에 있을 수 있습니다. IronOCR의 이미지 품질 필터와 방향 교정과 같은 사전 처리 도구를 사용하여 원본 이미지의 선명도를 개선하십시오.
커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.