使用IronOCR在C#中將文字以圖像高亮顯示

This article was translated from English: Does it need improvement?
Translated
View the article in English

IronOCR的HighlightTextAndSaveAsImages方法通過在檢測到的文字(字元、單詞、行或段落)周圍繪製邊框來可視化OCR結果,並將它們保存為診斷圖像,使開發者能夠驗證OCR的準確性和除錯識別問題。

可視化OCR結果涉及在引擎已在圖像中檢測到的特定文字元素周圍呈現邊框。 此過程在個別字元、單詞、行或段落的準確位置上覆蓋了醒目的高亮顯示,提供了清晰的已識別內容地圖。

這種視覺反饋對於除錯和驗證OCR輸出準確性至關重要,顯示軟體已識別的內容以及錯誤出現的位置。 當處理複雜文件或排除識別問題時,視覺高亮顯示成為一種基本的診斷工具。

本文展示了IronOCR的診斷功能及其HighlightTextAndSaveAsImages方法。 此功能高亮顯示特定的文字區域並將它們保存為圖像以供驗證。 無論是構建文件處理系統、實施品質控制措施還是驗證您的OCR實施,此功能都能對OCR引擎檢測到的內容提供即時的視覺反饋。

快速入門:立即在您的PDF中高亮顯示單詞

此程式碼片段展示了IronOCR的用法:載入一個PDF並高亮顯示文件中的每個單詞,將結果保存為圖像。 只需一行程式碼即可獲得OCR結果的視覺反饋。

  1. 使用NuGet套件管理器安裝https://www.nuget.org/packages/IronOcr

    PM > Install-Package IronOcr
  2. 複製並運行這段程式碼片段。

    new IronOcr.OcrInput().LoadPdf("document.pdf").HighlightTextAndSaveAsImages(new IronOcr.IronTesseract(), "highlight_page_", IronOcr.ResultHighlightType.Word);
  3. 部署以在您的實時環境中測試

    今天就開始在您的專案中使用IronOCR,透過免費試用

    arrow pointer

如何將文字高亮並保存為圖像?

使用IronOCR將文字高亮並保存為圖像是非常簡單的。 首先使用HighlightTextByType方法以高亮顯示文字區域並將它們保存為圖像。 此技術驗證了OCR的準確性並除錯文件中的文字識別問題。

該方法需要三個參數:ResultHighlightType枚舉值。 此範例使用HighlightTextAndSaveAsImages

請注意此功能使用輸出字串前綴,並為每頁的輸出圖像文件名追加頁面標識符(例如"page_0","page_1")。

此範例使用了一個包含三個段落的PDF。

輸入PDF的外觀是怎樣的?

我該如何實現突出顯示程式碼?

下面的範例程式碼展示了使用OcrInput類的基本實現。

:path=/static-assets/ocr/content-code-examples/how-to/highlight-texts-as-images.cs
using IronOcr;

IronTesseract ocrTesseract = new IronTesseract();

using var ocrInput = new OcrInput();
ocrInput.LoadPdf("document.pdf");
ocrInput.HighlightTextAndSaveAsImages(ocrTesseract, "highlight_page_", ResultHighlightType.Paragraph);
Imports IronOcr

Private ocrTesseract As New IronTesseract()

Private ocrInput = New OcrInput()
ocrInput.LoadPdf("document.pdf")
ocrInput.HighlightTextAndSaveAsImages(ocrTesseract, "highlight_page_", ResultHighlightType.Paragraph)
$vbLabelText   $csharpLabel

輸出圖像顯示了什麼?

網頁展示了三個段落,中間的段落用紅色邊框高亮顯示,展示了文字選擇功能

如上面的輸出圖像所示,所有三個段落都被淡紅色框高亮顯示。 這種視覺表示有助於開發者快速識別OCR引擎如何將文件分段為可讀塊。

不同的ResultHighlightType選項有哪些?

上面的範例使用了ResultHighlightType.Paragraph來高亮顯示文字塊。 IronOCR提供了其他的高亮選項通過此枚舉。 下面是所有可用型別的完整列表,每個都服務於不同的診斷目的。

Character:在OCR引擎檢測到的每個字元周圍繪製一個邊框。對於除錯字元識別或專用字體特別有用,尤其是在使用自訂語言文件時。

Word:高亮顯示引擎識別的每個完整單詞。理想用於驗證單詞邊界和正確的單詞識別,特別是在文字識別中實現條形碼和QR讀取的情況下。

Line:高亮顯示每一個檢測到的文字行。對於需要行識別驗證的複雜佈局的文件(如處理掃描文件時)特別有用。

Paragraph:高亮顯示整個被分組為段落的文字塊。完美用於理解文件佈局和驗證文字塊分段,特別是在表格提取時特別有用。

我如何比較不同的高亮型別?

這個綜合例子展示了如何在同一文件上生成所有不同型別的高亮,使您可以比較結果:

:path=/static-assets/ocr/content-code-examples/how-to/highlight-texts-as-images-3.cs
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)

    Console.WriteLine("All highlight images have been generated successfully!")
End Using
$vbLabelText   $csharpLabel

我如何處理多頁文件?

在處理多頁PDF或多幀TIFF文件時,高亮特性會自動單獨處理每個頁面。 這在實現PDF OCR文字提取工作流程時特別有用:

:path=/static-assets/ocr/content-code-examples/how-to/highlight-texts-as-images-4.cs
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 Using
$vbLabelText   $csharpLabel

性能最佳實踐是什麼?

使用高亮功能時,請考慮以下最佳實踐:

  1. 文件大小:高亮顯示的圖像可能很大,特別是對於高解析度的文件。 處理大型文件批量時,考慮輸出目錄的可用空間。 有關優化提示,請參見我們的快速OCR配置指南

  2. 性能:生成高亮顯示增加了處理的開銷。 對於生產系統而言,如果高亮顯示僅偶爾需要,請將其作為單獨的診斷過程實施,而不是主要工作流的一部分。 考慮使用多執行緒OCR進行批量處理。

  3. 錯誤處理:當進行文件操作時,始終實現適當的錯誤處理:
:path=/static-assets/ocr/content-code-examples/how-to/highlight-texts-as-images-5.cs
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 Try
$vbLabelText   $csharpLabel

高亮如何與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);
    }
}
Imports System.IO

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 Class
$vbLabelText   $csharpLabel

下一步該怎麼做?

現在您已經了解如何使用高亮功能,探索:

對於生產使用,請記得獲取授權以移除浮水印並存取全部功能。

常見問題

如何在我的C#應用中視覺化OCR結果?

IronOCR提供了HighlightTextAndSaveAsImages方法,它通過繪製框線在檢測到的文字元素(字元、詞語、行或段落)上視覺化OCR結果,並將其儲存為診斷圖像。這個功能幫助開發者驗證OCR的準確性和除錯識別問題。

在PDF文件中標註詞語的最簡單方法是什麼?

使用IronOCR,您可以只用一行程式碼就能在PDF中標註詞語:new IronOcr.OcrInput().LoadPdf("document.pdf").HighlightTextAndSaveAsImages(new IronOcr.IronTesseract(), "highlight_page_", IronOcr.ResultHighlightType.Word)。這會載入PDF並建立帶有標註詞語的圖像。

HighlightTextAndSaveAsImages方法需要哪些參數?

IronOCR中的HighlightTextAndSaveAsImages方法需要三個參數:IronTesseract OCR引擎實例、輸出文件名前綴字串,以及指定哪種文字元素(字元、詞語、行或段落)做標註的ResultHighlightType枚舉值。

使用文字標註功能時,輸出圖像如何命名?

IronOCR自動將您指定的前綴與頁面識別符結合來命名輸出圖像。例如,如果您使用"highlight_page_"作為前綴,該方法會生成名為"highlight_page_0"、"highlight_page_1"等的文件,分別對應文件中的每一頁。

為什麼視覺化標註對OCR開發很重要?

IronOCR中的視覺化標註提供了關鍵的診斷反饋,顯示OCR引擎檢測到的文字以及潛在錯誤發生的位置。這種視覺地圖幫助開發者除錯識別問題、驗證OCR的準確性,並解決複雜文件中的問題。

除了詞語,我可以標註不同型別的文字元素嗎?

可以,IronOCR的ResultHighlightType枚舉允許您標註包括單個字元、詞語、行或整個段落的各種文字元素。只需在調用HighlightTextAndSaveAsImages方法時指定所需的型別,即可視覺化不同層次的文字檢測。

IronOCR能整合到現有的應用程式中嗎?

IronOCR被設計成可以輕鬆地整合到現有應用程式中,使用C#允許開發人員以最小的努力為其軟體新增OCR功能。

使用IronOCR進行文件管理的好處是什麼?

使用IronOCR進行文件管理通過將掃描的文件轉換為可搜索和可編輯的文字來簡化工作流程,減少手動資料輸入的需求並提高文件的可存取性。

IronOCR如何提高資料精確性?

IronOCR通過其先進的識別算法和影像校正功能提高資料精確性,確保文字提取過程既可靠又精確。

IronOCR有免費試用版嗎?

有的,Iron Software提供IronOCR的免費試用版,允許使用者在做出購買決定前測試其功能和能力。

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

準備開始了嗎?
Nuget 下載 6,151,372 | 版本: 2026.7 剛剛發布
Still Scrolling Icon

還在滾動?

想要快速證明? PM > Install-Package IronOcr
執行範例 觀看您的圖像轉變為可搜尋文字。