自动化文档处理可以显著提高各种行业的生产力和准确性,从法律和金融服务到医疗保健和制造业。 这个任务的一个强大的工具是 Aspose.OCR for .NET,这使开发人员能够以高精度从扫描文件和图像中提取文本。

完整的例子

下面是一个完整的例子(作为一个)展示如何使用 Aspose.OCR for .NET 在一个目录中的多个图像上进行OCR,并将提取的文本存储到相应的文字文件。

步骤指南

步骤1:启动 OCR 发动机

创建和配置 OCR 引擎. 设置所需语言(此示例中的英语)。

// Step 1: Initialize the OCR Engine
using Aspose.Ocr;

using (Ocr ocrEngine = new Ocr())
{
    // Set language and other configurations if needed
    ocrEngine.Language = Language.English;

    // (Continue with steps below inside this using block)
}

步骤2:加载图像处理

设置输入/输出目录,确保输出的文件夹存在,并列出图像文件。

// Step 2: Load Images for Processing
string inputDirectory = @"path\to\input\images";
string outputDirectory = @"path\to\output\text";

if (!Directory.Exists(outputDirectory))
{
    Directory.CreateDirectory(outputDirectory);
}

// Get all files from the input directory (same pattern as the gist)
// TIP: to restrict to specific formats, replace "*.*" with "*.png" or "*.jpg"
string[] imageFiles = Directory.GetFiles(
    inputDirectory,
    "*.*",
    SearchOption.TopDirectoryOnly
);

步骤3:在每个图像上执行 OCR

将文件传输并使用文本识别 RecognizeImage(string path).

// Step 3: Perform OCR on Each Image
foreach (string imageFile in imageFiles)
{
    try
    {
        // Recognize text from the image (exactly as in the gist)
        string recognizedText = ocrEngine.RecognizeImage(imageFile);

        // Proceed to Step 4: save text to disk...
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Error processing {imageFile}: {ex.Message}");
    }
}

步骤4:将提取的文本保存到文件中

创建一个相应的 .txt 每个处理图像的文件。

// Step 4: Save Extracted Text to Files
string outputFilePath = Path.Combine(
    outputDirectory,
    Path.GetFileNameWithoutExtension(imageFile) + ".txt"
);

File.WriteAllText(outputFilePath, recognizedText);

Console.WriteLine($"Processed: {imageFile} -> {outputFilePath}");

提示和推文

  • 过滤格式:使用模型如 "*.png""*.jpg" 删除非图像文件。
  • 重定向字符串: 变更 SearchOption.TopDirectoryOnlySearchOption.AllDirectories.
  • 船空出口:如果 string.IsNullOrWhiteSpace(recognizedText)登录并继续。
  • ** 平行套件**:使用 Parallel.ForEach(imageFiles, file => { ... }) 更快的跑步(思想 I/O 和许可证)。

通过遵循这些步骤,您可以自动使用 Aspose.OCR 为 .NET 进行包装 OCR 并为下流处理出口干净的文本文件。

More in this category