如何在 .NET 中使用 Aspose.OCR FOSS Core API
Aspose.OCR FOSS for .NET 通过一个小型核心 API:AsposeOcr, OcrInput, OcrOutput, 和 RecognitionResult,来识别光栅图像和 PDF 文档中的文本。本指南将逐步演示如何安装该软件包并端到端使用该核心 API。
分步指南
步骤 1: 安装软件包
dotnet add package Aspose.OCR.FOSS步骤 2: 导入命名空间
在任何调用 AsposeOcr, OcrInput, 或 RecognitionResult 的源文件中添加 Aspose.OCR 命名空间:
using Aspose.OCR;此单一命名空间公开 AsposeOcr、OcrInput、OcrOutput、InputType 和 RecognitionResult。
步骤 3:构建一个 OcrInput 并识别图像
构建一个 AsposeOcr,使用 InputType.SingleImage 构建一个 OcrInput,使用 OcrInput.Add() 将文件排队,并调用 AsposeOcr.Recognize()。
var api = new AsposeOcr();
using var input = new OcrInput(InputType.SingleImage);
input.Add("scan.png");
RecognitionResult result = api.Recognize(input)[0];
Console.WriteLine(result.RecognitionText);步骤 4:读取单独的行和边界框
在 RecognitionLinesResult 中的每个 RecognitionResult.LinesResult 条目包含一行文本(TextInLine)及其像素坐标边界框(Line)。
foreach (RecognitionResult.LinesResult line in result.RecognitionLinesResult)
{
System.Drawing.Rectangle bounds = line.Line;
Console.WriteLine($"x={bounds.X}, y={bounds.Y}: {line.TextInLine}");
}步骤 5:识别多页 PDF
对于 InputType.PDF,AsposeOcr.Recognize() 按源顺序为每页返回一个 RecognitionResult。
using var pdfInput = new OcrInput(InputType.PDF);
pdfInput.Add("document.pdf");
OcrOutput output = api.Recognize(pdfInput);
foreach (RecognitionResult page in output)
{
Console.WriteLine(page.RecognitionText);
}常见问题与解决方案
NotSupportedException 调用时 Recognize(). 该 OcrInput 使用了除…之外的输入类型构建 InputType.SingleImage or InputType.PDF. 仅支持这两种输入类型。
FileNotFoundException 调用时 Recognize(). 通过…添加的路径 OcrInput.Add() 不存在于磁盘上。调用前请验证路径 Add().
ArgumentNullException 调用时 Recognize(). null 被传入而不是 an OcrInput 实例。始终构造 an OcrInput 首先。
Empty RecognitionLinesResult. 未检测到文本行 — 请确认源图像包含可辨认、未旋转的拉丁文字。
常见问题
OcrOutput 是否保留文件顺序?
是的。OcrOutput 是一个 RecognitionResult 列表,每个图像(或每个 PDF 页面)对应一个,顺序与通过 OcrInput.Add() 添加文件的顺序相同。
我需要处理 OcrInput 吗?
是的 — OcrInput 实现了 IDisposable。使用 using 语句或在识别完成后显式调用 Dispose()。
我可以在同一个 OcrInput 中处理图像和 PDF 吗?
不 — 每个 OcrInput 都是使用单一的 InputType(SingleImage 或 PDF)构建的,并且只能接受该类型的文件。