如何在 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屬性存取。

在OCR(光學字元識別)中,讀取信心水準指的是OCR系統對圖像或文件中已識別文字的準確性所賦予的確定性或可靠性水平。 這是衡量OCR系統對已識別文字是否正確的信心水準。 這個指標在處理掃描文件照片或任何文字質量可能不同的圖像時顯得尤為重要。

高信心得分表示識別的準確性很高,而低信心得分則表明識別可能不太可靠。 了解這些信心水準有助於開發者在應用程式中實現適當的驗證邏輯和錯誤處理。

快速入門:在一行中獲取OCR讀取信心水準

使用Confidence屬性,以查看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'語句來自動釋放用過的物件。 分別使用OcrPdfInput類新增圖像和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;
Imports IronOcr

' Instantiate IronTesseract
Private ocrTesseract As New IronTesseract()

' Add image
Private imageInput = New OcrImageInput("sample.tiff")
' Perform OCR
Private ocrResult As OcrResult = ocrTesseract.Read(imageInput)

' Get confidence level
Private confidence As Double = 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;
' Get page confidence level
Dim pageConfidence As Double = ocrResult.Pages(0).Confidence

' Get paragraph confidence level
Dim paragraphConfidence As Double = ocrResult.Paragraphs(0).Confidence

' Get line confidence level
Dim lineConfidence As Double = ocrResult.Lines(0).Confidence

' Get word confidence level
Dim wordConfidence As Double = ocrResult.Words(0).Confidence

' Get character confidence level
Dim characterConfidence As Double = ocrResult.Characters(0).Confidence

' Get block confidence level
Dim blockConfidence As Double = ocrResult.Blocks(0).Confidence
$vbLabelText   $csharpLabel

實用範例:按信心水準過濾

在處理品質不同的文件(例如低品質掃描件)時,您可以使用信心得分來過濾結果:

:path=/static-assets/ocr/content-code-examples/how-to/tesseract-result-confidence-4.cs
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}%)");
}
Imports IronOcr
Imports System.Linq

' Instantiate IronTesseract
Dim ocrTesseract As New IronTesseract()

' Configure for better accuracy
ocrTesseract.Configuration.ReadBarCodes = False
ocrTesseract.Configuration.PageSegmentationMode = TesseractPageSegmentationMode.AutoOsd

' Add image
Using imageInput As New OcrImageInput("invoice.png")
    ' Apply filters to improve quality
    imageInput.Deskew()
    imageInput.DeNoise()

    ' Perform OCR
    Dim ocrResult As OcrResult = ocrTesseract.Read(imageInput)

    ' Filter words with confidence above 85%
    Dim highConfidenceWords = ocrResult.Words _
        .Where(Function(word) word.Confidence >= 85) _
        .Select(Function(word) word.Text) _
        .ToList()

    ' Process only high-confidence text
    Dim reliableText As String = String.Join(" ", highConfidenceWords)
    Console.WriteLine($"High confidence text: {reliableText}")

    ' Flag low-confidence words for manual review
    Dim lowConfidenceWords = ocrResult.Words _
        .Where(Function(word) word.Confidence < 85) _
        .Select(Function(word) New With {Key .Text = word.Text, Key .Confidence = word.Confidence}) _
        .ToList()

    For Each word In lowConfidenceWords
        Console.WriteLine($"Review needed: '{word.Text}' (Confidence: {word.Confidence:F2}%)")
    Next
End Using
$vbLabelText   $csharpLabel

OCR中的字元選擇是什麼?

除了信心水準外,還有另一個有趣的屬性叫Choices。 選擇包含替代單詞選擇的列表及其統計相關性。 此資訊允許使用者存取其他可能的字元。 此功能在處理多語言或專用字體時特別有用。

: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;
Imports IronOcr
Imports IronOcr.OcrResult

' Instantiate IronTesseract
Private ocrTesseract As New IronTesseract()

' Add image
Private imageInput = New OcrImageInput("Potter.tiff")
' Perform OCR
Private ocrResult As OcrResult = ocrTesseract.Read(imageInput)

' Get choices
Private choices() As Choice = ocrResult.Characters(0).Choices
$vbLabelText   $csharpLabel

替代字元選擇如何提供幫助?

替代字元選擇提供多項好處:

  1. 疑義解決:當'O'和'0'、'l'和'1'混淆時
  2. 字體變化:對於樣式化或裝飾性字體的不同解釋
  3. 品質問題:處理劣化文字時的多個可能性
  4. 語言上下文:基於語言規則的替代解釋
OCR字元選擇除錯視圖展示信心得分和'第八章'的文字識別結果

使用字元選擇

這是一個全面的範例,展示如何利用字元選擇來提高準確性:

:path=/static-assets/ocr/content-code-examples/how-to/tesseract-result-confidence-6.cs
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}%");
            }
        }
    }
}
Imports IronOcr
Imports System
Imports System.Linq
Imports IronOcr.OcrResult

' Configure IronTesseract for detailed results
Dim ocrTesseract As New IronTesseract()

' Process image with potential ambiguities
Using imageInput As New OcrImageInput("ambiguous_text.png")
    Dim ocrResult As OcrResult = ocrTesseract.Read(imageInput)

    ' Analyze character choices for each word
    For Each word In ocrResult.Words
        Console.WriteLine(vbCrLf & $"Word: '{word.Text}' (Confidence: {word.Confidence:F2}%)")

        ' Check each character in the word
        For Each character In word.Characters
            If character.Choices IsNot Nothing AndAlso character.Choices.Length > 1 Then
                Console.WriteLine($"  Character '{character.Text}' has alternatives:")

                ' Display all choices sorted by confidence
                For Each choice In character.Choices.OrderByDescending(Function(c) c.Confidence)
                    Console.WriteLine($"    - '{choice.Text}': {choice.Confidence:F2}%")
                Next
            End If
        Next
    Next
End Using
$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}$");
    }
}
Imports IronOcr

Public Class DocumentValidator
    Private ReadOnly ocr As New IronTesseract()

    Public Function ValidatePassportNumber(imagePath As String, Optional minConfidence As Double = 95.0) As Boolean
        Using input As 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

            Dim result = ocr.Read(input)

            ' Find passport number pattern
            Dim passportLine = result.Lines _
                .Where(Function(line) line.Text.Contains("P<") OrElse IsPassportNumberFormat(line.Text)) _
                .FirstOrDefault()

            If passportLine IsNot Nothing Then
                Console.WriteLine($"Passport line found: {passportLine.Text}")
                Console.WriteLine($"Confidence: {passportLine.Confidence:F2}%")

                ' Only accept if confidence meets threshold
                Return passportLine.Confidence >= minConfidence
            End If

            Return False
        End Using
    End Function

    Private Function IsPassportNumberFormat(text As String) As Boolean
        ' Simple passport number validation
        Return System.Text.RegularExpressions.Regex.IsMatch(text, "^[A-Z]\d{7,9}$")
    End Function
End Class
$vbLabelText   $csharpLabel

優化以獲得更好的信心

為了達到更高的信心水準,考慮使用圖像過濾和預處理技術:

:path=/static-assets/ocr/content-code-examples/how-to/tesseract-result-confidence-8.cs
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}");
}
Imports IronOcr

' Create an optimized OCR workflow
Dim ocr As New IronTesseract()

Using input As 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

    Dim result = ocr.Read(input)

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

    ' Generate confidence report
    Dim confidenceReport = result.Pages.Select(Function(page, index) New With {
        .PageNumber = index + 1,
        .Confidence = page.Confidence,
        .WordCount = page.Words.Length,
        .LowConfidenceWords = page.Words.Count(Function(w) w.Confidence < 80)
    })

    For Each 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}")
    Next

End Using
$vbLabelText   $csharpLabel

總結

理解並利用OCR信心水準是構建強健的文件處理應用程式的關鍵。 通過利用IronOCR的信心屬性和字元選擇,開發者可以在OCR工作流程中實現智能驗證、錯誤處理和品質保證機制。 無論您是否在處理截圖表格或專用文件,信心得分提供了必要的指標來確保準確的文字提取。

常見問題

什麼是 OCR 信心及其重要性?

OCR 信心是一種從 0 到 100 的衡量標準,表示 OCR 系統對文字識別準確性的確定程度。IronOCR 透過 OcrResult 物件上的 Confidence 屬性提供此指標,幫助開發人員評估識別文字的可靠性,特別是在處理掃描文件、照片或文字品質不均的圖像時。

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

using 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 物件結構存取每個層級的 Confidence 屬性。

我可以獲得帶有信心評分的替代單詞建議嗎?

是的,IronOCR 提供一個 Choices 屬性,提供替代單詞選擇及其信心評分。當 OCR 引擎識別相同文字的多個可能解釋時,此功能有助於實現智能驗證邏輯。

如何在應用程式中實施基於信心的驗證?

在使用 IronOCR 的 Read 方法後,檢查 OcrResult 的 Confidence 屬性。基於信心水準設定條件邏輯——例如,自動接受高於 90 的結果,標記 70-90 之間的結果供審查,而對低於 70 的結果進行重新處理或手動驗證。

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機器人,結合他對技術的熱愛與創造力。

由...審核
Jeff Fritz
Jeffrey T. Fritz
首席計劃經理 - .NET社區團隊
Jeff還是.NET和Visual Studio團隊的首席計劃經理。他是.NET Conf虛擬會議系列的執行製作人,並主持每週兩次的開發者直播節目'Fritz and Friends',在節目中討論技術並與觀眾一起撰寫程式碼。Jeff撰寫工作坊、演講和內容計劃,為微軟開發者的最大活動如Microsoft Build、Microsoft Ignite、.NET Conf和Microsoft MVP Summit提供內容支援。
準備開始了嗎?
Nuget 下載 6,136,090 | 版本: 2026.7 剛剛發布
Still Scrolling Icon

還在滾動?

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