# C#에서 OCR 디버깅 방법
IronOCR는 소스에서 OCR 실패를 감지하고, 단어 및 문자 수준에서 인식 품질을 평가하며, 장기 실행 작업을 실시간으로 모니터링할 수 있게 합니다. 진단 파일 로깅, 유형 예외 계층 구조, 결과별 신뢰도 점수, 및 `OcrProgress` 이벤트 같은 내장 도구들은 프로덕션 파이프라인에서 이러한 워크플로우들을 지원합니다.
이 가이드에서는 진단 로깅 활성화, 유형별 예외 처리, 신뢰도 점수를 사용한 출력 유효성 검사, 실시간 작업 진행 상황 모니터링, 배치 파이프라인 오류 분리 등 각 기능에 대한 실제 작동 예제를 살펴봅니다.
*as-heading:2(빠른 시작: 전체 OCR 진단 로깅 활성화)*
첫 번째 `Read` 호출 전에 `LogFilePath` 및 `LoggingMode`을 `Installation` 클래스에 설정하십시오. Tesseract 초기화, 언어 팩 로딩 및 처리 세부 정보를 로그 파일에 기록하려면 두 가지 속성만 있으면 됩니다.
```cs
:title=Enable Full OCR Diagnostics in One Line
IronOcr.Installation.LogFilePath = "ocr.log"; IronOcr.Installation.LoggingMode = IronOcr.Installation.LoggingModes.All;
```
<div class="hsg-featured-snippet">
<h3>최소 워크플로우(5단계)</h3>
<ol>
<li><a class="js-modal-open" data-modal-id="trial-license-after-download" href="https://nuget.org/packages/IronOcr/">OCR 디버깅용 C# 라이브러리를 다운로드하세요.</a></li>
<li><code>LogFilePath</code> 쓰기 가능한 파일 경로로 설정하세요.</li>
<li>전체 진단 정보를 캡처하려면 <code>LoggingMode</code> <code>All</code> 로 설정하십시오.</li>
<li>OCR 작업을 실행하여 문제 재현</li>
<li>생성된 로그 파일을 검사하여 엔진 경고 및 처리 세부사항 확인</li>
</ol>
</div>
<br class="clear" />
## 진단 로깅을 활성화하는 방법은 무엇인가요?
[`Installation`](https://ironsoftware.com/csharp/ocr/object-reference/api/IronOcr.Installation.html) 클래스는 세 가지 로깅 제어를 노출합니다. 어떤 `Read` 메서드를 호출하기 전에 이것들을 설정하십시오.
```cs
:path=/static-assets/ocr/content-code-examples/how-to/debugging-enable-logging.cs
```
`LoggingMode`은 [`LoggingModes`](https://ironsoftware.com/csharp/ocr/object-reference/api/IronOcr.Installation.LoggingModes.html) 열거형에서 플래그 값을 수락합니다:
<div class="content__data-table" data-content-table>
<table>
<caption>표 1: 로깅 모드 옵션</caption>
<thead>
<tr><th>방법</th><th>출력 대상</th><th>사용 사례</th></tr>
</thead>
<tbody>
<tr><td><code>None</code></td><td>비활성화됨</td><td>외부 모니터링을 사용한 프로덕션</td></tr>
<tr><td><code>Debug</code></td><td>IDE 디버그 출력 창</td><td>로컬 개발</td></tr>
<tr><td><code>File</code></td><td><code>LogFilePath</code></td><td>서버 측 로그 수집</td></tr>
<tr><td><code>All</code></td><td>디버그 + 파일</td><td>전체 진단 캡처</td></tr>
</tbody>
</table>
</div>
`CustomLogger` 속성은 `Microsoft.Extensions.Logging.ILogger` 구현을 허용하여 OCR 진단을 Serilog, NLog, 또는 파이프라인의 다른 구조적 로깅 싱크로 전달할 수 있습니다. [`ClearLogFiles`](https://ironsoftware.com/csharp/ocr/object-reference/api/IronOcr.Installation.html)을 사용하여 실행 사이에 누적된 로그 데이터를 제거합니다.
로깅이 설정되었으므로 다음 단계는 IronOCR 발생할 수 있는 예외와 각 예외를 처리하는 방법을 이해하는 것입니다.
## IronOCR 어떤 예외를 발생시키나요?
IronOCR는 [`IronOcr.Exceptions`](https://ironsoftware.com/csharp/ocr/object-reference/api/IronOcr.Exceptions.html) 네임스페이스 아래에 유형화된 예외를 정의합니다. 포괄적인 차단 대신 이러한 오류를 구체적으로 포착하면 각 오류 유형을 올바른 복구 경로로 연결할 수 있습니다.
<div class="content__data-table" data-content-table>
<table>
<caption>표 2: IronOCR 예외 참조</caption>
<thead>
<tr><th>예외</th><th>일반적인 원인</th><th>수정 방법</th></tr>
</thead>
<tbody>
<tr><td><code>IronOcrInputException</code></td><td>손상되거나 지원되지 않는 이미지/PDF</td><td><code>OcrInput</code>로 로딩하기 전에 파일을 검증하세요</td></tr>
<tr><td><code>IronOcrProductException</code></td><td>OCR 실행 중 내부 엔진 오류</td><td>로그를 활성화하고 로그 출력을 확인하고 최신 NuGet 버전으로 업데이트</td></tr>
<tr><td><code>IronOcrDictionaryException</code></td><td>누락되었거나 손상된 <code>.traineddata</code> 언어 파일</td><td>언어 팩 NuGet 다시 설치하거나 <code>LanguagePackDirectory</code> 설정하세요.</td></tr>
<tr><td><code>IronOcrNativeException</code></td><td>네이티브 C++ 상호 운용 실패</td><td><a href="https://learn.microsoft.com/en-us/cpp/windows/latest-supported-vc-redist">Visual C++ 재배포 가능 패키지</a>를 설치하고 AVX 지원 확인</td></tr>
<tr><td><code>IronOcrLicensingException</code></td><td>누락되었거나 만료된 라이선스 키</td><td><code>Read</code> 호출하기 전에 <code>LicenseKey</code> 설정하세요.</td></tr>
<tr><td><code>LanguagePackException</code></td><td>언어 팩을 예상 경로에서 찾을 수 없습니다</td><td><code>LanguagePackDirectory</code>를 확인하거나 NuGet 언어 패키지를 재설치하세요</td></tr>
<tr><td><code>IronOcrAssemblyVersionMismatchException</code></td><td>부분 업데이트 후 어셈블리 버전이 일치하지 않음</td><td>NuGet 캐시를 지우고, 패키지를 복원하고, 모든 IronOCR 패키지가 일치하는지 확인하세요</td></tr>
</tbody>
</table>
</div>
다음 try-catch 블록을 사용하여 각 예외 유형을 개별적으로 처리하고, 조건부 로깅을 위해 예외 필터를 적용하십시오.
### 입력
`LoadPdf`을 통해 `OcrInput`에 로드된 IronOCR 솔루션에서 Acme Corporation으로의 단일 페이지 공급업체 송장입니다. 여기에는 네 가지 품목, 세금 및 총액이 포함되어 있어 각 예외 처리기가 현실적인 연습을 할 수 있을 만큼 충분한 텍스트 다양성을 제공합니다.
<iframe loading="lazy" src="/static-assets/ocr/how-to/debugging/invoice_scan.pdf" width="100%" height="400px"></iframe>
<p style="text-align: center; font-style: italic; color: #555; font-size: 13px; margin-top: 6px;">invoice_scan.pdf: 공급업체 송장(#INV-2024-7829)은 각 유형의 예외 처리기를 순차적으로 시연하는 데 사용됩니다.</p>
```cs
:path=/static-assets/ocr/content-code-examples/how-to/debugging-exception-handling.cs
```
### 산출
#### 성공 결과
송장이 깔끔하게 로드되고 엔진은 문자 수와 신뢰도 점수를 반환합니다.
<div class="content-img-align-center">
<div class="center-image-wrapper">
<img src="/static-assets/ocr/how-to/debugging/exception-handling-success.png" alt="터미널 출력에는 invoice_scan.pdf 파일의 OCR 읽기가 성공적으로 완료되었으며, 문자 수와 신뢰도 점수가 표시됩니다." class="img-responsive add-shadow" />
</div>
</div>
#### 출력 실패
<div class="content-img-align-center">
<div class="center-image-wrapper">
<img src="/static-assets/ocr/how-to/debugging/exception-handling-failed.png" alt="누락된 PDF 파일을 로드할 때 발생한 예외를 보여주는 터미널 출력" class="img-responsive add-shadow" />
</div>
</div>
캐치 블록을 가장 구체적인 것부터 가장 일반적인 것 순으로 정렬하세요. `when` 조항은 [AVX 관련 오류](https://ironsoftware.com/csharp/ocr/troubleshooting/sehexception-avx-support/)를 필터링하며 관련 없는 네이티브 오류를 잡지 않습니다. 각 핸들러는 예외 메시지를 기록합니다. 포괄적인 블록은 사후 분석을 위해 스택 추적 정보도 캡처합니다.
올바른 예외를 포착하면 무언가 잘못되었다는 것을 알 수 있지만, 엔진이 성공적으로 작동했을 때 얼마나 잘 작동했는지는 알 수 없습니다. 이를 위해서는 신뢰도 점수를 사용하십시오.
## 신뢰도 점수를 사용하여 OCR 출력 결과를 검증하는 방법은 무엇인가요?
[`OcrResult`](https://ironsoftware.com/csharp/ocr/object-reference/api/IronOcr.OcrResult.html)의 각 인스턴스는 0과 1 사이의 값을 가졌으며 인식된 모든 문자에 걸쳐 엔진의 통계적 확신도를 나타내는 `Confidence` 속성을 노출합니다. 이 기능은 [문서](https://ironsoftware.com/csharp/ocr/object-reference/api/IronOcr.OcrResult.html) , [페이지](https://ironsoftware.com/csharp/ocr/object-reference/api/IronOcr.OcrResult.Page.html) ,[단락](https://ironsoftware.com/csharp/ocr/object-reference/api/IronOcr.OcrResult.Paragraph.html) , [단어](https://ironsoftware.com/csharp/ocr/object-reference/api/IronOcr.OcrResult.Word.html) ,[문자](https://ironsoftware.com/csharp/ocr/object-reference/api/IronOcr.OcrResult.Character.html) 등 결과 계층 구조의 모든 수준에서 접근할 수 있습니다.
임계값 기반 게이트 패턴을 사용하여 품질이 낮은 결과가 하위 단계로 전파되는 것을 방지하십시오.
### 입력
`LoadImage`에 로드된 품목이 나열된 세열의 영수증과 바코드를 포함하는 상품 영수증입니다. 좁은 폭, 고정폭 글꼴, 흐릿한 인쇄체는 단어별 신뢰도 임계값을 측정하는 실용적인 스트레스 테스트 도구로 활용될 수 있습니다.
<div class="content-img-align-center">
<div class="center-image-wrapper" style="max-width: 320px; margin: 0 auto;">
<img src="/static-assets/ocr/how-to/debugging/receipt.png" alt="FoodMart에서 발행한 품목별 구매 내역, 총액, 적립 포인트가 표시된 감열식 영수증 샘플입니다. 이 이미지는 OCR 입력 자료로 사용되었습니다." class="img-responsive add-shadow" />
</div>
</div>
<p style="text-align: center; font-style: italic; color: #555; font-size: 13px; margin-top: 6px;">receipt.png: 수신확인 이미지에 대해 임계값 게이트 신뢰도 검증 및 단어별 정확성 분석을 보여주는 열 발열 영수증 스캔</p>
```cs
:path=/static-assets/ocr/content-code-examples/how-to/debugging-confidence-scoring.cs
```
### 산출
<div class="content-img-align-center">
<div class="center-image-wrapper">
<img src="/static-assets/ocr/how-to/debugging/confidence-scoring-output.png" alt="터미널 출력에는 영수증 이미지에 대한 신뢰도 점수, 승인/플래그/거부 결정, 그리고 단어별 낮은 신뢰도 항목에 대한 상세 분석 정보가 표시됩니다." class="img-responsive add-shadow" />
</div>
</div>
이 패턴은 OCR이 데이터 입력, 송장 처리 또는 준수 워크플로에 피드되는 파이프라인에서 필수적입니다. 단어 단위 분석을 통해 원본 이미지의 어느 부분이 화질 저하를 유발했는지 정확하게 파악할 수 있습니다. 그런 다음 [이미지 품질 필터](https://ironsoftware.com/csharp/ocr/how-to/image-quality-correction/) 나 [방향 보정을](https://ironsoftware.com/csharp/ocr/how-to/image-orientation-correction/) 적용하고 다시 처리할 수 있습니다. 신뢰 점수에 대한 자세한 내용은 [신뢰 수준 사용법](https://ironsoftware.com/csharp/ocr/how-to/tesseract-result-confidence/)을 참조하세요.
장기적인 업무에서는 자신감만으로는 충분하지 않습니다. 엔진이 여전히 진행 중인지 알 필요가 있으며, 이는 `OcrProgress` 이벤트가 도움이 됩니다.
## OCR 진행 상황을 실시간으로 모니터링하려면 어떻게 해야 하나요?
다중 페이지 문서의 경우, 각 페이지 완료 후 `IronTesseract`에서 `OcrProgress` 이벤트가 발생합니다. `OcrProgressEventArgs` 객체는 진행률 퍼센트, 경과 시간, 전체 페이지 수 및 완료된 페이지를 노출합니다. 이 예시에서는 경영진 요약, 매출 분석 및 운영 지표를 포함하는 구조화된 비즈니스 문서인 3페이지 분량의 분기 보고서를 입력으로 사용합니다.
### 입력
`LoadPdf`에 로드된 3페이지 짜리 2024년 1분기 금융 보고서입니다. 1페이지는 KPI 지표를 포함한 요약 보고서를, 2페이지는 제품 라인 및 지역별 매출표를, 3페이지는 운영 처리량을 다룹니다. 각 페이지 유형별로 페이지 처리 시간이 다르며, 이는 진행 상황 콜백에서 확인할 수 있습니다.
<iframe loading="lazy" src="/static-assets/ocr/how-to/debugging/quarterly_report.pdf" width="100%" height="400px"></iframe>
<p style="text-align: center; font-style: italic; color: #555; font-size: 13px; margin-top: 6px;">quarterly_report.pdf: 2024년 1분기 재무 보고서(3페이지, 요약, 매출 분석, 운영 지표)로, 페이지별 실시간 `OcrProgress` 콜백을 시연하는 데 사용됩니다.</p>
```cs
:path=/static-assets/ocr/content-code-examples/how-to/debugging-progress-monitoring.cs
```
### 산출
<div class="content-img-align-center">
<div class="center-image-wrapper">
<img src="/static-assets/ocr/how-to/debugging/progress-monitoring-output.png" alt="터미널 출력에는 3페이지 PDF 파일의 페이지별 OcrProgress 이벤트 콜백, 완료율 및 경과 시간이 표시됩니다." class="img-responsive add-shadow" />
</div>
</div>
이 이벤트를 로깅 인프라에 연결하여 OCR 작업 지속 시간을 추적하고 중단을 감지하세요. 경과 시간이 임계값을 초과했는데도 진행률이 증가하지 않으면 파이프라인에서 해당 작업을 조사 대상으로 표시할 수 있습니다. 이는 단일 잘못된 페이지가 전체 작업을 정지시킬 수 있는 [배치 PDF 처리](https://ironsoftware.com/csharp/ocr/how-to/input-pdfs/)에 특히 유용합니다.
진행 상황 모니터링은 실행 상태를 보여주지만, 파일 수준 오류가 발생하면 이를 격리하지 않을 경우 전체 배치 작업이 중단될 수 있습니다.
## 일괄 OCR 파이프라인에서 오류를 어떻게 처리해야 하나요?
실제 운영 환경에서는 단일 파일 오류로 인해 전체 배치 처리가 중단되어서는 안 됩니다. 파일별로 오류를 분리하고, 실패 상황을 맥락과 함께 기록하며, 마지막에 요약 보고서를 생성합니다. 예제는 송장, 구매 주문서, 서비스 계약을 포함하는 스캔 문서 폴더를 처리하며, 고의로 오류 경로를 트리거하도록 손상된 파일을 포함합니다. 대표적인 예시는 아래와 같습니다.
### 입력
`Directory.GetFiles`에 전달된 PDF 폴더 - 송장, 구매 주문서, 서비스 계약서 및 고의로 손상된 파일입니다. 아래 두 가지 대표 샘플은 파이프라인이 한 번 실행에서 처리하는 문서의 다양성을 보여줍니다.
<div class="competitors-section__wrapper-even-1">
<div class="competitors__card" style="width: 48%;">
<iframe loading="lazy" src="/static-assets/ocr/how-to/debugging/batch-scan-01.pdf" width="100%" height="380px"></iframe>
<p class="competitors__download-link" style="color: #181818; font-style: italic;">batch-scan-01.pdf: Bright Horizon Ltd. 송장(INV-2024-001) - OCR 검사 성공.</p>
</div>
<div class="competitors__card" style="width: 48%;">
<iframe loading="lazy" src="/static-assets/ocr/how-to/debugging/batch-scan-02.pdf" width="100%" height="380px"></iframe>
<p class="competitors__download-link" style="color: #181818; font-style: italic;">batch-scan-02.pdf: TechSupply Inc. 구매 주문서(PO-2024-042) - 동일 실행에서 두 번째 문서 유형.</p>
</div>
</div>
```cs
:path=/static-assets/ocr/content-code-examples/how-to/debugging-batch-pipeline.cs
```
### 산출
<div class="content-img-align-center">
<div class="center-image-wrapper">
<img src="/static-assets/ocr/how-to/debugging/batch-pipeline-output.png" alt="터미널 출력에는 파일별 문자 수, 신뢰도 점수, 손상된 PDF에서 발생한 오류 1개, 요약 정보가 포함된 배치 파이프라인 결과가 표시됩니다." class="img-responsive add-shadow" />
</div>
</div>
외부 예외 처리 블록은 공유 저장소의 네트워크 시간 초과, 권한 문제 또는 대용량 TIFF 파일의 메모리 부족 상황과 같은 예기치 않은 오류를 처리합니다. 각 오류는 파일 경로와 오류 메시지를 요약 보고서에 기록하며, 루프는 나머지 파일을 계속 처리합니다. `batch_debug.log`의 로그 파일은 내부 진단을 트리거하는 모든 파일에 대한 엔진 수준의 세부 정보를 캡처합니다.
서비스 또는 웹 응용 프로그램에서 블록 없는 실행을 위해, IronOCR은 [`ReadAsync`](https://ironsoftware.com/csharp/ocr/how-to/async/)를 지원하며, 동일한 try-catch 구조를 사용합니다.
파이프라인이 오류 없이 실행되었지만 추출된 텍스트가 여전히 잘못된 경우, 근본 원인은 거의 항상 코드보다는 이미지 품질에 있습니다. 이 문제를 해결하는 방법은 다음과 같습니다.
## OCR 정확도 문제를 어떻게 해결하나요?
신뢰도 점수가 지속적으로 낮다면 문제는 OCR 엔진이 아니라 원본 이미지에 있습니다. IronOCR 이러한 문제를 해결하기 위한 전처리 도구를 제공합니다.
- 선명도, 노이즈 제거, 팽창, 침식 등의 [이미지 품질 필터를](https://ironsoftware.com/csharp/ocr/how-to/image-quality-correction/) 적용하여 텍스트 가독성을 향상시키세요.
- [방향 보정 기능을](https://ironsoftware.com/csharp/ocr/how-to/image-orientation-correction/) 사용하여 스캔한 문서의 기울기를 자동으로 보정하고 회전시키세요.
- 저해상도 이미지의 경우 처리 전에 [DPI 설정을 조정하십시오.](https://ironsoftware.com/csharp/ocr/how-to/dpi-setting/)
- 복잡한 레이아웃에서 텍스트 영역을 감지하고 분리하기 위해 [컴퓨터 비전 기술을](https://ironsoftware.com/csharp/ocr/how-to/computer-vision/) 활용합니다.
[IronOCR 유틸리티를](https://ironsoftware.com/csharp/ocr/troubleshooting/ironocr-utility/) 사용하면 필터 조합을 시각적으로 테스트하고 최적의 C# 구성을 내보낼 수 있습니다.
배포 관련 문제의 경우, IronOCR [Azure Functions](https://ironsoftware.com/csharp/ocr/troubleshooting/azure-functions-deployment/) , [Docker 및 Linux](https://ironsoftware.com/csharp/ocr/troubleshooting/libgdiplus/) , 그리고 [일반적인 환경 설정](https://ironsoftware.com/csharp/ocr/troubleshooting/general-troubleshooting-ocr/) 에 대한 전용 문제 해결 가이드를 제공합니다.
## 다음엔 어디로 가야 할까요?
이제 런타임 시 IronOCR 디버깅 방법을 이해했으니 다음을 살펴보세요.
- [OCR 결과 구조 및 메타데이터](https://ironsoftware.com/csharp/ocr/how-to/read-results/) (페이지, 블록, 단락, 단어, 좌표 등) 탐색
- 결과 계층 구조의 모든 단계에서 [신뢰도 점수](https://ironsoftware.com/csharp/ocr/how-to/tesseract-result-confidence/) 이해하기
- `ReadAsync`와 함께 [비동기 및 멀티스레딩](https://ironsoftware.com/csharp/ocr/how-to/async/)을 사용하여 높은 처리량 파이프라인을 구축
- 전체 속성 목록을 위한 [전체 API 참조](https://ironsoftware.com/csharp/ocr/object-reference/api/) 탐색
프로덕션 사용을 위해, 워터마크 제거 및 전체 기능에 액세스하려면 [라이센스 획득](https://ironsoftware.com/csharp/ocr/licensing/)을 기억하세요.
IronOCR는 소스에서 OCR 실패를 감지하고, 단어 및 문자 수준에서 인식 품질을 평가하며, 장기 실행 작업을 실시간으로 모니터링할 수 있게 합니다. 진단 파일 로깅, 유형 예외 계층 구조, 결과별 신뢰도 점수, 및 OcrProgress 이벤트 같은 내장 도구들은 프로덕션 파이프라인에서 이러한 워크플로우들을 지원합니다.
이 가이드에서는 진단 로깅 활성화, 유형별 예외 처리, 신뢰도 점수를 사용한 출력 유효성 검사, 실시간 작업 진행 상황 모니터링, 배치 파이프라인 오류 분리 등 각 기능에 대한 실제 작동 예제를 살펴봅니다.
빠른 시작: 전체 OCR 진단 로깅 활성화
첫 번째 Read 호출 전에 LogFilePath 및 LoggingMode을 Installation 클래스에 설정하십시오. Tesseract 초기화, 언어 팩 로딩 및 처리 세부 정보를 로그 파일에 기록하려면 두 가지 속성만 있으면 됩니다.
Installation 클래스는 세 가지 로깅 제어를 노출합니다. 어떤 Read 메서드를 호출하기 전에 이것들을 설정하십시오.
using IronOcr;// Write logs to a specific fileInstallation.LogFilePath = "logs/ocr_diagnostics.log";// Enable all logging channels: file + debug outputInstallation.LoggingMode = Installation.LoggingModes.All;// Or pipe logs into your existing ILogger pipelineInstallation.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;
ImportsIronOcr' Write logs to a specific fileInstallation.LogFilePath = "logs/ocr_diagnostics.log"' Enable all logging channels: file + debug outputInstallation.LoggingMode = Installation.LoggingModes.All' Or pipe logs into your existing ILogger pipelineInstallation.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 = myLoggerInstance
CustomLogger 속성은 Microsoft.Extensions.Logging.ILogger 구현을 허용하여 OCR 진단을 Serilog, NLog, 또는 파이프라인의 다른 구조적 로깅 싱크로 전달할 수 있습니다. ClearLogFiles을 사용하여 실행 사이에 누적된 로그 데이터를 제거합니다.
로깅이 설정되었으므로 다음 단계는 IronOCR 발생할 수 있는 예외와 각 예외를 처리하는 방법을 이해하는 것입니다.
IronOCR 어떤 예외를 발생시키나요?
IronOCR는 IronOcr.Exceptions 네임스페이스 아래에 유형화된 예외를 정의합니다. 포괄적인 차단 대신 이러한 오류를 구체적으로 포착하면 각 오류 유형을 올바른 복구 경로로 연결할 수 있습니다.
NuGet 캐시를 지우고, 패키지를 복원하고, 모든 IronOCR 패키지가 일치하는지 확인하세요
다음 try-catch 블록을 사용하여 각 예외 유형을 개별적으로 처리하고, 조건부 로깅을 위해 예외 필터를 적용하십시오.
입력
LoadPdf을 통해 OcrInput에 로드된 IronOCR 솔루션에서 Acme Corporation으로의 단일 페이지 공급업체 송장입니다. 여기에는 네 가지 품목, 세금 및 총액이 포함되어 있어 각 예외 처리기가 현실적인 연습을 할 수 있을 만큼 충분한 텍스트 다양성을 제공합니다.
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 formatConsole.Error.WriteLine($"Input error: {ex.Message}");}catch (IronOcrDictionaryException ex){ // Language pack missing — common in containerized deploymentsConsole.Error.WriteLine($"Language pack error: {ex.Message}");}catch (IronOcrNativeException ex) when (ex.Message.Contains("AVX")){ // CPU does not support AVX instructionsConsole.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 errorsConsole.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}");
}
ImportsIronOcrImportsIronOcr.ExceptionsDim ocr = New IronTesseract()TryUsing input = New OcrInput() input.LoadPdf("invoice_scan.pdf") Dim result AsOcrResult = ocr.Read(input)Console.WriteLine($"Text: {result.Text}")Console.WriteLine($"Confidence: {result.Confidence:P1}")EndUsingCatch ex AsIronOcrInputException ' File could not be loaded — corrupt, locked, or unsupported formatConsole.Error.WriteLine($"Input error: {ex.Message}")Catch ex AsIronOcrDictionaryException ' Language pack missing — common in containerized deploymentsConsole.Error.WriteLine($"Language pack error: {ex.Message}")Catch ex AsIronOcrNativeExceptionWhen ex.Message.Contains("AVX") ' CPU does not support AVX instructionsConsole.Error.WriteLine($"Hardware incompatibility: {ex.Message}")Catch ex AsIronOcrLicensingExceptionConsole.Error.WriteLine("License key is missing or invalid.")Catch ex AsIronOcrProductException ' Catch-all for other IronOCR engine errorsConsole.Error.WriteLine($"OCR engine error: {ex.Message}")Console.Error.WriteLine($"Stack trace: {ex.StackTrace}")EndTry
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 Try
산출
성공 결과
송장이 깔끔하게 로드되고 엔진은 문자 수와 신뢰도 점수를 반환합니다.
출력 실패
캐치 블록을 가장 구체적인 것부터 가장 일반적인 것 순으로 정렬하세요. when 조항은 AVX 관련 오류를 필터링하며 관련 없는 네이티브 오류를 잡지 않습니다. 각 핸들러는 예외 메시지를 기록합니다. 포괄적인 블록은 사후 분석을 위해 스택 추적 정보도 캡처합니다.
올바른 예외를 포착하면 무언가 잘못되었다는 것을 알 수 있지만, 엔진이 성공적으로 작동했을 때 얼마나 잘 작동했는지는 알 수 없습니다. 이를 위해서는 신뢰도 점수를 사용하십시오.
신뢰도 점수를 사용하여 OCR 출력 결과를 검증하는 방법은 무엇인가요?
OcrResult의 각 인스턴스는 0과 1 사이의 값을 가졌으며 인식된 모든 문자에 걸쳐 엔진의 통계적 확신도를 나타내는 Confidence 속성을 노출합니다. 이 기능은 문서 , 페이지 ,단락 , 단어 ,문자 등 결과 계층 구조의 모든 수준에서 접근할 수 있습니다.
임계값 기반 게이트 패턴을 사용하여 품질이 낮은 결과가 하위 단계로 전파되는 것을 방지하십시오.
입력
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 decisionif (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 diagnosticsforeach (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})");
}
}
ImportsIronOcrDim ocr As New IronTesseract()Using input As New OcrInput() input.LoadImage("receipt.png") Dim result AsOcrResult = ocr.Read(input) Dim confidence AsDouble = result.ConfidenceConsole.WriteLine($"Overall confidence: {confidence:P1}") ' Threshold-gated decision If confidence >= 0.9 ThenConsole.WriteLine("ACCEPT — high confidence, processing result.")ProcessResult(result.Text) ElseIf confidence >= 0.7 ThenConsole.WriteLine("FLAG — moderate confidence, queuing for review.")QueueForReview(result.Text, confidence) ElseConsole.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.PagesConsole.WriteLine($" Page {page.PageNumber}: {page.Confidence:P1}") Dim lowConfidenceWords = page.Words _ .Where(Function(w) w.Confidence < 0.7) _ .ToList() For Each word In lowConfidenceWordsConsole.WriteLine($" Low-confidence word: ""{word.Text}"" ({word.Confidence:P1})") Next NextEndUsing
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 Using
산출
이 패턴은 OCR이 데이터 입력, 송장 처리 또는 준수 워크플로에 피드되는 파이프라인에서 필수적입니다. 단어 단위 분석을 통해 원본 이미지의 어느 부분이 화질 저하를 유발했는지 정확하게 파악할 수 있습니다. 그런 다음 이미지 품질 필터 나 방향 보정을 적용하고 다시 처리할 수 있습니다. 신뢰 점수에 대한 자세한 내용은 신뢰 수준 사용법을 참조하세요.
장기적인 업무에서는 자신감만으로는 충분하지 않습니다. 엔진이 여전히 진행 중인지 알 필요가 있으며, 이는 OcrProgress 이벤트가 도움이 됩니다.
OCR 진행 상황을 실시간으로 모니터링하려면 어떻게 해야 하나요?
다중 페이지 문서의 경우, 각 페이지 완료 후 IronTesseract에서 OcrProgress 이벤트가 발생합니다. OcrProgressEventArgs 객체는 진행률 퍼센트, 경과 시간, 전체 페이지 수 및 완료된 페이지를 노출합니다. 이 예시에서는 경영진 요약, 매출 분석 및 운영 지표를 포함하는 구조화된 비즈니스 문서인 3페이지 분량의 분기 보고서를 입력으로 사용합니다.
입력
LoadPdf에 로드된 3페이지 짜리 2024년 1분기 금융 보고서입니다. 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}");
ImportsIronOcrDim 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 SubUsing input As New OcrInput() input.LoadPdf("quarterly_report.pdf") Dim result AsOcrResult = ocr.Read(input)Console.WriteLine($"Finished in {result.Pages.Count()} pages, confidence: {result.Confidence:P1}")EndUsing
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 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) - 동일 실행에서 두 번째 문서 유형.
ImportsIronOcrImportsIronOcr.ExceptionsDim ocr As New IronTesseract()Installation.LogFilePath = "batch_debug.log"Installation.LoggingMode = Installation.LoggingModes.FileDim files AsString() = Directory.GetFiles("scans/", "*.pdf")Dim succeeded AsInteger = 0, failed AsInteger = 0Dim totalConfidence AsDouble = 0Dim failures As New List(Of (FileAsString, ErrorAsString))()For Each file AsStringIn filesTryUsing input As New OcrInput() input.LoadPdf(file) Dim result AsOcrResult = ocr.Read(input) totalConfidence += result.Confidence succeeded += 1Console.WriteLine($"OK: {Path.GetFileName(file)} — {result.Confidence:P1}")EndUsingCatch ex AsIronOcrInputException failed += 1 failures.Add((file, $"Input error: {ex.Message}"))Console.Error.WriteLine($"FAIL: {Path.GetFileName(file)} — {ex.Message}")Catch ex AsIronOcrProductException failed += 1 failures.Add((file, $"Engine error: {ex.Message}"))Console.Error.WriteLine($"FAIL: {Path.GetFileName(file)} — {ex.Message}")Catch ex AsException failed += 1 failures.Add((file, $"Unexpected: {ex.Message}"))Console.Error.WriteLine($"FAIL: {Path.GetFileName(file)} — {ex.GetType().Name}: {ex.Message}")EndTryNext' Summary reportConsole.WriteLine(vbCrLf & "--- Batch Summary ---")Console.WriteLine($"Total: {files.Length} | Passed: {succeeded} | Failed: {failed}")If succeeded > 0 ThenConsole.WriteLine($"Average confidence: {totalConfidence / succeeded:P1}")End IfFor Each failure In failuresConsole.WriteLine($" {Path.GetFileName(failure.File)}: {failure.Error}")Next
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}")
Next
산출
외부 예외 처리 블록은 공유 저장소의 네트워크 시간 초과, 권한 문제 또는 대용량 TIFF 파일의 메모리 부족 상황과 같은 예기치 않은 오류를 처리합니다. 각 오류는 파일 경로와 오류 메시지를 요약 보고서에 기록하며, 루프는 나머지 파일을 계속 처리합니다. batch_debug.log의 로그 파일은 내부 진단을 트리거하는 모든 파일에 대한 엔진 수준의 세부 정보를 캡처합니다.
서비스 또는 웹 응용 프로그램에서 블록 없는 실행을 위해, IronOCR은 ReadAsync를 지원하며, 동일한 try-catch 구조를 사용합니다.
파이프라인이 오류 없이 실행되었지만 추출된 텍스트가 여전히 잘못된 경우, 근본 원인은 거의 항상 코드보다는 이미지 품질에 있습니다. 이 문제를 해결하는 방법은 다음과 같습니다.
OCR 정확도 문제를 어떻게 해결하나요?
신뢰도 점수가 지속적으로 낮다면 문제는 OCR 엔진이 아니라 원본 이미지에 있습니다. IronOCR 이러한 문제를 해결하기 위한 전처리 도구를 제공합니다.
선명도, 노이즈 제거, 팽창, 침식 등의 이미지 품질 필터를 적용하여 텍스트 가독성을 향상시키세요.
커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.