如何在 C# 中使用 Tesseract OCR 置信度值 | IronOCR

如何運用IronOCR提升 C# OCR 讀取的信心

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

IronOCR 的讀取置信度表示 OCR 系統對識別文字準確性的確定程度,取值範圍為 0 到 100,分數越高表示可靠性越高——可透過任何 OcrResult 物件上的 Confidence 屬性存取它。

OCR(光學字元辨識)的讀取置信度是指 OCR 系統對影像或文件中辨識出的文字的準確性所賦予的確定性或可靠性等級。 它是衡量 OCR 系統對識別文本正確性的信心程度的指標。 在處理掃描文件照片或任何文字品質可能有所不同的影像時,此指標尤其重要。

置信度分數越高,表示辨識結果的準確度越有把握;而信賴度分數越低,表示辨識結果的可靠性可能較低。 了解這些置信度等級有助於開發人員在應用程式中實現適當的驗證邏輯和錯誤處理。

快速入門:一行程式碼即可掌握 OCR 讀取技巧

使用 IronTesseract 的 Read 方法和圖像檔案路徑,然後存取返回的 OcrResultConfidence 屬性,以查看IronOCR對其文本識別的確定性如何。 這是一種簡單可靠的評估 OCR 輸出準確性的方法。

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

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

    double confidence = new IronOcr.IronTesseract().Read("input.png").Confidence;
  3. 部署到您的生產環境進行測試

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

    arrow pointer


如何提升C#的閱讀理解能力?

對輸入影像執行 OCR 後,文字的置信度會儲存在Confidence屬性中。 使用"using"語句可以在使用後自動釋放物件。 分別使用 OcrImageInputOcrPdfInput 類別新增影像和 PDF 等文件。 Read 方法將傳回一個OcrResult對象,允許存取Confidence屬性。

:path=/static-assets/ocr/content-code-examples/how-to/tesseract-result-confidence-get-confidence.cs
using IronOcr;

// Instantiate IronTesseract
IronTesseract ocrTesseract = new IronTesseract();

// Add image
using var imageInput = new OcrImageInput("sample.tiff");
// Perform OCR
OcrResult ocrResult = ocrTesseract.Read(imageInput);

// Get confidence level
double confidence = ocrResult.Confidence;
$vbLabelText   $csharpLabel

傳回的置信度值範圍為 0 到 100,其中:

  • 90-100 :極佳的置信度 - 文字高度可靠
  • 80-89 :置信度良好-文字整體準確,僅有少量不確定性
  • 70-79 :中等置信度 - 文字可能包含一些錯誤 -低於 70 :低置信度 - 文字應進行審核或重新處理

如何在不同層面建立自信?

您不僅可以獲得整個文件的置信度,還可以存取每一頁、段落、行、單字和字元的置信度。 此外,您還可以獲得區塊的置信度,該區塊表示一個或多個緊密相鄰的段落的集合。

:path=/static-assets/ocr/content-code-examples/how-to/tesseract-result-confidence-confidence-level.cs
// Get page confidence level
double pageConfidence = ocrResult.Pages[0].Confidence;

// Get paragraph confidence level
double paragraphConfidence = ocrResult.Paragraphs[0].Confidence;

// Get line confidence level
double lineConfidence = ocrResult.Lines[0].Confidence;

// Get word confidence level
double wordConfidence = ocrResult.Words[0].Confidence;

// Get character confidence level
double characterConfidence = ocrResult.Characters[0].Confidence;

// Get block confidence level
double blockConfidence = ocrResult.Blocks[0].Confidence;
$vbLabelText   $csharpLabel

實際範例:按置信度篩選

處理品質參差不齊的文件(例如低品質掃描件)時,可以使用置信度評分來篩選結果:

using IronOcr;
using System.Linq;

// Instantiate IronTesseract
IronTesseract ocrTesseract = new IronTesseract();

// Configure for better accuracy
ocrTesseract.Configuration.ReadBarCodes = false;
ocrTesseract.Configuration.PageSegmentationMode = TesseractPageSegmentationMode.AutoOsd;

// Add image
using var imageInput = new OcrImageInput("invoice.png");
// Apply filters to improve quality
imageInput.Deskew();
imageInput.DeNoise();

// Perform OCR
OcrResult ocrResult = ocrTesseract.Read(imageInput);

// Filter words with confidence above 85%
var highConfidenceWords = ocrResult.Words
    .Where(word => word.Confidence >= 85)
    .Select(word => word.Text)
    .ToList();

// Process only high-confidence text
string reliableText = string.Join(" ", highConfidenceWords);
Console.WriteLine($"High confidence text: {reliableText}");

// Flag low-confidence words for manual review
var lowConfidenceWords = ocrResult.Words
    .Where(word => word.Confidence < 85)
    .Select(word => new { word.Text, word.Confidence })
    .ToList();

foreach (var word in lowConfidenceWords)
{
    Console.WriteLine($"Review needed: '{word.Text}' (Confidence: {word.Confidence:F2}%)");
}
using IronOcr;
using System.Linq;

// Instantiate IronTesseract
IronTesseract ocrTesseract = new IronTesseract();

// Configure for better accuracy
ocrTesseract.Configuration.ReadBarCodes = false;
ocrTesseract.Configuration.PageSegmentationMode = TesseractPageSegmentationMode.AutoOsd;

// Add image
using var imageInput = new OcrImageInput("invoice.png");
// Apply filters to improve quality
imageInput.Deskew();
imageInput.DeNoise();

// Perform OCR
OcrResult ocrResult = ocrTesseract.Read(imageInput);

// Filter words with confidence above 85%
var highConfidenceWords = ocrResult.Words
    .Where(word => word.Confidence >= 85)
    .Select(word => word.Text)
    .ToList();

// Process only high-confidence text
string reliableText = string.Join(" ", highConfidenceWords);
Console.WriteLine($"High confidence text: {reliableText}");

// Flag low-confidence words for manual review
var lowConfidenceWords = ocrResult.Words
    .Where(word => word.Confidence < 85)
    .Select(word => new { word.Text, word.Confidence })
    .ToList();

foreach (var word in lowConfidenceWords)
{
    Console.WriteLine($"Review needed: '{word.Text}' (Confidence: {word.Confidence:F2}%)");
}
$vbLabelText   $csharpLabel

OCR中的字元選項有哪些?

除了置信水準之外,還有另一個有趣的屬性叫做選擇。 選項中包含備選詞語清單及其統計相關性。 此資訊允許使用者存取其他可能的角色。 當使用多種語言或特殊字體時,此功能尤其有用。

:path=/static-assets/ocr/content-code-examples/how-to/tesseract-result-confidence-get-choices.cs
using IronOcr;
using static IronOcr.OcrResult;

// Instantiate IronTesseract
IronTesseract ocrTesseract = new IronTesseract();

// Add image
using var imageInput = new OcrImageInput("Potter.tiff");
// Perform OCR
OcrResult ocrResult = ocrTesseract.Read(imageInput);

// Get choices
Choice[] choices = ocrResult.Characters[0].Choices;
$vbLabelText   $csharpLabel

不同的角色選擇有何幫助?

不同的角色選擇會帶來以下幾個好處:

1.歧義消除:當字元"O"和"0",或"l"和"1"混淆時
2.字體變體:風格化或裝飾字體的不同詮釋
3.品質問題:處理降級文字時可能出現多種問題
4.語言語境:基於語言規則的不同解釋

OCR字元選擇偵錯視圖,顯示

角色選擇

以下是一個全面的範例,示範如何透過角色選擇來提高準確率:

using IronOcr;
using System;
using System.Linq;
using static IronOcr.OcrResult;

// Configure IronTesseract for detailed results
IronTesseract ocrTesseract = new IronTesseract();

// Process image with potential ambiguities
using var imageInput = new OcrImageInput("ambiguous_text.png");
OcrResult ocrResult = ocrTesseract.Read(imageInput);

// Analyze character choices for each word
foreach (var word in ocrResult.Words)
{
    Console.WriteLine($"\nWord: '{word.Text}' (Confidence: {word.Confidence:F2}%)");

    // Check each character in the word
    foreach (var character in word.Characters)
    {
        if (character.Choices != null && character.Choices.Length > 1)
        {
            Console.WriteLine($"  Character '{character.Text}' has alternatives:");

            // Display all choices sorted by confidence
            foreach (var choice in character.Choices.OrderByDescending(c => c.Confidence))
            {
                Console.WriteLine($"    - '{choice.Text}': {choice.Confidence:F2}%");
            }
        }
    }
}
using IronOcr;
using System;
using System.Linq;
using static IronOcr.OcrResult;

// Configure IronTesseract for detailed results
IronTesseract ocrTesseract = new IronTesseract();

// Process image with potential ambiguities
using var imageInput = new OcrImageInput("ambiguous_text.png");
OcrResult ocrResult = ocrTesseract.Read(imageInput);

// Analyze character choices for each word
foreach (var word in ocrResult.Words)
{
    Console.WriteLine($"\nWord: '{word.Text}' (Confidence: {word.Confidence:F2}%)");

    // Check each character in the word
    foreach (var character in word.Characters)
    {
        if (character.Choices != null && character.Choices.Length > 1)
        {
            Console.WriteLine($"  Character '{character.Text}' has alternatives:");

            // Display all choices sorted by confidence
            foreach (var choice in character.Choices.OrderByDescending(c => c.Confidence))
            {
                Console.WriteLine($"    - '{choice.Text}': {choice.Confidence:F2}%");
            }
        }
    }
}
$vbLabelText   $csharpLabel

進階自信策略

在處理護照車牌MICR支票特殊文件時,置信度評分對於驗證至關重要:

using IronOcr;

public class DocumentValidator
{
    private readonly IronTesseract ocr = new IronTesseract();

    public bool ValidatePassportNumber(string imagePath, double minConfidence = 95.0)
    {
        using var input = new OcrImageInput(imagePath);

        // Configure for passport reading
        ocr.Configuration.ReadBarCodes = true;
        ocr.Configuration.PageSegmentationMode = TesseractPageSegmentationMode.SingleLine;

        // Apply preprocessing
        input.Deskew();
        input.Scale(200); // Upscale for better accuracy

        var result = ocr.Read(input);

        // Find passport number pattern
        var passportLine = result.Lines
            .Where(line => line.Text.Contains("P<") || IsPassportNumberFormat(line.Text))
            .FirstOrDefault();

        if (passportLine != null)
        {
            Console.WriteLine($"Passport line found: {passportLine.Text}");
            Console.WriteLine($"Confidence: {passportLine.Confidence:F2}%");

            // Only accept if confidence meets threshold
            return passportLine.Confidence >= minConfidence;
        }

        return false;
    }

    private bool IsPassportNumberFormat(string text)
    {
        // Simple passport number validation
        return System.Text.RegularExpressions.Regex.IsMatch(text, @"^[A-Z]\d{7,9}$");
    }
}
using IronOcr;

public class DocumentValidator
{
    private readonly IronTesseract ocr = new IronTesseract();

    public bool ValidatePassportNumber(string imagePath, double minConfidence = 95.0)
    {
        using var input = new OcrImageInput(imagePath);

        // Configure for passport reading
        ocr.Configuration.ReadBarCodes = true;
        ocr.Configuration.PageSegmentationMode = TesseractPageSegmentationMode.SingleLine;

        // Apply preprocessing
        input.Deskew();
        input.Scale(200); // Upscale for better accuracy

        var result = ocr.Read(input);

        // Find passport number pattern
        var passportLine = result.Lines
            .Where(line => line.Text.Contains("P<") || IsPassportNumberFormat(line.Text))
            .FirstOrDefault();

        if (passportLine != null)
        {
            Console.WriteLine($"Passport line found: {passportLine.Text}");
            Console.WriteLine($"Confidence: {passportLine.Confidence:F2}%");

            // Only accept if confidence meets threshold
            return passportLine.Confidence >= minConfidence;
        }

        return false;
    }

    private bool IsPassportNumberFormat(string text)
    {
        // Simple passport number validation
        return System.Text.RegularExpressions.Regex.IsMatch(text, @"^[A-Z]\d{7,9}$");
    }
}
$vbLabelText   $csharpLabel

優化以獲得更強的信心

為了獲得更高的置信度,可以考慮使用影像濾波器和預處理技術:

using IronOcr;

// Create an optimized OCR workflow
IronTesseract ocr = new IronTesseract();

using var input = new OcrImageInput("low_quality_scan.jpg");

// Apply multiple filters to improve confidence
input.Deskew();           // Correct rotation
input.DeNoise();          // Remove noise
input.Sharpen();          // Enhance edges
input.Dilate();           // Thicken text
input.Scale(150);         // Upscale for clarity

// Configure for accuracy over speed
ocr.Configuration.TesseractVersion = TesseractVersion.Tesseract5;
ocr.Configuration.EngineMode = TesseractEngineMode.TesseractOnly;

var result = ocr.Read(input);

Console.WriteLine($"Document confidence: {result.Confidence:F2}%");

// Generate confidence report
var confidenceReport = result.Pages
    .Select((page, index) => new
    {
        PageNumber = index + 1,
        Confidence = page.Confidence,
        WordCount = page.Words.Length,
        LowConfidenceWords = page.Words.Count(w => w.Confidence < 80)
    });

foreach (var page in confidenceReport)
{
    Console.WriteLine($"Page {page.PageNumber}: {page.Confidence:F2}% confidence");
    Console.WriteLine($"  Total words: {page.WordCount}");
    Console.WriteLine($"  Low confidence words: {page.LowConfidenceWords}");
}
using IronOcr;

// Create an optimized OCR workflow
IronTesseract ocr = new IronTesseract();

using var input = new OcrImageInput("low_quality_scan.jpg");

// Apply multiple filters to improve confidence
input.Deskew();           // Correct rotation
input.DeNoise();          // Remove noise
input.Sharpen();          // Enhance edges
input.Dilate();           // Thicken text
input.Scale(150);         // Upscale for clarity

// Configure for accuracy over speed
ocr.Configuration.TesseractVersion = TesseractVersion.Tesseract5;
ocr.Configuration.EngineMode = TesseractEngineMode.TesseractOnly;

var result = ocr.Read(input);

Console.WriteLine($"Document confidence: {result.Confidence:F2}%");

// Generate confidence report
var confidenceReport = result.Pages
    .Select((page, index) => new
    {
        PageNumber = index + 1,
        Confidence = page.Confidence,
        WordCount = page.Words.Length,
        LowConfidenceWords = page.Words.Count(w => w.Confidence < 80)
    });

foreach (var page in confidenceReport)
{
    Console.WriteLine($"Page {page.PageNumber}: {page.Confidence:F2}% confidence");
    Console.WriteLine($"  Total words: {page.WordCount}");
    Console.WriteLine($"  Low confidence words: {page.LowConfidenceWords}");
}
$vbLabelText   $csharpLabel

概括

理解和利用 OCR 置信度評分對於建立強大的文件處理應用程式至關重要。 透過利用 IronOCR 的置信度屬性和字元選擇功能,開發人員可以在其 OCR 工作流程中實現智慧驗證、錯誤處理和品質保證機制。 無論您是處理螢幕截圖表格還是專業文檔,置信度評分都能提供確保準確提取文字所需的指標。

常見問題解答

什麼是 OCR 信心,為什麼它很重要?

OCR 置信度是一個從 0 到 100 的度量,表示 OCR 系統對文字辨識準確性的肯定程度。IronOCR 透過任何 OcrResult 物件上的 Confidence 屬性提供此度量,協助開發人員評估辨識文字的可靠性,尤其是在處理掃描文件、照片或文字品質不一的影像時。

如何在 C# 中快速檢查 OCR 的信心?

使用 IronOCR,您只需要一行程式碼就可以得到 OCR 的信心值: double confidence = new IronOcr.IronTesseract().Read("input.png").Confidence; 這會回傳一個 0-100 之間的信心分數,表示 IronOCR 對於文字辨識的肯定程度。

不同的置信度分數範圍代表什麼意思?

IronOCR 信心分數表示:90-100 (優) 表示文字高度可靠;80-89 (良) 表示文字大致準確,但有輕微的不確定性;70-79 (中) 表示文字可能包含一些錯誤;低於 70 (低) 表示文字應該重新檢閱或處理。

如何存取不同文字元素的置信度?

IronOCR 可讓您擷取多重粒度的置信度 - 頁面、段落、行、字詞和個別字元。執行 OCR 之後,您可以透過 OcrResult 物件結構存取各層級的置信度屬性。

我可以得到有信心分數的替代詞建議嗎?

是的,IronOCR 提供了一個「選擇」(Choices)屬性,可提供其他的字詞選擇以及它們的置信度分數。當 OCR 引擎識別出同一文字的多種可能解釋時,此功能會有所幫助,讓您可以實作智慧型驗證邏輯。

如何在我的應用程式中實作信心驗證?

使用 IronOCR 的 Read 方法後,檢查 OcrResult 的 Confidence 屬性。根據置信度臨界值實施條件邏輯 - 例如,自動接受 90 分以上的結果,標記 70-90 分之間的結果以供審查,並重新處理或手動驗證 70 分以下的結果。

Curtis Chau
技術作家

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

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

審核人
Jeff Fritz
Jeffrey T. Fritz
首席程序经理 - .NET 社群团队
Jeff 也是 .NET 和 Visual Studio 团队的首席程序经理。他是 .NET Conf 虚拟会议系列的执行制作人,并主持“Fritz 和朋友”这一每周两次的開發者的直播节目,在节目上讨论技術并与观众一起编写代碼。Jeff 撰写研讨会、主持演讲,并计划大型 Microsoft 開發者活動(包括 Microsoft Build、Microsoft Ignite、.NET Conf 和 Microsoft MVP Summit)的內容。
準備好開始了嗎?
Nuget 下載 5,525,971 | 版本: 2026.3 剛剛發布
Still Scrolling Icon

還在捲動嗎?

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