在C#中快速配置OCR以獲得最佳性能

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

IronOCR的快速配置通過使用EnglishFast語言模式並禁用不必要的功能如條碼閱讀,使OCR處理速度提高最多17%而不影響準確性。 此優化非常適合時間關鍵的高容量處理。

IronOCR即裝即用效果良好。 當速度優先於絕對準確性時,IronOCR提供快速配置。 此設置提供顯著的掃描性能提升,對準確性的影響微乎其微,比標準OCR配置要快得多。

本文演示如何設置快速配置並比較快速與標準IronOCR配置的基準測試結果。 無論您正在處理掃描文件PDF圖片,這些優化都可以顯著改善您的應用性能。


快速入門:在C#中配置快速OCR

快速配置的主要組件是Language屬性。 將OcrLanguage.EnglishFast優先考慮速度而可能犧牲少許準確性。 這使得IronOCR能夠更快速地批量閱讀,這在時間至關重要的任務關鍵應用中尤為有用。

除了設置快速語言外,禁用不必要的配置,如ReadBarCodes,可以進一步提升速度。 讓IronOCR自動檢測頁面分割,以保持設置簡單。 有關更高級的配置選項,請參見我們的Tesseract詳細配置指南

以下程式碼範例處理以下輸入圖像:

我應該使用什麼輸入格式?

《白鯨記》開篇文字以白色顯示在深色背景上,展示以實梅爾為介紹

快速配置需要哪些程式碼?

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

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

    /* :path=/static-assets/ocr/content-code-examples/how-to/ocr-fast-configuration.cs */
    using IronOcr;
    using System;
    
    var ocrTesseract = new IronTesseract();
    
    // Fast Dictionary
    ocrTesseract.Language = OcrLanguage.EnglishFast;
    
    // Turn off unneeded options
    ocrTesseract.Configuration.ReadBarCodes = false;
    
    // Assume text is laid out neatly in an orthogonal document
    ocrTesseract.Configuration.PageSegmentationMode = TesseractPageSegmentationMode.Auto;
    
    using var ocrInput = new OcrInput();
    ocrInput.LoadImage("image.png");
    
    var ocrResult = ocrTesseract.Read(ocrInput);
    Console.WriteLine(ocrResult.Text);
  3. 部署以在您的實時環境中測試

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

    arrow pointer

我可以預期什麼輸出?

Visual Studio編輯器顯示《白鯨記》小說的開頭段落

這是從上方提取的文字輸出。 OCR引擎在保持原始格式和結構的同時準確捕捉文學文字。 快速配置為清晰、高對比度的文字提供了優秀的結果,如本例。


快速配置與標準有何不同?

為了展示實際影響,我們對標準配置和快速配置的性能進行基準測試。 我們使用一組包含數段文字的10個樣本圖像來比較性能並可視化使用快速配置的利弊。

對於標準配置,我們用預設設置初始化IronTesseract,不應用任何速度導向的屬性。 這種基準方法類似於我們的性能跟蹤指南,該指南展示如何實時監控OCR操作。

這是我們用來運行測試的樣本輸入。這些圖像代表您在處理多頁文件或批量操作時可能遇到的典型文件情況。

我如何運行基準測試?

:path=/static-assets/ocr/content-code-examples/how-to/ocr-fast-configuration-benchmark.cs
using IronOcr;
using System;
using System.Diagnostics;
using System.IO;

// --- Tesseract Engine Setup ---
var ocrTesseract = new IronTesseract();
ocrTesseract.Language = OcrLanguage.EnglishFast;
ocrTesseract.Configuration.ReadBarCodes = false;
ocrTesseract.Configuration.PageSegmentationMode = TesseractPageSegmentationMode.Auto;

// --- 1. Define folder and get files ---
string folderPath = @"images"; // IMPORTANT: Set this to your image directory
string filePattern = "*.png";    // Change to "*.jpg", "*.bmp", etc. as needed
string outputFilePath = "ocr_results.txt"; // The new results file

// Get all image files in the directory
var imageFiles = Directory.GetFiles(folderPath, filePattern);

Console.WriteLine($"Found {imageFiles.Length} total images to process...");
Console.WriteLine($"Results will be written to: {outputFilePath}");

// --- 2. Start timer and process images, writing to file ---
// Open the output file *before* the loop for efficiency
using (StreamWriter writer = new StreamWriter(outputFilePath))
{
    var stopwatch = Stopwatch.StartNew();

    foreach (var file in imageFiles)
    {
        string fileName = Path.GetFileName(file);

        using var ocrInput = new OcrInput();
        ocrInput.LoadImage(file);

        var ocrResult = ocrTesseract.Read(ocrInput);

        // Check if any text was actually found
        if (!string.IsNullOrEmpty(ocrResult.Text))
        {
            // Write to Console
            Console.WriteLine($"--- Text found in: {fileName} ---");
            Console.WriteLine(ocrResult.Text.Trim());
            Console.WriteLine("------------------------------------------");

            // Write to File
            writer.WriteLine($"--- Text found in: {fileName} ---");
            writer.WriteLine(ocrResult.Text.Trim());
            writer.WriteLine("------------------------------------------");
            writer.WriteLine(); // Add a blank line for readability
        }
        else
        {
            // Write to Console
            Console.WriteLine($"No text found in: {fileName}");

            // Write to File
            writer.WriteLine($"No text found in: {fileName}");
            writer.WriteLine();
        }
    }

    stopwatch.Stop();

    // --- 3. Print and write final benchmark summary ---
    string lineSeparator = "\n========================================";
    string title = "Batch OCR Processing Complete";
    string summary = $"Fast configuration took {stopwatch.Elapsed.TotalSeconds:F2} seconds";

    // Write summary to Console
    Console.WriteLine(lineSeparator);
    Console.WriteLine(title);
    Console.WriteLine("========================================");
    Console.WriteLine(summary);

    // Write summary to File
    writer.WriteLine(lineSeparator);
    writer.WriteLine(title);
    writer.WriteLine("========================================");
    writer.WriteLine(summary);

    if (imageFiles.Length > 0)
    {
        string avgTime = $"Average time per image: {(stopwatch.Elapsed.TotalSeconds / (double)imageFiles.Length):F3} seconds";
        Console.WriteLine(avgTime);
        writer.WriteLine(avgTime);
    }
}

Console.WriteLine($"\nSuccessfully saved results to {outputFilePath}");
Imports IronOcr
Imports System
Imports System.Diagnostics
Imports System.IO

' --- Tesseract Engine Setup ---
Dim ocrTesseract As New IronTesseract()
ocrTesseract.Language = OcrLanguage.EnglishFast
ocrTesseract.Configuration.ReadBarCodes = False
ocrTesseract.Configuration.PageSegmentationMode = TesseractPageSegmentationMode.Auto

' --- 1. Define folder and get files ---
Dim folderPath As String = "images" ' IMPORTANT: Set this to your image directory
Dim filePattern As String = "*.png" ' Change to "*.jpg", "*.bmp", etc. as needed
Dim outputFilePath As String = "ocr_results.txt" ' The new results file

' Get all image files in the directory
Dim imageFiles = Directory.GetFiles(folderPath, filePattern)

Console.WriteLine($"Found {imageFiles.Length} total images to process...")
Console.WriteLine($"Results will be written to: {outputFilePath}")

' --- 2. Start timer and process images, writing to file ---
' Open the output file *before* the loop for efficiency
Using writer As New StreamWriter(outputFilePath)
    Dim stopwatch = Stopwatch.StartNew()

    For Each file In imageFiles
        Dim fileName As String = Path.GetFileName(file)

        Using ocrInput As New OcrInput()
            ocrInput.LoadImage(file)

            Dim ocrResult = ocrTesseract.Read(ocrInput)

            ' Check if any text was actually found
            If Not String.IsNullOrEmpty(ocrResult.Text) Then
                ' Write to Console
                Console.WriteLine($"--- Text found in: {fileName} ---")
                Console.WriteLine(ocrResult.Text.Trim())
                Console.WriteLine("------------------------------------------")

                ' Write to File
                writer.WriteLine($"--- Text found in: {fileName} ---")
                writer.WriteLine(ocrResult.Text.Trim())
                writer.WriteLine("------------------------------------------")
                writer.WriteLine() ' Add a blank line for readability
            Else
                ' Write to Console
                Console.WriteLine($"No text found in: {fileName}")

                ' Write to File
                writer.WriteLine($"No text found in: {fileName}")
                writer.WriteLine()
            End If
        End Using
    Next

    stopwatch.Stop()

    ' --- 3. Print and write final benchmark summary ---
    Dim lineSeparator As String = vbLf & "========================================"
    Dim title As String = "Batch OCR Processing Complete"
    Dim summary As String = $"Fast configuration took {stopwatch.Elapsed.TotalSeconds:F2} seconds"

    ' Write summary to Console
    Console.WriteLine(lineSeparator)
    Console.WriteLine(title)
    Console.WriteLine("========================================")
    Console.WriteLine(summary)

    ' Write summary to File
    writer.WriteLine(lineSeparator)
    writer.WriteLine(title)
    writer.WriteLine("========================================")
    writer.WriteLine(summary)

    If imageFiles.Length > 0 Then
        Dim avgTime As String = $"Average time per image: {(stopwatch.Elapsed.TotalSeconds / CDbl(imageFiles.Length)):F3} seconds"
        Console.WriteLine(avgTime)
        writer.WriteLine(avgTime)
    End If
End Using

Console.WriteLine(vbLf & $"Successfully saved results to {outputFilePath}")
$vbLabelText   $csharpLabel

此基準程式碼展示了幾個重要概念:

  1. 批量處理:程式碼在一個操作中處理多個圖像,例如我們的多執行緒OCR範例,顯示如何利用並行處理進一步增加速度。

  2. 性能測量:使用Stopwatch類提供精確的計時測量到毫秒,這對於比較不同配置至關重要。

  3. 結果記錄:控制台和文件輸出可確保您可以稍後分析結果並驗證配置之間的準確性差異。

我可以預期什麼性能增益?

模式 總時間 平均時間/圖像 與標準的時間增益 與標準的準確性增益
標準 10.40秒 1.040秒 Baseline Baseline
快速 8.60秒 0.860秒 +17.31%(更快) +0%(相同)

標準和快速配置之間的基準比較顯示了快速配置的顯著性能優勢。 通過將標準模式設置為基線(總時間10.40秒),快速配置僅用8.60秒完成了相同的10張圖像批次。 這代表了17.31%的顯著時間增益。 重要的是,這種速度提升並未損害質量; 兩種模式之間的準確性相同,兩個配置生成了相同的文字輸出。

為了驗證結果,您可以下載快速文字輸出標準文字輸出

何時應使用快速配置?

快速配置特別有利於:

  • 高容量文件處理,需要快速處理數千頁
  • 即時應用,在響應時間關鍵的情況下
  • 網頁應用,需要保持使用者體驗的響應性
  • 批量處理系統,需要在緊湊的時間表上運行

對於涉及多語言低質量掃描或專業文件型別如車牌護照的更複雜場景,您可能需要使用標準配置以確保最大準確性。

IronOCR使配置之間的切換變得簡單——只需改變幾個屬性,您的應用即可適應不同的性能需求,而無需大幅更改程式碼。

常見問題

快速OCR配置與標準設置相比,速度有多快?

IronOCR的快速配置相比標準OCR設置可實現高達17%的速度提高,對準確性的影響微乎其微。此性能增益是通過EnglishFast語言模式和禁用不必要功能來實現的。

啟用快速OCR處理的主要設置是什麼?

IronOCR快速配置的主要組件是將Language屬性設置為OcrLanguage.EnglishFast。這優先考慮速度而非小幅準確性成本,使其非常適合批量處理和時間關鍵的應用。

我如何在使用EnglishFast模式之外進一步優化OCR速度?

您可以通過在IronOCR中禁用不必要的功能來獲得額外的速度提升,例如如果不需要條碼檢測,將ReadBarCodes設為false。此外,通過使用TesseractPageSegmentationMode.Auto讓IronOCR自動檢測頁面分段。

何時應使用快速OCR配置而不是標準設置?

IronOCR的快速OCR配置非常適合在時間至關重要且可接受準確性輕微妥協的高容量處理場景。對於需要快速處理掃描文件、PDF或圖像的關鍵性應用特別有用。

快速配置適用於所有文件型別嗎?

是的,IronOCR的快速配置可以有效處理包括掃描文件、PDF和圖像在內的各種文件型別。優化的好處不會因您正在處理的輸入格式而改變。

使用快速OCR模式時是否會有任何準確性損失?

IronOCR的快速配置提供顯著的掃描性能增益,對準確性的影響微乎其微。雖然使用EnglishFast模式可能會有小幅準確性成本,但對於優先考慮速度的應用來說,這種權衡通常是值得的。

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
執行範例 觀看您的圖像轉變為可搜尋文字。