在C#中使用IronOCR将文本突出显示为图像
IronOCR 的 HighlightTextAndSaveAsImages 方法通过在检测到的文本(字符、单词、行或段落)周围绘制边界框来可视化 OCR 结果,并将它们另存为诊断图像,使开发人员可以验证 OCR 准确性和调试识别问题。
可视化 OCR 结果包括在引擎检测到的图像中的特定文本元素周围呈现边界框。 该流程可在单个字符、单词、行或段落的准确位置上叠加明显的高亮标记,提供清晰的识别内容地图。
这种可视化反馈对于调试和验证 OCR 输出的准确性至关重要,它可以显示软件已经识别出的内容和出错的地方。 在处理复杂文档或排除识别问题时,可视化高亮显示成为必不可少的诊断工具。
本文演示了 IronOCR 的诊断功能及其 HighlightTextAndSaveAsImages 方法。 该功能可突出显示文本的特定部分,并将其保存为图像以供验证。 无论是构建文档处理系统、实施质量控制措施,还是验证您的 OCR 实施,该功能都能就 OCR 引擎检测到的内容提供即时的可视化反馈。
此片段演示了 IronOCR 的用法:加载 PDF 文件并高亮显示文档中的每个单词,然后将结果保存为图像。 只需一行即可获得 OCR 结果的视觉反馈。
-
1使用 IronOCR 安装 NuGet Package Manager
-
2复制并运行这段代码。
new IronOcr.OcrInput().LoadPdf("document.pdf").HighlightTextAndSaveAsImages(new IronOcr.IronTesseract(), "highlight_page_", IronOcr.ResultHighlightType.Word);Dim ocrInput As New IronOcr.OcrInput() ocrInput.LoadPdf("document.pdf").HighlightTextAndSaveAsImages(New IronOcr.IronTesseract(), "highlight_page_", IronOcr.ResultHighlightType.Word)Dim ocrInput As New IronOcr.OcrInput() ocrInput.LoadPdf("document.pdf").HighlightTextAndSaveAsImages(New IronOcr.IronTesseract(), "highlight_page_", IronOcr.ResultHighlightType.Word) -
3部署到您的生产环境中进行测试
今天就用免费试用在您的项目中开始使用IronOCR
最小工作流程(4 个步骤)
- 下载并安装 IronOCR C# 库
- 实例化 OCR 引擎
- 使用
LoadPdf加载 PDF 文档 - 使用
HighlightTextAndSaveAsImages突出显示文本部分并将其保存为图像
如何突出显示文本并保存为图像?
使用 IronOCR 可以直接突出显示文本并将其保存为图片。 使用 LoadPdf 加载现有 PDF,然后调用 HighlightTextAndSaveAsImages 方法以突出显示文本部分并将其保存为图像。 该技术可验证 OCR 的准确性并调试文档中的文本识别问题。
该方法接受三个参数:IronTesseract OCR 引擎、输出文件名前缀以及 ResultHighlightType 中的枚举,用于指示要突出显示的文本类型。 此示例使用 ResultHighlightType.Paragraph 将文本块突出显示为段落。HighlightTextAndSaveAsImages
本示例使用的 PDF 有三个段落。
输入 PDF 看起来像什么?
如何实现高亮代码?
下面的示例代码演示了使用 OcrInput 类 的基本实现。
using IronOcr;
IronTesseract ocrTesseract = new IronTesseract();
using var ocrInput = new OcrInput();
ocrInput.LoadPdf("document.pdf");
ocrInput.HighlightTextAndSaveAsImages(ocrTesseract, "highlight_page_", ResultHighlightType.Paragraph);using IronOcr;
IronTesseract ocrTesseract = new IronTesseract();
using var ocrInput = new OcrInput();
ocrInput.LoadPdf("document.pdf");
ocrInput.HighlightTextAndSaveAsImages(ocrTesseract, "highlight_page_", ResultHighlightType.Paragraph);Imports IronOcr
Dim ocrTesseract As New IronTesseract()
Using ocrInput As New OcrInput()
ocrInput.LoadPdf("document.pdf")
ocrInput.HighlightTextAndSaveAsImages(ocrTesseract, "highlight_page_", ResultHighlightType.Paragraph)
End UsingImports IronOcr
Dim ocrTesseract As New IronTesseract()
Using ocrInput As New OcrInput()
ocrInput.LoadPdf("document.pdf")
ocrInput.HighlightTextAndSaveAsImages(ocrTesseract, "highlight_page_", ResultHighlightType.Paragraph)
End Using输出图像显示什么?

如上图所示,所有三个段落都用浅红色方框突出显示。 这种可视化的表达方式可以帮助开发人员快速识别 OCR 引擎是如何将文档分割成可读区块的。
结果高亮类型有哪些不同选择?
上面的例子使用 ResultHighlightType.Paragraph 突出显示文本块。 IronOCR 通过此枚举提供额外的突出显示选项。 以下是可用类型的完整列表,每种类型都有不同的诊断用途。
字符: 在 OCR 引擎检测到的每个字符周围绘制一个边界框。对于调试字符识别或特种字体特别有用,尤其是在使用自定义语言文件时。
单词: 突出显示引擎识别的每个完整单词。非常适合验证单词边界和正确的单词识别,特别是在实现条形码和 QR 读取时。
行: 突出显示每个检测到的文本行。对于需要行识别验证的复杂布局文档很有用,例如在处理扫描文档时。
段落: 突出显示作为段落分组的整个文本块。非常适合理解文档布局并验证文本块分段,特别是在使用表格提取时非常有用。
如何比较不同的高亮类型?
本综合示例演示了在同一文档中生成所有不同类型的高亮内容,您可以对结果进行比较:
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!");Imports IronOcr
Imports System
' Initialize the OCR engine with custom configuration
Dim ocrTesseract As 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 ocrInput As 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)
End Using
Console.WriteLine("All highlight images have been generated successfully!")Imports IronOcr
Imports System
' Initialize the OCR engine with custom configuration
Dim ocrTesseract As 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 ocrInput As 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)
End Using
Console.WriteLine("All highlight images have been generated successfully!")如何处理多页文档?
在处理多页 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");Imports IronOcr
Imports System.IO
Dim ocrTesseract As New IronTesseract()
' Load a multi-page document
Using ocrInput As New OcrInput()
ocrInput.LoadPdf("multi-page-document.pdf")
' Create output directory if it doesn't exist
Dim outputDir As String = "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
Dim pageCount As Integer = Directory.GetFiles(outputDir, "page_*.png").Length
Console.WriteLine($"Generated {pageCount} highlighted page images")
End UsingImports IronOcr
Imports System.IO
Dim ocrTesseract As New IronTesseract()
' Load a multi-page document
Using ocrInput As New OcrInput()
ocrInput.LoadPdf("multi-page-document.pdf")
' Create output directory if it doesn't exist
Dim outputDir As String = "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
Dim pageCount As Integer = Directory.GetFiles(outputDir, "page_*.png").Length
Console.WriteLine($"Generated {pageCount} highlighted page images")
End Using性能最佳实践是什么?
使用高亮功能时,请考虑以下最佳实践:
- 文件大小: 高亮的图像可能很大,特别是对于高分辨率文档。 在处理大批量文件时,请考虑输出目录的可用空间。 有关优化技巧,请参见我们的快速 OCR 配置指南。
- 性能: 生成高亮增加了处理开销。 对于偶尔需要突出显示的生产系统,应将其作为单独的诊断流程而不是主要工作流程的一部分来实施。 考虑使用多线程 OCR 进行批处理。
- 错误处理: 处理文件操作时始终实施适当的错误处理:
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
}Imports System
Try
Using ocrInput As 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)
End Using
Catch ex As Exception
Console.WriteLine($"Error during highlighting: {ex.Message}")
' Log error details for debugging
End TryImports System
Try
Using ocrInput As 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)
End Using
Catch ex As Exception
Console.WriteLine($"Error during highlighting: {ex.Message}")
' Log error details for debugging
End Try高亮如何与 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);
}
}Public Class OcrDebugger
Private ReadOnly _tesseract As IronTesseract
Private ReadOnly _debugMode As Boolean
Public Sub New(Optional enableDebugMode As Boolean = False)
_tesseract = New IronTesseract()
_debugMode = enableDebugMode
End Sub
Public Function ProcessDocument(filePath As String) As OcrResult
Using input As New OcrInput()
input.LoadPdf(filePath)
' Apply preprocessing
input.Deskew()
input.DeNoise()
' Generate debug highlights if in debug mode
If _debugMode Then
Dim debugPath As String = $"debug_{Path.GetFileNameWithoutExtension(filePath)}_"
input.HighlightTextAndSaveAsImages(_tesseract, debugPath, ResultHighlightType.Word)
End If
' Perform actual OCR
Return _tesseract.Read(input)
End Using
End Function
End ClassPublic Class OcrDebugger
Private ReadOnly _tesseract As IronTesseract
Private ReadOnly _debugMode As Boolean
Public Sub New(Optional enableDebugMode As Boolean = False)
_tesseract = New IronTesseract()
_debugMode = enableDebugMode
End Sub
Public Function ProcessDocument(filePath As String) As OcrResult
Using input As New OcrInput()
input.LoadPdf(filePath)
' Apply preprocessing
input.Deskew()
input.DeNoise()
' Generate debug highlights if in debug mode
If _debugMode Then
Dim debugPath As String = $"debug_{Path.GetFileNameWithoutExtension(filePath)}_"
input.HighlightTextAndSaveAsImages(_tesseract, debugPath, ResultHighlightType.Word)
End If
' Perform actual OCR
Return _tesseract.Read(input)
End Using
End Function
End Class下一步我应该去哪里?
现在您已了解如何使用高亮显示功能,请继续探索:
- 从您的 OCR 结果创建可搜索的 PDF
- 阅读特定文档类型,如护照或许可证
- 使用我们的快速入门指南在您的开发环境中设置 IronOCR
- 为全球应用程序提供 125 种国际语言支持
- 使用滤镜向导优化图像处理
对于生产使用,请记得获取许可证来去除水印并访问完整的功能。
常见问题
IronOCR如何在图像中突出显示文本?
IronOCR使用 HighlightTextAndSaveAsImages 方法来可视化OCR结果。它为检测到的文本(如字符、单词、行或段落)绘制边界框,并将其保存为图像。
为什么在OCR中突出显示文本很有用?
文本突出显示对于调试和验证OCR输出的准确性非常有用。它提供了OCR引擎检测到的内容的视觉反馈,有助于识别复杂文档中的识别错误。
如何使用IronOCR在PDF文档中实现文本突出显示?
您可以使用 LoadPdf 加载PDF文档,并使用IronOCR的 HighlightTextAndSaveAsImages 方法。这将突出显示指定的文本元素并将结果保存为图像。
IronOCR中的不同ResultHighlightType选项是什么?
IronOCR提供了不同的 ResultHighlightType 选项,包括字符、单词、行和段落,每个选项都用于文本识别的不同诊断目的。
IronOCR可以处理多页文档进行文本突出显示吗?
是的,IronOCR可以处理多页文档,如PDF或TIFF文件,自动逐页处理并为每页生成相应的高亮图像。
在生产环境中使用突出显示功能时我应该考虑什么?
使用突出显示功能时,请考虑文件大小和处理开销。如果即时反馈不是必需的,最好将突出显示实现为单独的诊断过程。
如何解决IronOCR中空白输出图像的问题?
确保输入文档包含可读文本,并且OCR引擎配置正确。您可能还需要对图像进行优化或调整方向以改善结果。
使用IronOCR高亮功能时应遵循哪些性能最佳实践?
通过确保有足够的可用空间来管理大型高亮图像,并考虑实现多线程以提高速度。对于文件操作,还应进行适当的错误处理。
Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。