請求書OCR API(開発者チュートリアル)
Invoice OCR APIは、機械学習を用いて請求書データの抽出を自動化し、手入力によるエラーを排除しながら、デジタル文書とスキャン文書の両方からベンダーの詳細、請求書番号、価格を正確に抽出します。 このチュートリアルでは、 IronOCRを使用して請求書の OCR ソリューションを構築する方法を説明します。
Invoice OCR技術は、機械学習とコンピュータビジョンを活用することで、請求書データを自動処理に適した形式に変換します。 手作業によるデータ入力の遅延、コスト、エラーといった一般的な課題に対処しながら、あらゆる形式の請求書から仕入先情報、請求書番号、価格を正確に抽出する方法を学びます。
この記事では、 .NET開発者向けの主要な請求書OCR APIであるIronOCRを使用しています。
請求書OCR APIの作成方法
- 請求書OCR APIをダウンロードしてインストールする
- Visual Studioで新しいC#プロジェクトを作成するか、既存のプロジェクトを開く。
- Load an existing image file using ``OcrInput`` method
- `Ocr.Read`メソッドを使用して画像からテキストを抽出します。
- Print the extracted text in Console using `Console.`WriteLine``
IronOCRとは何ですか?
Iron Software社が開発したIronOCRは、開発者向けに包括的なOCRツールを提供します。 機械学習とコンピューター ビジョンを使用して、スキャンされたドキュメント、画像、PDF からテキストを抽出し、自動処理を可能にします。 そのAPIは様々な言語やプラットフォームとシームレスに統合され、手作業によるデータ入力ミスを減らし、効率性を向上させます。 抽出されたデータは、分析と意思決定のために既存のシステムに直接取り込まれる。 画像前処理、バーコード認識、柔軟なファイル解析といった機能により、その汎用性が向上している。 IronOCRは、開発者が高度なテキスト認識機能をアプリケーションに組み込むことを可能にします。
この図書館は、専用の言語パックを通じて125の国際言語をサポートしており、グローバルな請求書処理に最適です。 高度な機能としては、テキストを自動的に検出するコンピュータビジョン機能があり、レイアウトが多様な請求書などに特に役立ちます。 さらに、 IronOCRはマルチスレッド処理機能を備えており、大量の請求書処理を効率的に行うことができます。
IronOCRを請求書処理に利用すべき理由は何ですか?
IronOCRは、請求書処理アプリケーションにおいて魅力的な利点を提供します。 まず、最適化されたTesseract 5エンジンにより、卓越した精度を実現しています。このエンジンは、特に.NETアプリケーション向けに強化されています。 図書館では、スキャンされた文書からPDFファイル、さらには低品質のスキャン画像まで、さまざまな形式の請求書を取り扱っています。
内蔵の画像最適化フィルターが処理前に画像品質を自動的に向上させ、より正確なテキスト抽出を実現します。 特定の要件を持つ請求書の場合、 IronOCRはカスタム言語トレーニングをサポートしており、請求書の種類でよく見られる独自のフォントやフォーマットに合わせて最適化を行うことができます。
IronOCRは他のOCRライブラリと何が違うのか?
IronOCRは、エンタープライズレベルの機能を維持しながらも、シンプルな1行OCR機能によって他社製品との差別化を図っています。 Tesseractの生の実装とは異なり、 IronOCRは複雑な操作をシームレスに処理するマネージド.NET APIを提供します。 当図書館では、さまざまな種類の文書に対応した専門的な文書読み取り方法を提供しており、請求書の明細項目に不可欠な、文書内の表の読み取り専用のサポートも含まれています。
フィルターウィザードは、特定の請求書画像に最適な前処理設定を自動的に判断するため、最適化における推測作業が不要になります。 IronOCRは包括的なデバッグ機能も提供しており、開発者はOCRエンジンが何を見ているかを視覚化し、抽出に関する問題を効果的にトラブルシューティングできます。
どのような前提条件が必要ですか?
IronOCRを使用する前に、以下の前提条件が満たされていることを確認してください。
- Visual StudioなどのIDEがインストールされた適切な開発環境
- C#プログラミングの基礎知識を持ち、コード例を効果的に理解・修正できること
- NuGetパッケージマネージャーまたはコマンドラインを使用して、プロジェクトにIronOCRライブラリをインストールします。
これらの前提条件を満たせば、 IronOCRをスムーズに使いこなせるようになります。
IronOCRは、 Windows 、 Linux 、 macOS向けの包括的なセットアップガイドを提供しています。 このライブラリはクラウドへのデプロイをサポートしており、 AWS LambdaとAzure Functions向けの具体的なチュートリアルも用意されています。
どのバージョンのVisual Studioを使用すべきですか?
IronOCRは、Visual Studioの2017から最新リリースまでのバージョンをサポートしています。 最適な互換性と最新のC#機能へのアクセスを確保するには、Visual Studio 2019または2022の使用をお勧めします。 このライブラリは、 .NET Framework、 .NET Core、および.NET 5以降と完全に互換性があり、開発環境における柔軟性を確保します。
クロスプラットフォーム開発には、C#拡張機能を備えたVisual Studio Codeが最適です。 モバイル開発者は、IronOCRのAndroidおよびiOS実装に関するガイダンスを活用できるため、 .NET MAUIアプリケーションにも適しています。
必要なC#の知識レベルは?
基本的な請求書OCRの実装には、中級レベルのC#の知識があれば十分です。 あなたは以下の点に抵抗を感じないはずです。
オブジェクト指向プログラミングの概念 ストリームとファイルI/Oの操作
- 基本的なasync/awaitパターン
- パターンマッチングのための正規表現
- 堅牢なエラー管理のための例外処理
IronOCRの直感的なAPI設計により、画像処理や機械学習に関する高度な専門知識は必要ありません。 ライブラリが複雑な処理を内部的に行うため、あなたはビジネスロジックに集中できます。 初心者は、簡単なOCRの例から始めることができます。
新しい Visual Studio プロジェクトを作成するにはどうすればよいですか?
IronOCRを使い始めるには、まずVisual Studioで新しいプロジェクトを作成します。
Visual Studioを開き、"ファイル"メニューから"新規"にカーソルを合わせ、"プロジェクト"をクリックします。
新しいプロジェクト
新しいウィンドウで"コンソールアプリケーション"を選択し、"次へ"をクリックします。
コンソールアプリケーション
新しいウィンドウが表示されます。 プロジェクト名と場所を入力し、"次へ"をクリックしてください。
プロジェクト設定
最後に、ターゲットフレームワークを選択し、"作成"をクリックします。
ターゲットフレームワーク
新しいVisual Studioプロジェクトの準備ができました。 IronOCRをインストールしましょう。
OCRアプリケーションに最適なプロジェクトタイプはどれですか?
このチュートリアルでは簡略化のためコンソールアプリケーションを使用していますが、 IronOCRは様々なプロジェクトタイプをサポートしています。
-コンソールアプリケーション:バッチ処理やコマンドラインツールに最適
- Webアプリケーション:APIやWebベースのサービスの構築に最適です。
- Windows Forms/WPF :GUIを備えたデスクトップアプリケーションに適しています
- .NET MAUIアプリ:クロスプラットフォームソリューション向け
大量のデータを処理する場合は、 IronOCRをWindowsサービスまたはマイクロサービスアーキテクチャで実装することを検討してください。 図書館の進捗状況追跡機能により、長時間にわたる作業の監視が容易になります。
どの.NET Frameworkバージョンをターゲットにすべきですか?
IronOCRは、 .NETの各バージョン間で幅広い互換性を提供します。 新規プロジェクトでは、最適なパフォーマンスと最新機能を利用するために、 .NET 6.0以降をターゲットにしてください。 このライブラリは優れた後方互換性を維持しています。
- .NET Framework 4.6.2以降:レガシーEnterpriseアプリケーション向け
- .NET Core 3.1 :安定したデプロイメントのための長期サポート
- .NET 5.0以降:パフォーマンスが向上した最新のフレームワーク
- .NET Standard 2.0 :プラットフォーム間での最大限の互換性
Dockerコンテナにデプロイする場合、 .NET 6.0以降を使用すると、イメージサイズが小さくなり、パフォーマンスが向上します。 Azure Functionsでは、 .NET 6.0と.NET Frameworkの両方がサポートされています。
IronOCRはどのようにインストールすればよいですか?
IronOCRをダウンロードしてインストールするには、2つの簡単な方法があります。
- Visual Studio NuGetパッケージ マネージャーの使用
- Visual Studio コマンドラインの使用
NuGetパッケージマネージャーとコマンドラインは、それぞれどのような場合に使い分けるべきでしょうか?
ワークフローに応じて、 NuGetパッケージマネージャーのGUIとコマンドラインのどちらかを選択してください。
NuGetパッケージ マネージャー GUI は、次のような場合に最も効果的です。
- NuGetパッケージを初めて使用する IronOCRの言語パックを閲覧したい
- 視覚的な確認を好む
- 複数のパッケージを管理します
コマンドライン(パッケージマネージャコンソール)が特に優れているのは、次のような場合です。 コマンドインターフェースの操作に慣れている
- スクリプト化されたデプロイメントに従います
- 特定のバージョンをすぐに必要とする -高度なインストールオプションを使用する
どちらの方法でも同じ結果が得られます。快適さやニーズに基づいて選択してください。
他にどのような言語パックが必要になる可能性がありますか?
IronOCRは、専用パックを通じて125の国際言語をサポートしています。 請求書処理に関しては、以下を考慮してください。
-業種別パック:財務文書用の財務言語パック -地域言語:請求書の発行元言語に基づく(スペイン語、フランス語、ドイツ語) -多言語対応:複数の言語で記載された請求書に対応 -カスタム言語:特殊なフォントやカスタムトレーニングデータ用
言語パックはメインのIronOCRパッケージと同時にインストールされ、英語以外のテキストの認識精度を大幅に向上させます。
Visual Studio NuGetパッケージマネージャーを使用する
Visual StudioのNuGetパッケージマネージャーを使用して、 IronOCRをC#プロジェクトに組み込みます。
ツール> NuGetパッケージ マネージャー>ソリューションのNuGetパッケージの管理に移動します。
NuGetパッケージマネージャー
IronOCRを検索し、プロジェクトにパッケージをインストールしてください。
NuGet パッケージ マネージャー UI で IronOCR パッケージを選択します。
同じ方法で追加の言語パックをインストールしてください。
Visual Studio コマンドラインの使用
- Visual Studioで、 [ツール] > [NuGet パッケージ マネージャー] > [パッケージ マネージャー コンソール]に移動します。
-
パッケージマネージャーコンソールに以下のコマンドを入力します。
Install-Package IronOcr
パッケージマネージャーコンソール
パッケージはダウンロードされ、現在のプロジェクトにインストールされると、すぐに使用できるようになります。
IronOCRを使用して請求書からデータを抽出するにはどうすればよいですか?
IronOCRを使えば、わずか数行のコードで請求書データを簡単に抽出できます。 これにより、手作業によるデータ入力が不要になり、ワークフローが効率化されます。
以下は、テキスト抽出用の請求書の例です。
サンプル請求書
この請求書からすべてのデータを抽出してみましょう。
using IronOcr;
using System;
// Initialize a new instance of the IronTesseract class
// This is the main OCR engine that will process our invoice
var ocr = new IronTesseract();
// Configure OCR settings for better invoice processing
ocr.Configuration.BlackListCharacters = "~`$#^*_}{]___PROTECTED_LINK_48___ method from ___PROTECTED_LINK_49___ class. Key enhancements include:
- **Image preprocessing**: ___PROTECTED_LINK_50___ corrects tilted scans; ___PROTECTED_LINK_51___ removes artifacts
- **Resolution enhancement**: Setting ___PROTECTED_LINK_52___ improves recognition
- **Character blacklisting**: Prevents common OCR misinterpretations
- **Confidence scoring**: Assesses extraction reliability
!___PROTECTED_LINK_53___
**Invoice Parser**
### How Do I Handle Different Invoice Formats?
Invoice formats vary between vendors, but IronOCR provides flexible solutions:
1. **Template-based**: Define ___PROTECTED_LINK_54___
2. **Computer vision**: Use ___PROTECTED_LINK_55___ to locate text
3. **Table extraction**: Leverage ___PROTECTED_LINK_56___ for line items
4. **Multi-format**: Process ___PROTECTED_LINK_57___, ___PROTECTED_LINK_58___, and ___PROTECTED_LINK_59___
For complex layouts, implement the ___PROTECTED_LINK_60___ which uses machine learning to identify structures automatically.
### What Are Common Extraction Patterns for Invoice Data?
Invoice data follows recognizable patterns extractable using regular expressions with OCR results:
```csharp
using IronOcr;
using System;
using System.Text.`RegularExpressions`;
using System.Collections.Generic;
public class `InvoiceDataExtractor`
{
private readonly `IronTesseract` ocr;
public `InvoiceDataExtractor`()
{
ocr = new `IronTesseract`();
// Configure for optimal invoice reading
`ocr.Configuration`.`ReadBarcodes` = true; // Many invoices include barcodes
`ocr.Configuration`.`TesseractVersion` = `TesseractVersion`.Tesseract5;
}
public `InvoiceData` `ExtractInvoiceData`(string imagePath)
{
var invoiceData = new `InvoiceData`();
using (var input = new `OcrInput`(imagePath))
{
// Apply filters for better accuracy
input.`EnhanceResolution`(300);
`input.Sharpen`();
var result = `ocr.Read`(input);
var text = `result.Text`;
// Extract invoice number
invoiceData.`InvoiceNumber` = `ExtractPattern`(text,
@"INV[/-]?\d{4}[/-]?\d{5}|Invoice\s*#?\s*:?\s*(\d+)");
// Extract dates
invoiceData.`InvoiceDate` = `ExtractDate`(text,
@"Invoice\s*Date\s*:?\s*(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})");
invoiceData.`DueDate` = `ExtractDate`(text,
@"Due\s*Date\s*:?\s*(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})");
// Extract amounts
`invoiceData.Total` = `ExtractAmount`(text,
@"Total\s*:?\s*\$?\s*([\d,]+\.?\d*)");
`invoiceData.Tax` = `ExtractAmount`(text,
@"Tax\s*:?\s*\$?\s*([\d,]+\.?\d*)");
// Extract vendor information
invoiceData.`VendorName` = `ExtractVendorName`(text);
// Extract line items using table detection
invoiceData.`LineItems` = `ExtractLineItems`(result);
// Extract any barcodes found
if (`result.Barcodes`.Length > 0)
{
invoiceData.`BarcodeValues` = new List<string>();
foreach (var barcode in `result.Barcodes`)
{
invoiceData.`BarcodeValues`.Add(`barcode.Value`);
}
}
}
return invoiceData;
}
private string `ExtractPattern`(string text, string pattern)
{
var match = Regex.Match(text, pattern, `RegexOptions`.`IgnoreCase`);
return `match.Success` ? `match.Value` : `string.Empty`;
}
private `DateTime`? `ExtractDate`(string text, string pattern)
{
var match = Regex.Match(text, pattern, `RegexOptions`.`IgnoreCase`);
if (`match.Success` && `match.Groups`.Count > 1)
{
if (`DateTime`.`TryParse`(`match.Groups`[1].Value, out `DateTime` date))
return date;
}
return null;
}
private decimal `ExtractAmount`(string text, string pattern)
{
var match = Regex.Match(text, pattern, `RegexOptions`.`IgnoreCase`);
if (`match.Success` && `match.Groups`.Count > 1)
{
var amountStr = `match.Groups`[1].Value.Replace(",", "");
if (decimal.`TryParse`(amountStr, out decimal amount))
return amount;
}
return 0;
}
private string `ExtractVendorName`(string text)
{
// Usually the vendor name appears in the first few lines
var lines = `text.Split`('\n');
if (`lines.Length` > 0)
{
// Simple heuristic: first non-empty line that's not a common header
foreach (var line in lines)
{
var trimmed = `line.Trim`();
if (!string.`IsNullOrEmpty`(trimmed) &&
!trimmed.`ToLower`().Contains("invoice") &&
`trimmed.Length` > 3)
{
return trimmed;
}
}
}
return `string.Empty`;
}
private List<`LineItem`> `ExtractLineItems`(`OcrResult` result)
{
var lineItems = new List<`LineItem`>();
// Use IronOCR's table detection capabilities
if (`result.Tables` != null && `result.Tables`.Count > 0)
{
foreach (var table in `result.Tables`)
{
// Process each row as a potential line item
for (int i = 1; i < table.`RowCount`; i++) // Skip header row
{
var item = new `LineItem`
{
Description = table[i, 0]?.Text ?? "",
Quantity = `ParseQuantity`(table[i, 1]?.Text),
`UnitPrice` = `ParseAmount`(table[i, 2]?.Text),
Total = `ParseAmount`(table[i, 3]?.Text)
};
if (!string.`IsNullOrEmpty`(`item.Description`))
`lineItems.Add`(item);
}
}
}
return lineItems;
}
private int `ParseQuantity`(string text)
{
if (string.`IsNullOrEmpty`(text)) return 0;
var cleaned = Regex.Replace(text, @"[^\d]", "");
return int.`TryParse`(cleaned, out int qty) ? qty : 0;
}
private decimal `ParseAmount`(string text)
{
if (string.`IsNullOrEmpty`(text)) return 0;
var cleaned = Regex.Replace(text, @"[^\d.]", "");
return decimal.`TryParse`(cleaned, out decimal amt) ? amt : 0;
}
}
// Data classes for structured invoice information
public class `InvoiceData`
{
public string `InvoiceNumber` { get; set; }
public `DateTime`? `InvoiceDate` { get; set; }
public `DateTime`? `DueDate` { get; set; }
public string `VendorName` { get; set; }
public decimal Total { get; set; }
public decimal Tax { get; set; }
public List<`LineItem`> `LineItems` { get; set; }
public List<string> `BarcodeValues` { get; set; }
}
public class `LineItem`
{
public string Description { get; set; }
public int Quantity { get; set; }
public decimal `UnitPrice` { get; set; }
public decimal Total { get; set; }
}
using IronOcr;
using System;
// Initialize a new instance of the IronTesseract class
// This is the main OCR engine that will process our invoice
var ocr = new IronTesseract();
// Configure OCR settings for better invoice processing
ocr.Configuration.BlackListCharacters = "~`$#^*_}{]___PROTECTED_LINK_48___ method from ___PROTECTED_LINK_49___ class. Key enhancements include:
- **Image preprocessing**: ___PROTECTED_LINK_50___ corrects tilted scans; ___PROTECTED_LINK_51___ removes artifacts
- **Resolution enhancement**: Setting ___PROTECTED_LINK_52___ improves recognition
- **Character blacklisting**: Prevents common OCR misinterpretations
- **Confidence scoring**: Assesses extraction reliability
!___PROTECTED_LINK_53___
**Invoice Parser**
### How Do I Handle Different Invoice Formats?
Invoice formats vary between vendors, but IronOCR provides flexible solutions:
1. **Template-based**: Define ___PROTECTED_LINK_54___
2. **Computer vision**: Use ___PROTECTED_LINK_55___ to locate text
3. **Table extraction**: Leverage ___PROTECTED_LINK_56___ for line items
4. **Multi-format**: Process ___PROTECTED_LINK_57___, ___PROTECTED_LINK_58___, and ___PROTECTED_LINK_59___
For complex layouts, implement the ___PROTECTED_LINK_60___ which uses machine learning to identify structures automatically.
### What Are Common Extraction Patterns for Invoice Data?
Invoice data follows recognizable patterns extractable using regular expressions with OCR results:
```csharp
using IronOcr;
using System;
using System.Text.`RegularExpressions`;
using System.Collections.Generic;
public class `InvoiceDataExtractor`
{
private readonly `IronTesseract` ocr;
public `InvoiceDataExtractor`()
{
ocr = new `IronTesseract`();
// Configure for optimal invoice reading
`ocr.Configuration`.`ReadBarcodes` = true; // Many invoices include barcodes
`ocr.Configuration`.`TesseractVersion` = `TesseractVersion`.Tesseract5;
}
public `InvoiceData` `ExtractInvoiceData`(string imagePath)
{
var invoiceData = new `InvoiceData`();
using (var input = new `OcrInput`(imagePath))
{
// Apply filters for better accuracy
input.`EnhanceResolution`(300);
`input.Sharpen`();
var result = `ocr.Read`(input);
var text = `result.Text`;
// Extract invoice number
invoiceData.`InvoiceNumber` = `ExtractPattern`(text,
@"INV[/-]?\d{4}[/-]?\d{5}|Invoice\s*#?\s*:?\s*(\d+)");
// Extract dates
invoiceData.`InvoiceDate` = `ExtractDate`(text,
@"Invoice\s*Date\s*:?\s*(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})");
invoiceData.`DueDate` = `ExtractDate`(text,
@"Due\s*Date\s*:?\s*(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})");
// Extract amounts
`invoiceData.Total` = `ExtractAmount`(text,
@"Total\s*:?\s*\$?\s*([\d,]+\.?\d*)");
`invoiceData.Tax` = `ExtractAmount`(text,
@"Tax\s*:?\s*\$?\s*([\d,]+\.?\d*)");
// Extract vendor information
invoiceData.`VendorName` = `ExtractVendorName`(text);
// Extract line items using table detection
invoiceData.`LineItems` = `ExtractLineItems`(result);
// Extract any barcodes found
if (`result.Barcodes`.Length > 0)
{
invoiceData.`BarcodeValues` = new List<string>();
foreach (var barcode in `result.Barcodes`)
{
invoiceData.`BarcodeValues`.Add(`barcode.Value`);
}
}
}
return invoiceData;
}
private string `ExtractPattern`(string text, string pattern)
{
var match = Regex.Match(text, pattern, `RegexOptions`.`IgnoreCase`);
return `match.Success` ? `match.Value` : `string.Empty`;
}
private `DateTime`? `ExtractDate`(string text, string pattern)
{
var match = Regex.Match(text, pattern, `RegexOptions`.`IgnoreCase`);
if (`match.Success` && `match.Groups`.Count > 1)
{
if (`DateTime`.`TryParse`(`match.Groups`[1].Value, out `DateTime` date))
return date;
}
return null;
}
private decimal `ExtractAmount`(string text, string pattern)
{
var match = Regex.Match(text, pattern, `RegexOptions`.`IgnoreCase`);
if (`match.Success` && `match.Groups`.Count > 1)
{
var amountStr = `match.Groups`[1].Value.Replace(",", "");
if (decimal.`TryParse`(amountStr, out decimal amount))
return amount;
}
return 0;
}
private string `ExtractVendorName`(string text)
{
// Usually the vendor name appears in the first few lines
var lines = `text.Split`('\n');
if (`lines.Length` > 0)
{
// Simple heuristic: first non-empty line that's not a common header
foreach (var line in lines)
{
var trimmed = `line.Trim`();
if (!string.`IsNullOrEmpty`(trimmed) &&
!trimmed.`ToLower`().Contains("invoice") &&
`trimmed.Length` > 3)
{
return trimmed;
}
}
}
return `string.Empty`;
}
private List<`LineItem`> `ExtractLineItems`(`OcrResult` result)
{
var lineItems = new List<`LineItem`>();
// Use IronOCR's table detection capabilities
if (`result.Tables` != null && `result.Tables`.Count > 0)
{
foreach (var table in `result.Tables`)
{
// Process each row as a potential line item
for (int i = 1; i < table.`RowCount`; i++) // Skip header row
{
var item = new `LineItem`
{
Description = table[i, 0]?.Text ?? "",
Quantity = `ParseQuantity`(table[i, 1]?.Text),
`UnitPrice` = `ParseAmount`(table[i, 2]?.Text),
Total = `ParseAmount`(table[i, 3]?.Text)
};
if (!string.`IsNullOrEmpty`(`item.Description`))
`lineItems.Add`(item);
}
}
}
return lineItems;
}
private int `ParseQuantity`(string text)
{
if (string.`IsNullOrEmpty`(text)) return 0;
var cleaned = Regex.Replace(text, @"[^\d]", "");
return int.`TryParse`(cleaned, out int qty) ? qty : 0;
}
private decimal `ParseAmount`(string text)
{
if (string.`IsNullOrEmpty`(text)) return 0;
var cleaned = Regex.Replace(text, @"[^\d.]", "");
return decimal.`TryParse`(cleaned, out decimal amt) ? amt : 0;
}
}
// Data classes for structured invoice information
public class `InvoiceData`
{
public string `InvoiceNumber` { get; set; }
public `DateTime`? `InvoiceDate` { get; set; }
public `DateTime`? `DueDate` { get; set; }
public string `VendorName` { get; set; }
public decimal Total { get; set; }
public decimal Tax { get; set; }
public List<`LineItem`> `LineItems` { get; set; }
public List<string> `BarcodeValues` { get; set; }
}
public class `LineItem`
{
public string Description { get; set; }
public int Quantity { get; set; }
public decimal `UnitPrice` { get; set; }
public decimal Total { get; set; }
}
Imports IronOcr
Imports System
Imports System.Text.RegularExpressions
Imports System.Collections.Generic
Public Class InvoiceDataExtractor
Private ReadOnly ocr As IronTesseract
Public Sub New()
ocr = New IronTesseract()
' Configure for optimal invoice reading
ocr.Configuration.ReadBarcodes = True ' Many invoices include barcodes
ocr.Configuration.TesseractVersion = TesseractVersion.Tesseract5
End Sub
Public Function ExtractInvoiceData(imagePath As String) As InvoiceData
Dim invoiceData As New InvoiceData()
Using input As New OcrInput(imagePath)
' Apply filters for better accuracy
input.EnhanceResolution(300)
input.Sharpen()
Dim result = ocr.Read(input)
Dim text = result.Text
' Extract invoice number
invoiceData.InvoiceNumber = ExtractPattern(text, "INV[/-]?\d{4}[/-]?\d{5}|Invoice\s*#?\s*:?\s*(\d+)")
' Extract dates
invoiceData.InvoiceDate = ExtractDate(text, "Invoice\s*Date\s*:?\s*(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})")
invoiceData.DueDate = ExtractDate(text, "Due\s*Date\s*:?\s*(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})")
' Extract amounts
invoiceData.Total = ExtractAmount(text, "Total\s*:?\s*\$?\s*([\d,]+\.?\d*)")
invoiceData.Tax = ExtractAmount(text, "Tax\s*:?\s*\$?\s*([\d,]+\.?\d*)")
' Extract vendor information
invoiceData.VendorName = ExtractVendorName(text)
' Extract line items using table detection
invoiceData.LineItems = ExtractLineItems(result)
' Extract any barcodes found
If result.Barcodes.Length > 0 Then
invoiceData.BarcodeValues = New List(Of String)()
For Each barcode In result.Barcodes
invoiceData.BarcodeValues.Add(barcode.Value)
Next
End If
End Using
Return invoiceData
End Function
Private Function ExtractPattern(text As String, pattern As String) As String
Dim match = Regex.Match(text, pattern, RegexOptions.IgnoreCase)
Return If(match.Success, match.Value, String.Empty)
End Function
Private Function ExtractDate(text As String, pattern As String) As DateTime?
Dim match = Regex.Match(text, pattern, RegexOptions.IgnoreCase)
If match.Success AndAlso match.Groups.Count > 1 Then
Dim dateValue As DateTime
If DateTime.TryParse(match.Groups(1).Value, dateValue) Then
Return dateValue
End If
End If
Return Nothing
End Function
Private Function ExtractAmount(text As String, pattern As String) As Decimal
Dim match = Regex.Match(text, pattern, RegexOptions.IgnoreCase)
If match.Success AndAlso match.Groups.Count > 1 Then
Dim amountStr = match.Groups(1).Value.Replace(",", "")
Dim amount As Decimal
If Decimal.TryParse(amountStr, amount) Then
Return amount
End If
End If
Return 0
End Function
Private Function ExtractVendorName(text As String) As String
' Usually the vendor name appears in the first few lines
Dim lines = text.Split(ControlChars.Lf)
If lines.Length > 0 Then
' Simple heuristic: first non-empty line that's not a common header
For Each line In lines
Dim trimmed = line.Trim()
If Not String.IsNullOrEmpty(trimmed) AndAlso
Not trimmed.ToLower().Contains("invoice") AndAlso
trimmed.Length > 3 Then
Return trimmed
End If
Next
End If
Return String.Empty
End Function
Private Function ExtractLineItems(result As OcrResult) As List(Of LineItem)
Dim lineItems As New List(Of LineItem)()
' Use IronOCR's table detection capabilities
If result.Tables IsNot Nothing AndAlso result.Tables.Count > 0 Then
For Each table In result.Tables
' Process each row as a potential line item
For i As Integer = 1 To table.RowCount - 1 ' Skip header row
Dim item As New LineItem With {
.Description = If(table(i, 0)?.Text, ""),
.Quantity = ParseQuantity(table(i, 1)?.Text),
.UnitPrice = ParseAmount(table(i, 2)?.Text),
.Total = ParseAmount(table(i, 3)?.Text)
}
If Not String.IsNullOrEmpty(item.Description) Then
lineItems.Add(item)
End If
Next
Next
End If
Return lineItems
End Function
Private Function ParseQuantity(text As String) As Integer
If String.IsNullOrEmpty(text) Then Return 0
Dim cleaned = Regex.Replace(text, "[^\d]", "")
Dim qty As Integer
Return If(Integer.TryParse(cleaned, qty), qty, 0)
End Function
Private Function ParseAmount(text As String) As Decimal
If String.IsNullOrEmpty(text) Then Return 0
Dim cleaned = Regex.Replace(text, "[^\d.]", "")
Dim amt As Decimal
Return If(Decimal.TryParse(cleaned, amt), amt, 0)
End Function
End Class
' Data classes for structured invoice information
Public Class InvoiceData
Public Property InvoiceNumber As String
Public Property InvoiceDate As DateTime?
Public Property DueDate As DateTime?
Public Property VendorName As String
Public Property Total As Decimal
Public Property Tax As Decimal
Public Property LineItems As List(Of LineItem)
Public Property BarcodeValues As List(Of String)
End Class
Public Class LineItem
Public Property Description As String
Public Property Quantity As Integer
Public Property UnitPrice As Decimal
Public Property Total As Decimal
End Class
請求書処理:請求書から特定のデータを抽出します。
このコードを使用すると、顧客の請求書番号などの特定の請求書データを抽出できます。
using IronOcr;
using System;
using System.Text.`RegularExpressions`;
// Initialize a new instance of the `IronTesseract` class
var ocr = new `IronTesseract`();
// Use the `OcrInput` object to load the image file
using (var input = new `OcrInput`(@"`r2.png`"))
{
// Perform OCR on the image
var result = `ocr.Read`(input);
// Define a regular expression pattern for the invoice number
var linePattern = @"INV\/\d{4}\/\d{5}";
// Match the pattern in the extracted text
var lineMatch = Regex.Match(`result.Text`, linePattern);
// Check if the pattern matches any part of the text
if (`lineMatch.Success`)
{
// If a match is found, print the invoice number
var lineValue = `lineMatch.Value`;
Console.`WriteLine`("Customer Invoice number: " + lineValue);
}
}
using IronOcr;
using System;
using System.Text.`RegularExpressions`;
// Initialize a new instance of the `IronTesseract` class
var ocr = new `IronTesseract`();
// Use the `OcrInput` object to load the image file
using (var input = new `OcrInput`(@"`r2.png`"))
{
// Perform OCR on the image
var result = `ocr.Read`(input);
// Define a regular expression pattern for the invoice number
var linePattern = @"INV\/\d{4}\/\d{5}";
// Match the pattern in the extracted text
var lineMatch = Regex.Match(`result.Text`, linePattern);
// Check if the pattern matches any part of the text
if (`lineMatch.Success`)
{
// If a match is found, print the invoice number
var lineValue = `lineMatch.Value`;
Console.`WriteLine`("Customer Invoice number: " + lineValue);
}
}
Imports IronOcr
Imports System
Imports System.Text.RegularExpressions
' Initialize a new instance of the IronTesseract class
Dim ocr As New IronTesseract()
' Use the OcrInput object to load the image file
Using input As New OcrInput("r2.png")
' Perform OCR on the image
Dim result = ocr.Read(input)
' Define a regular expression pattern for the invoice number
Dim linePattern As String = "INV/\d{4}/\d{5}"
' Match the pattern in the extracted text
Dim lineMatch As Match = Regex.Match(result.Text, linePattern)
' Check if the pattern matches any part of the text
If lineMatch.Success Then
' If a match is found, print the invoice number
Dim lineValue As String = lineMatch.Value
Console.WriteLine("Customer Invoice number: " & lineValue)
End If
End Using
請求書のスキャン
複雑な抽出シナリオの場合は、請求書の種類に合わせて最適化された専用のOCR設定を使用してください。OcrResultクラスは、認識された各要素に関する詳細情報(座標や検証のための信頼度スコアなど)を提供します。
請求書OCR APIの主なメリットは何ですか?
IronOCRの請求書OCR APIは、機械学習とコンピュータビジョンを活用して請求書処理を変革します。 この技術は、請求書のテキストを機械可読形式に変換することで、分析、統合、およびプロセス改善のためのデータ抽出を簡素化します。 請求書処理のための堅牢な自動化機能を提供し、精度を向上させ、買掛金などのワークフローを最適化します。
IronOCRは、追加の設定なしに最適化されたTesseractの結果を使用することで、卓越した精度を実現します。 マルチページフレームの TIFF 、 PDF ファイル、およびすべての一般的な画像形式をサポートします。 画像からのバーコード読み取りは、抽出の新たな次元を加える。
請求書処理における主なメリット:
1.時間の節約:数時間かかる作業を数秒に短縮 2.正確性:信頼度スコアリングでエラーを最小限に抑える 3.スケーラビリティ:マルチスレッドで数千の処理が可能 4.統合:検索可能なPDFまたは構造化フォーマットへのエクスポート 5.コスト削減:運用コストの削減
このライブラリは導入の柔軟性が高く、オンプレミス、クラウド、ハイブリッドなど、既存のシステムへの統合が可能です。 IronOCRはDocker 、 Azure 、 AWSをサポートしているため、お客様のニーズに合わせて拡張可能です。
IronOCRのライセンスオプション(専用サポートや定期的なアップデートなど)を利用することで、本番環境は大きなメリットを得られます。 図書館のトラブルシューティングガイドと技術サポートにより、スムーズな導入が保証されます。
IronOCRに関する詳しい情報は、ホームページをご覧ください。 請求書OCRに関するその他のチュートリアルについては、こちらの詳細な請求書OCRガイドをご覧ください。 請求書のフィールドにコンピュータビジョンを使用する方法については、こちらのコンピュータビジョンチュートリアルをご覧ください。
よくある質問
OCRを使用してインボイスデータ処理をどのように自動化できますか?
IronOCRを使用して機械学習アルゴリズムを活用することで、インボイスデータ処理を自動化できます。IronOCRは、デジタルおよびスキャンされたインボイスからベンダー情報、インボイス番号、価格などの詳細を抽出し、手動入力のエラーを減らし、効率を向上させます。
インボイスOCR APIのセットアップにはどのような手順が含まれていますか?
IronOCRを使用してインボイスOCR APIをセットアップするには、まずVisual StudioのNuGetパッケージマネージャーを介してライブラリをダウンロードしてインストールします。次に、新しいC#プロジェクトを作成し、IronOCRを統合し、テキスト抽出のために画像ファイルを読み込み、読み取るためのメソッドを使用します。
IronOCRはインボイス番号などの特定のデータを抽出できますか?
はい、IronOCRはインボイス番号のような特定のデータを抽出できます。通常の表現を使用して抽出されたテキストのパターンと一致させることで、インボイスから特定の情報を引き出せます。
インボイス処理に役立つIronOCRのいくつかの機能は何ですか?
IronOCRには、画像の前処理、バーコード認識、ファイル解析などの機能があります。これにより、さまざまな請求書形式からテキストを正確に抽出および処理する能力が向上し、データキャプチャおよびワークフローの効率が改善されます。
画像の前処理はどのようにしてOCRの結果を改善できますか?
IronOCRの画像前処理は、テキスト抽出前に画像の品質を最適化することで、OCRの結果を改善します。これには、コントラスト調整やノイズ削減などの操作が含まれ、インボイスからのデータ抽出の精度を高めることができます。
デジタルおよびスキャンされたインボイスの両方にIronOCRを使用することは可能ですか?
はい、IronOCRはデジタルおよびスキャンされた両方のインボイスを処理できます。先進的な機械学習およびコンピュータビジョン技術を使用して、さまざまな形式および画像品質から正確にテキストを抽出します。
IronOCRは複数のページ形式およびファイルタイプをどのように処理しますか?
IronOCRは、複数のページ形式および一般的な画像およびPDFファイルタイプをサポートしています。複雑なドキュメントから効率的にテキストを抽出できるため、さまざまなインボイス処理アプリケーションにおいて非常に柔軟です。
開発者はIronOCRを使用するためのチュートリアルをどこで見つけることができますか?
開発者はIronOCRのウェブサイトでチュートリアルや追加のリソースを見つけることができます。このサイトは、さまざまな状況でIronOCRを適用するためのハウツーガイドやブログ投稿を含む幅広い学習資料を提供しています。



