在C#中使用IronOCR將文本突出顯示為圖像
IronOCR的HighlightTextAndSaveAsImages方法通過在檢測到的文本(字符、單詞、行或段落)周圍繪制邊框來可視化OCR結果,並將它們保存為診斷圖像,使開發人員能夠驗證OCR準確性並調試識別問題。
可視化 OCR 結果包括在引擎偵測到的影像中特定文字元素周圍渲染邊界框。 此流程會在個別字元、字詞、行或段落的精確位置上覆蓋明顯的高亮點,提供清晰的認知內容地圖。
此視覺化回饋對於調試和驗證 OCR 輸出的準確性至關重要,可顯示軟體已識別出哪些內容以及在哪些地方出錯。 在處理複雜的文件或排除識別問題時,可視化高亮顯示成為重要的診斷工具。
本文演示了IronOCR的HighlightTextAndSaveAsImages方法的診斷能力。 此功能可強調特定的文字部分,並將其儲存為影像以供驗證。 無論是建立文件處理系統、執行品質控制措施,或是驗證您的 OCR 實作,此功能都能立即提供 OCR 引擎偵測到的視覺回饋。
此片段示範了 IronOCR 的用法:載入 PDF,並高亮顯示文件中的每個字,將結果儲存為影像。 只需一行即可獲得 OCR 結果的視覺回饋。
-
1使用 IronOCR 安裝 NuGet Package Manager
-
2複製並運行這段程式碼。
new IronOcr.OcrInput().LoadPdf("document.pdf").HighlightTextAndSaveAsImages(new IronOcr.IronTesseract(), "highlight_page_", IronOcr.ResultHighlightType.Word);Dim ocrInput As New IronOcr.OcrInput() ocrInput.LoadPdf("document.pdf").HighlightTextAndSaveAsImages(New IronOcr.IronTesseract(), "highlight_page_", IronOcr.ResultHighlightType.Word)Dim ocrInput As New IronOcr.OcrInput() ocrInput.LoadPdf("document.pdf").HighlightTextAndSaveAsImages(New IronOcr.IronTesseract(), "highlight_page_", IronOcr.ResultHighlightType.Word) -
3部署到您的生產環境進行測試
立即在您的項目中開始使用 IronOCR,並使用 免費試用
最簡工作流程(4 個步驟)
- 下載並安裝IronOCR C#程式庫
- 實例化 OCR 引擎
- 使用
LoadPdf載入 PDF 文檔 - 使用
HighlightTextAndSaveAsImages高亮文本片段並將它們保存為圖像
如何將文本突出顯示並保存為圖像?
使用 IronOCR 可以直接高亮顯示文字並將其儲存為影像。 使用LoadPdf載入現有的PDF,然後調用HighlightTextAndSaveAsImages方法來突出顯示文本區塊並將其保存為圖像。 此技術可驗證 OCR 的準確性,並除錯文件中的文字辨識問題。
該方法包含三個參數:IronTesseract OCR引擎、輸出文件名的前綴和ResultHighlightType中的一個枚舉,用於指示要突出顯示的文本類型。 此範例使用ResultHighlightType.Paragraph將文本區塊突出顯示為段落。HighlightTextAndSaveAsImages
本範例使用的 PDF 有三個段落。
輸入PDF看起來怎樣?
如何實現突出顯示代碼?
以下範例代碼演示了使用OcrInput class的基本實現。
using IronOcr;
IronTesseract ocrTesseract = new IronTesseract();
using var ocrInput = new OcrInput();
ocrInput.LoadPdf("document.pdf");
ocrInput.HighlightTextAndSaveAsImages(ocrTesseract, "highlight_page_", ResultHighlightType.Paragraph);using IronOcr;
IronTesseract ocrTesseract = new IronTesseract();
using var ocrInput = new OcrInput();
ocrInput.LoadPdf("document.pdf");
ocrInput.HighlightTextAndSaveAsImages(ocrTesseract, "highlight_page_", ResultHighlightType.Paragraph);Imports IronOcr
Dim ocrTesseract As New IronTesseract()
Using ocrInput As New OcrInput()
ocrInput.LoadPdf("document.pdf")
ocrInput.HighlightTextAndSaveAsImages(ocrTesseract, "highlight_page_", ResultHighlightType.Paragraph)
End UsingImports IronOcr
Dim ocrTesseract As New IronTesseract()
Using ocrInput As New OcrInput()
ocrInput.LoadPdf("document.pdf")
ocrInput.HighlightTextAndSaveAsImages(ocrTesseract, "highlight_page_", ResultHighlightType.Paragraph)
End Using輸出圖像顯示了什麼?

如上圖所示,所有三個段落都已用淺紅色方塊突出顯示。 此視覺化表示法可協助開發人員快速辨識 OCR 引擎如何將文件分割成可閱讀的區塊。
不同的ResultHighlightType選項是什麼?
以上範例使用了ResultHighlightType.Paragraph來突出顯示文本塊。 IronOCR 透過此枚舉提供額外的突出顯示選項。 以下是可用類型的完整清單,每種類型都有不同的診斷用途。
Character:在由OCR引擎檢測到的每個字符周圍繪制邊框。對於調試字符識別或專用字體特別有用,尤其是在使用自訂語言文件時。
Word:突出顯示引擎識別出的每個完整單詞。檢驗單詞邊界和單詞識別的理想選擇,尤其在伴隨條碼和QR碼讀取的文本識別時。
Line:突出顯示每條檢測到的文本行。適合需要進行行識別驗證的複雜佈局文件,例如處理掃描文件時。
Paragraph:突出顯示作為段落分組的整個文本塊。對於理解文件佈局和驗證文本塊分段非常完美,特別是在使用表格提取時尤為有用。
如何比較不同的突出顯示類型?
此綜合範例示範在同一份文件上產生所有不同類型的重點,讓您可以比較結果:
using IronOcr;
using System;
// Initialize the OCR engine with custom configuration
IronTesseract ocrTesseract = new IronTesseract();
// Configure for better accuracy if needed
ocrTesseract.Configuration.ReadBarCodes = false; // Disable if not needed for performance
ocrTesseract.Configuration.PageSegmentationMode = TesseractPageSegmentationMode.AutoOsd;
// Load the PDF document
using var ocrInput = new OcrInput();
ocrInput.LoadPdf("document.pdf");
// Generate highlights for each type
Console.WriteLine("Generating character-level highlights...");
ocrInput.HighlightTextAndSaveAsImages(ocrTesseract, "highlight_character_", ResultHighlightType.Character);
Console.WriteLine("Generating word-level highlights...");
ocrInput.HighlightTextAndSaveAsImages(ocrTesseract, "highlight_word_", ResultHighlightType.Word);
Console.WriteLine("Generating line-level highlights...");
ocrInput.HighlightTextAndSaveAsImages(ocrTesseract, "highlight_line_", ResultHighlightType.Line);
Console.WriteLine("Generating paragraph-level highlights...");
ocrInput.HighlightTextAndSaveAsImages(ocrTesseract, "highlight_paragraph_", ResultHighlightType.Paragraph);
Console.WriteLine("All highlight images have been generated successfully!");using IronOcr;
using System;
// Initialize the OCR engine with custom configuration
IronTesseract ocrTesseract = new IronTesseract();
// Configure for better accuracy if needed
ocrTesseract.Configuration.ReadBarCodes = false; // Disable if not needed for performance
ocrTesseract.Configuration.PageSegmentationMode = TesseractPageSegmentationMode.AutoOsd;
// Load the PDF document
using var ocrInput = new OcrInput();
ocrInput.LoadPdf("document.pdf");
// Generate highlights for each type
Console.WriteLine("Generating character-level highlights...");
ocrInput.HighlightTextAndSaveAsImages(ocrTesseract, "highlight_character_", ResultHighlightType.Character);
Console.WriteLine("Generating word-level highlights...");
ocrInput.HighlightTextAndSaveAsImages(ocrTesseract, "highlight_word_", ResultHighlightType.Word);
Console.WriteLine("Generating line-level highlights...");
ocrInput.HighlightTextAndSaveAsImages(ocrTesseract, "highlight_line_", ResultHighlightType.Line);
Console.WriteLine("Generating paragraph-level highlights...");
ocrInput.HighlightTextAndSaveAsImages(ocrTesseract, "highlight_paragraph_", ResultHighlightType.Paragraph);
Console.WriteLine("All highlight images have been generated successfully!");Imports IronOcr
Imports System
' Initialize the OCR engine with custom configuration
Dim ocrTesseract As New IronTesseract()
' Configure for better accuracy if needed
ocrTesseract.Configuration.ReadBarCodes = False ' Disable if not needed for performance
ocrTesseract.Configuration.PageSegmentationMode = TesseractPageSegmentationMode.AutoOsd
' Load the PDF document
Using ocrInput As New OcrInput()
ocrInput.LoadPdf("document.pdf")
' Generate highlights for each type
Console.WriteLine("Generating character-level highlights...")
ocrInput.HighlightTextAndSaveAsImages(ocrTesseract, "highlight_character_", ResultHighlightType.Character)
Console.WriteLine("Generating word-level highlights...")
ocrInput.HighlightTextAndSaveAsImages(ocrTesseract, "highlight_word_", ResultHighlightType.Word)
Console.WriteLine("Generating line-level highlights...")
ocrInput.HighlightTextAndSaveAsImages(ocrTesseract, "highlight_line_", ResultHighlightType.Line)
Console.WriteLine("Generating paragraph-level highlights...")
ocrInput.HighlightTextAndSaveAsImages(ocrTesseract, "highlight_paragraph_", ResultHighlightType.Paragraph)
End Using
Console.WriteLine("All highlight images have been generated successfully!")Imports IronOcr
Imports System
' Initialize the OCR engine with custom configuration
Dim ocrTesseract As New IronTesseract()
' Configure for better accuracy if needed
ocrTesseract.Configuration.ReadBarCodes = False ' Disable if not needed for performance
ocrTesseract.Configuration.PageSegmentationMode = TesseractPageSegmentationMode.AutoOsd
' Load the PDF document
Using ocrInput As New OcrInput()
ocrInput.LoadPdf("document.pdf")
' Generate highlights for each type
Console.WriteLine("Generating character-level highlights...")
ocrInput.HighlightTextAndSaveAsImages(ocrTesseract, "highlight_character_", ResultHighlightType.Character)
Console.WriteLine("Generating word-level highlights...")
ocrInput.HighlightTextAndSaveAsImages(ocrTesseract, "highlight_word_", ResultHighlightType.Word)
Console.WriteLine("Generating line-level highlights...")
ocrInput.HighlightTextAndSaveAsImages(ocrTesseract, "highlight_line_", ResultHighlightType.Line)
Console.WriteLine("Generating paragraph-level highlights...")
ocrInput.HighlightTextAndSaveAsImages(ocrTesseract, "highlight_paragraph_", ResultHighlightType.Paragraph)
End Using
Console.WriteLine("All highlight images have been generated successfully!")如何處理多頁文檔?
處理多頁PDF或多幀TIFF文件時,突出顯示功能會自動單獨處理每頁。 這在實施PDF OCR文本提取工作流程時特別有用:
using IronOcr;
using System.IO;
IronTesseract ocrTesseract = new IronTesseract();
// Load a multi-page document
using var ocrInput = new OcrInput();
ocrInput.LoadPdf("multi-page-document.pdf");
// Create output directory if it doesn't exist
string outputDir = "highlighted_pages";
Directory.CreateDirectory(outputDir);
// Generate highlights for each page
// Files will be named: highlighted_pages/page_0.png, page_1.png, etc.
ocrInput.HighlightTextAndSaveAsImages(ocrTesseract,
Path.Combine(outputDir, "page_"),
ResultHighlightType.Word);
// Count generated files for verification
int pageCount = Directory.GetFiles(outputDir, "page_*.png").Length;
Console.WriteLine($"Generated {pageCount} highlighted page images");using IronOcr;
using System.IO;
IronTesseract ocrTesseract = new IronTesseract();
// Load a multi-page document
using var ocrInput = new OcrInput();
ocrInput.LoadPdf("multi-page-document.pdf");
// Create output directory if it doesn't exist
string outputDir = "highlighted_pages";
Directory.CreateDirectory(outputDir);
// Generate highlights for each page
// Files will be named: highlighted_pages/page_0.png, page_1.png, etc.
ocrInput.HighlightTextAndSaveAsImages(ocrTesseract,
Path.Combine(outputDir, "page_"),
ResultHighlightType.Word);
// Count generated files for verification
int pageCount = Directory.GetFiles(outputDir, "page_*.png").Length;
Console.WriteLine($"Generated {pageCount} highlighted page images");Imports IronOcr
Imports System.IO
Dim ocrTesseract As New IronTesseract()
' Load a multi-page document
Using ocrInput As New OcrInput()
ocrInput.LoadPdf("multi-page-document.pdf")
' Create output directory if it doesn't exist
Dim outputDir As String = "highlighted_pages"
Directory.CreateDirectory(outputDir)
' Generate highlights for each page
' Files will be named: highlighted_pages/page_0.png, page_1.png, etc.
ocrInput.HighlightTextAndSaveAsImages(ocrTesseract,
Path.Combine(outputDir, "page_"),
ResultHighlightType.Word)
' Count generated files for verification
Dim pageCount As Integer = Directory.GetFiles(outputDir, "page_*.png").Length
Console.WriteLine($"Generated {pageCount} highlighted page images")
End UsingImports IronOcr
Imports System.IO
Dim ocrTesseract As New IronTesseract()
' Load a multi-page document
Using ocrInput As New OcrInput()
ocrInput.LoadPdf("multi-page-document.pdf")
' Create output directory if it doesn't exist
Dim outputDir As String = "highlighted_pages"
Directory.CreateDirectory(outputDir)
' Generate highlights for each page
' Files will be named: highlighted_pages/page_0.png, page_1.png, etc.
ocrInput.HighlightTextAndSaveAsImages(ocrTesseract,
Path.Combine(outputDir, "page_"),
ResultHighlightType.Word)
' Count generated files for verification
Dim pageCount As Integer = Directory.GetFiles(outputDir, "page_*.png").Length
Console.WriteLine($"Generated {pageCount} highlighted page images")
End Using性能最佳實踐是什麼?
使用高亮顯示功能時,請考慮這些最佳實務:
- 文件大小:對於高分辨率文件,突出顯示的圖像可能很大。 在處理大量批次時,請考慮輸出目錄的可用空間。 關於優化提示,請參閱我們的快速OCR配置指南。
- 性能:生成突出顯示會增加處理負擔。 對於只是偶爾需要高亮度的生產系統,請將其作為獨立的診斷流程來實施,而不是主要工作流程的一部分。 考慮使用多執行緒 OCR 進行批次處理。
- 錯誤處理:進行文件操作時,一定要執行適當的錯誤處理:
try
{
using var ocrInput = new OcrInput();
ocrInput.LoadPdf("document.pdf");
// Apply image filters if needed for better recognition
ocrInput.Deskew(); // Correct slight rotations
ocrInput.DeNoise(); // Remove background noise
ocrInput.HighlightTextAndSaveAsImages(ocrTesseract, "highlight_", ResultHighlightType.Word);
}
catch (Exception ex)
{
Console.WriteLine($"Error during highlighting: {ex.Message}");
// Log error details for debugging
}try
{
using var ocrInput = new OcrInput();
ocrInput.LoadPdf("document.pdf");
// Apply image filters if needed for better recognition
ocrInput.Deskew(); // Correct slight rotations
ocrInput.DeNoise(); // Remove background noise
ocrInput.HighlightTextAndSaveAsImages(ocrTesseract, "highlight_", ResultHighlightType.Word);
}
catch (Exception ex)
{
Console.WriteLine($"Error during highlighting: {ex.Message}");
// Log error details for debugging
}Imports System
Try
Using ocrInput As New OcrInput()
ocrInput.LoadPdf("document.pdf")
' Apply image filters if needed for better recognition
ocrInput.Deskew() ' Correct slight rotations
ocrInput.DeNoise() ' Remove background noise
ocrInput.HighlightTextAndSaveAsImages(ocrTesseract, "highlight_", ResultHighlightType.Word)
End Using
Catch ex As Exception
Console.WriteLine($"Error during highlighting: {ex.Message}")
' Log error details for debugging
End TryImports System
Try
Using ocrInput As New OcrInput()
ocrInput.LoadPdf("document.pdf")
' Apply image filters if needed for better recognition
ocrInput.Deskew() ' Correct slight rotations
ocrInput.DeNoise() ' Remove background noise
ocrInput.HighlightTextAndSaveAsImages(ocrTesseract, "highlight_", ResultHighlightType.Word)
End Using
Catch ex As Exception
Console.WriteLine($"Error during highlighting: {ex.Message}")
' Log error details for debugging
End Try突出顯示如何與OCR結果整合?
突出顯示功能與IronOCR的結果對象一起工作,允許您將可視化突出顯示與提取的文本數據相對應。 這尤其有用,當您需要track OCR progress或驗證特定部分的識別文本時。 OcrResult類別提供有關每個檢測元素的詳細信息,這直接對應於此方法生成的視覺突出顯示。
如果遇到問題怎麼辦?
如果遇到突出顯示功能的問題,請參閱一般疑難排解指南以獲得常見解決方案。 針對特定的高亮度相關問題:
- 空白輸出圖像:確保輸入文件包含可讀文本,並且OCR引擎已正確配置為適用於您的文件類型。 您可能需要應用圖片優化濾鏡或
fixing image orientation來改善識別。 - 缺少突出顯示:某些文檔類型可能需要特殊的預處理。 嘗試應用圖片濾鏡或
fixing image orientation來改善識別。 - 性能問題:對於大型文件,考慮實施
multithreading以提高處理速度。 此外,若遇到低品質輸入時,請參考我們的修復低質量掃描指導。
如何將此用於生產調試?
高亮顯示功能可作為絕佳的生產除錯工具。 當與中止令牌和超時的長時間運行操作集成時,您可以創建一個可靠的診斷系統。 考慮在您的應用程式中實作除錯模式:
public class OcrDebugger
{
private readonly IronTesseract _tesseract;
private readonly bool _debugMode;
public OcrDebugger(bool enableDebugMode = false)
{
_tesseract = new IronTesseract();
_debugMode = enableDebugMode;
}
public OcrResult ProcessDocument(string filePath)
{
using var input = new OcrInput();
input.LoadPdf(filePath);
// Apply preprocessing
input.Deskew();
input.DeNoise();
// Generate debug highlights if in debug mode
if (_debugMode)
{
string debugPath = $"debug_{Path.GetFileNameWithoutExtension(filePath)}_";
input.HighlightTextAndSaveAsImages(_tesseract, debugPath, ResultHighlightType.Word);
}
// Perform actual OCR
return _tesseract.Read(input);
}
}public class OcrDebugger
{
private readonly IronTesseract _tesseract;
private readonly bool _debugMode;
public OcrDebugger(bool enableDebugMode = false)
{
_tesseract = new IronTesseract();
_debugMode = enableDebugMode;
}
public OcrResult ProcessDocument(string filePath)
{
using var input = new OcrInput();
input.LoadPdf(filePath);
// Apply preprocessing
input.Deskew();
input.DeNoise();
// Generate debug highlights if in debug mode
if (_debugMode)
{
string debugPath = $"debug_{Path.GetFileNameWithoutExtension(filePath)}_";
input.HighlightTextAndSaveAsImages(_tesseract, debugPath, ResultHighlightType.Word);
}
// Perform actual OCR
return _tesseract.Read(input);
}
}Public Class OcrDebugger
Private ReadOnly _tesseract As IronTesseract
Private ReadOnly _debugMode As Boolean
Public Sub New(Optional enableDebugMode As Boolean = False)
_tesseract = New IronTesseract()
_debugMode = enableDebugMode
End Sub
Public Function ProcessDocument(filePath As String) As OcrResult
Using input As New OcrInput()
input.LoadPdf(filePath)
' Apply preprocessing
input.Deskew()
input.DeNoise()
' Generate debug highlights if in debug mode
If _debugMode Then
Dim debugPath As String = $"debug_{Path.GetFileNameWithoutExtension(filePath)}_"
input.HighlightTextAndSaveAsImages(_tesseract, debugPath, ResultHighlightType.Word)
End If
' Perform actual OCR
Return _tesseract.Read(input)
End Using
End Function
End ClassPublic Class OcrDebugger
Private ReadOnly _tesseract As IronTesseract
Private ReadOnly _debugMode As Boolean
Public Sub New(Optional enableDebugMode As Boolean = False)
_tesseract = New IronTesseract()
_debugMode = enableDebugMode
End Sub
Public Function ProcessDocument(filePath As String) As OcrResult
Using input As New OcrInput()
input.LoadPdf(filePath)
' Apply preprocessing
input.Deskew()
input.DeNoise()
' Generate debug highlights if in debug mode
If _debugMode Then
Dim debugPath As String = $"debug_{Path.GetFileNameWithoutExtension(filePath)}_"
input.HighlightTextAndSaveAsImages(_tesseract, debugPath, ResultHighlightType.Word)
End If
' Perform actual OCR
Return _tesseract.Read(input)
End Using
End Function
End Class接下來我應該去哪裡?
現在您已瞭解如何使用高亮顯示功能,請探索:
對於生產使用,請記得獲取授權以移除水印並獲得完整功能。
常見問題
IronOCR如何在圖像中突出顯示文字?
IronOCR使用 HighlightTextAndSaveAsImages 方法來視覺化OCR結果。它會在檢測到的文字(例如字元、單詞、行或段落)周圍畫出邊界框,並將其保存為圖像。
為什麼在OCR中,文字突出顯示很有用?
文字突出顯示對調試和驗證OCR輸出準確性很有用。它提供了OCR引擎所檢測內容的視覺反饋,有助於識別複雜文件中的識別錯誤。
如何使用IronOCR為PDF文件實現文字突出顯示?
您可以使用 LoadPdf 加載PDF文件,並使用IronOCR中的 HighlightTextAndSaveAsImages 方法。這會突出顯示指定的文字元素,並將結果保存為圖像。
IronOCR中的不同ResultHighlightType選項有哪些?
IronOCR提供不同的 ResultHighlightType 選項,包括字元、單詞、行和段落,每種選項都可用於文字識別的各種診斷目的。
IronOCR可以處理多頁文件的文字突出顯示嗎?
是的,IronOCR可以處理多頁文件,如PDF或TIFF檔,並自動處理每一頁,為每一頁生成相應的高亮圖像。
在生產環境中使用高亮功能時,我應該考慮什麼?
在使用高亮功能時,請考慮文件大小和處理的額外負擔。如果即時反饋不是必需的,最好將高亮功能作為一個單獨的診斷過程實施。
如何解決IronOCR中空白輸出圖像的問題?
確保輸入文件包含可讀的文字,以及OCR引擎已正確配置。您可能還需要進行圖像優化或方向調整以改善結果。
使用IronOCR高亮時,我應該遵循哪些性能最佳實踐?
通過確保有足夠的可用空間來管理大型高亮圖像,並考慮實施多執行緒以提高速度。還應為文件操作實施適當的錯誤處理。
Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。