如何在 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 对象上的置信度属性提供这一度量,帮助开发人员评估识别文本的可靠性,尤其是在处理扫描文档、照片或文本质量不一的图像时。

如何在 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 提供了一个 "选择 "属性,可提供其他单词选择及其置信度分数。当 OCR 引擎识别出同一文本的多种可能解释时,该功能将有所帮助,使您可以实施智能验证逻辑。

如何在应用程序中实施基于置信度的验证?

使用 IronOCR 的读取方法后,检查 OcrResult 的置信度属性。根据置信度阈值实施条件逻辑--例如,自动接受 90 分以上的结果,标记 70-90 分之间的结果以供审核,重新处理或手动验证 70 分以下的结果。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,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 峰会在内的最大型微软开发者活动的内容。
准备开始了吗?
Nuget 下载 5,525,971 | 版本: 2026.3 刚刚发布
Still Scrolling Icon

还在滚动吗?

想快速获得证据? PM > Install-Package IronOcr
运行示例 观看您的图像变成可搜索文本。