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

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

IronOCR 的 HighlightTextAndSaveAsImages 方法透過在偵測到的文字(字元、單字、行或段落)周圍繪製邊界方塊來視覺化 OCR 結果,並將其儲存為診斷影像,使開發人員能夠驗證 OCR 準確性並調試識別問題。

視覺化 OCR 結果包括圍繞引擎在影像中偵測到的特定文字元素渲染邊界框。 該過程會在單字、單字、行或段落的確切位置上疊加明顯的高亮顯示,從而提供識別內容的清晰地圖。

這種視覺回饋對於偵錯和驗證 OCR 輸出準確性至關重要,它可以顯示軟體識別出了什麼以及在哪裡出現了錯誤。 在處理複雜文件或檢查辨識問題時,視覺高亮顯示成為重要的診斷工具。

本文透過 HighlightTextAndSaveAsImages 方法示範了 IronOCR 的診斷功能。 此功能可反白顯示文字的特定部分並將其儲存為圖像以供驗證。 無論是建立文件處理系統、實施品質控制措施,或是驗證 OCR 實現,此功能都能立即提供 OCR 引擎偵測到內容的視覺回饋。

快速入門:立即高亮 PDF 中的文字快速入門:立即高亮 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可以輕鬆地高亮顯示文字並將其儲存為圖像。 使用 LoadPdf 載入現有 PDF,然後呼叫 HighlightTextAndSaveAsImages 方法突出顯示文字部分並將其儲存為圖像。 該技術可驗證 OCR 的準確性並調試文件中的文字辨識問題。

此方法接受三個參數: IronTesseract OCR 引擎、輸出檔案名稱的前綴以及 ResultHighlightType 枚舉,該枚舉指定要反白顯示的文字類型。 本範例使用 ResultHighlightType.Paragraph 將文字區塊反白顯示為段落。

請注意此函數使用輸出字串前綴,並為每個頁面在輸出影像檔案名稱後附加頁面識別碼(例如,"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);
$vbLabelText   $csharpLabel

輸出影像顯示了什麼?

網頁包含三個段落,中間段落以紅色邊框突出顯示,表示可進行文字選擇。

如上圖所示,所有三個段落都以淺紅色方框突出顯示。 這種視覺化表示有助於開發人員快速識別 OCR 引擎如何將文件分割成可讀區塊。

ResultHighlightType 有哪些不同的選項?

上面的範例使用 ResultHighlightType.Paragraph 來反白顯示文字區塊。 IronOCR透過此枚舉提供額外的突出顯示選項。 以下是所有可用類型的完整列表,每種類型都有不同的診斷用途。

字元:在 OCR 引擎偵測到的每個字元周圍繪製一個邊界框。這對於偵錯字元辨識或特殊字體非常有用,尤其是在處理自訂語言檔案時。

單字:高亮顯示引擎辨識出的每個完整單字。非常適合驗證單字邊界和正確識別單字,尤其是在將條碼和二維碼讀取與文字辨識結合使用時。

:高亮顯示偵測到的每一行文字。適用於需要進行行識別驗證的複雜佈局文檔,例如處理掃描文檔時。

段落:高亮顯示以段落形式分組的整個文字區塊。非常適合了解文件佈局和驗證文字區塊分割,在處理表格提取時尤其有用。

如何比較不同的高亮類型?

這個全面的範例示範如何為同一文件中的所有不同類型產生高亮顯示,以便您可以比較結果:

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!");
$vbLabelText   $csharpLabel

如何處理多頁文件?

處理多頁 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");
$vbLabelText   $csharpLabel

績效最佳實務有哪些?

使用高亮顯示功能時,請遵循以下最佳實務:

1.文件大小:突出顯示的圖像可能很大,尤其是高解析度文件。 處理大量資料時,請考慮輸出目錄的可用空間。 有關優化技巧,請參閱我們的快速 OCR 設定指南

2.效能:產生高光片段會增加處理開銷。 對於僅偶爾需要高亮顯示的生產系統,應將其作為單獨的診斷流程來實現,而不是作為主要工作流程的一部分。 考慮使用多執行緒OCR進行批次處理。

3.錯誤處理:在進行文件操作時,請務必實現適當的錯誤處理:

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
}
$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);
    }
}
$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 枚舉允許您高亮顯示各種文字元素,包括單獨的 Characters、Words、Lines 或整個段落。只需在呼叫 HighlightTextAndSaveAsImages 方法時指定所需的類型,即可視覺化不同層級的文字偵測。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。

準備好開始了嗎?
Nuget 下載 5,556,263 | 版本: 2026.3 剛剛發布
Still Scrolling Icon

還在捲動嗎?

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