收據掃描 API:使用 C# 和 IronOCR 從收據中提取資料
收據掃描API使用OCR技術自動從收據中提取資料,顯著減少手動輸入錯誤並加速處理。 本指南展示如何使用C#中的IronOCR準確提取收據圖像中的供應商名稱、日期、項目、價格及總額,並內建圖片預處理及支持多種格式。
為何選擇IronOCR來進行收據掃描?
IronOCR是一個靈活的OCR程式庫,提供可靠的從掃描文件、圖片和PDF提取文字的功能。 憑藉先進的算法、計算機視覺和機器學習模型,IronOCR即使在複雜的情況下也能確保高準確率。 該程式庫支持多種語言和字體樣式,非常適合全球應用。 通過將IronOCR整合到您的應用程式中,您可以自動化資料輸入和文字分析,提升生產力。
IronOCR如何從收據圖像中提取文字?
IronOCR從文件、照片、截圖和即時攝像頭看到的內容中檢索文字,然後作為JSON響應返回。 使用先進的算法和機器學習,IronOCR分析圖像資料、識別字元,並將其轉換為機器可讀的文字。 該程式庫使用增強了專有改進的Tesseract 5技術,具有卓越的精確度。
為何IronOCR在處理收據上表現優越?
IronOCR擅長處理低品質掃描、多樣的收據格式和不同的方向。 內建的圖像預處理過濾器能在處理前自動改善圖像質量,確保即使是揉皺或褪色的收據也能得到最佳效果。
使用IronOCR需要做哪些準備?
在使用IronOCR之前,請確保這些先決條件已到位:
支持哪些開發環境?
需要哪些程式設計技能?
需要哪些軟體依賴?
- IronOCR安裝:通過NuGet包管理器安裝。 可能需要平台特定的依賴項。
是否需要授權金鑰?
- 授權金鑰(可選):提供免費試用; 生產環境使用需要授權。
如何為收據掃描建立新的Visual Studio專案?
如何在Visual Studio中開始新專案?
打開Visual Studio並進入文件,然後懸停在新建上,點擊專案。
新專案圖像
我應該選擇哪個專案模板?
選擇控制台應用程式,然後點擊下一步。 此模板非常適合在實施到Web應用之前學習IronOCR。
控制台應用
我應該如何命名我的收據掃描器專案?
寫下您的專案名稱和位置,然後點擊下一步。 選擇一個描述性的名稱,如'ReceiptScannerAPI'。
專案配置
我應選擇哪個版本的.NET Framework?
選擇.NET 5.0或更高版本以達到最佳相容性,然後單擊建立。
目標框架
如何在我的專案中安裝IronOCR?
提供兩種簡單的安裝方法:
如何使用NuGet包管理器方法?
前往工具 > NuGet包管理器 > 管理解決方案的NuGet包
NuGet套件管理器
搜索IronOCR並安裝該包。 對於非英文收據,安裝語言特定的包。
IronOCR
如何使用命令行安裝?
-
前往工具 > NuGet包管理器 > 包管理器控制台
-
輸入此命令:
包管理器控制台
如何快速提取IronOCR的收據資料?
使用幾行程式碼提取收據資料:
-
1Install IronOCR with NuGet Package Manager
-
2複製並運行這段程式碼片段。
using IronOcr; using System; var ocr = new IronTesseract(); // Configure for receipt scanning ocr.Configuration.ReadBarCodes = true; ocr.Configuration.WhiteListCharacters = "0123456789.$,ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz% "; using (var input = new OcrInput(@"receipt.jpg")) { // Apply automatic image enhancement input.DeNoise(); input.Deskew(); input.EnhanceResolution(225); // Extract text from receipt var result = ocr.Read(input); // Display extracted text and confidence Console.WriteLine($"Extracted Text:\n{result.Text}"); Console.WriteLine($"\nConfidence: {result.Confidence}%"); }Imports IronOcr Imports System Dim ocr = New IronTesseract() ' Configure for receipt scanning ocr.Configuration.ReadBarCodes = True ocr.Configuration.WhiteListCharacters = "0123456789.$,ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz% " Using input = New OcrInput("receipt.jpg") ' Apply automatic image enhancement input.DeNoise() input.Deskew() input.EnhanceResolution(225) ' Extract text from receipt Dim result = ocr.Read(input) ' Display extracted text and confidence Console.WriteLine($"Extracted Text:{vbCrLf}{result.Text}") Console.WriteLine($"{vbCrLf}Confidence: {result.Confidence}%") End UsingImports IronOcr Imports System Dim ocr = New IronTesseract() ' Configure for receipt scanning ocr.Configuration.ReadBarCodes = True ocr.Configuration.WhiteListCharacters = "0123456789.$,ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz% " Using input = New OcrInput("receipt.jpg") ' Apply automatic image enhancement input.DeNoise() input.Deskew() input.EnhanceResolution(225) ' Extract text from receipt Dim result = ocr.Read(input) ' Display extracted text and confidence Console.WriteLine($"Extracted Text:{vbCrLf}{result.Text}") Console.WriteLine($"{vbCrLf}Confidence: {result.Confidence}%") End Using -
3部署以在您的實時環境中測試
今天就開始在您的專案中使用IronOCR,透過免費試用
如何從收據圖像中提取結構化資料?
IronOCR從各種文件型別中提取劃銷項目、定價、稅金和總額。該程式庫支持PDF、多頁TIFF和不同的圖像格式。
using IronOcr;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
class ReceiptScanner
{
static void Main()
{
var ocr = new IronTesseract();
// Configure OCR for optimal receipt reading
ocr.Configuration.WhiteListCharacters = "0123456789.$,ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz% ";
ocr.Configuration.BlackListCharacters = "~`@#*_}{][|\\";
ocr.Configuration.TesseractVersion = TesseractVersion.Tesseract5;
// Load the image of the receipt
using (var input = new OcrInput(@"r2.png"))
{
// Apply image enhancement filters
input.Deskew(); // Fix image rotation
input.EnhanceResolution(225); // Optimal DPI for receipts
input.DeNoise(); // Remove background noise
input.Sharpen(); // Improve text clarity
// Perform OCR on the input image
var result = ocr.Read(input);
// Regular expression patterns to extract relevant details from the OCR result
var descriptionPattern = @"\w+\s+(.*?)\s+(\d+\.\d+)\s+Units\s+(\d+\.\d+)\s+Tax15%\s+\$(\d+\.\d+)";
var pricePattern = @"\$\d+(\.\d{2})?";
var datePattern = @"\d{1,2}[/-]\d{1,2}[/-]\d{2,4}";
// Variables to store extracted data
var descriptions = new List<string>();
var unitPrices = new List<decimal>();
var taxes = new List<decimal>();
var amounts = new List<decimal>();
var lines = result.Text.Split('\n');
foreach (var line in lines)
{
// Match each line against the description pattern
var descriptionMatch = Regex.Match(line, descriptionPattern);
if (descriptionMatch.Success)
{
descriptions.Add(descriptionMatch.Groups[1].Value.Trim());
unitPrices.Add(decimal.Parse(descriptionMatch.Groups[2].Value));
// Calculate tax and total amount for each item
var tax = unitPrices[unitPrices.Count - 1] * 0.15m;
taxes.Add(tax);
amounts.Add(unitPrices[unitPrices.Count - 1] + tax);
}
// Extract date if found
var dateMatch = Regex.Match(line, datePattern);
if (dateMatch.Success)
{
Console.WriteLine($"Receipt Date: {dateMatch.Value}");
}
}
// Output the extracted data
for (int i = 0; i < descriptions.Count; i++)
{
Console.WriteLine($"Description: {descriptions[i]}");
Console.WriteLine($"Quantity: 1.00 Units");
Console.WriteLine($"Unit Price: ${unitPrices[i]:0.00}");
Console.WriteLine($"Taxes: ${taxes[i]:0.00}");
Console.WriteLine($"Amount: ${amounts[i]:0.00}");
Console.WriteLine("-----------------------");
}
// Calculate and display totals
var subtotal = unitPrices.Sum();
var totalTax = taxes.Sum();
var grandTotal = amounts.Sum();
Console.WriteLine($"\nSubtotal: ${subtotal:0.00}");
Console.WriteLine($"Total Tax: ${totalTax:0.00}");
Console.WriteLine($"Grand Total: ${grandTotal:0.00}");
}
}
}using IronOcr;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
class ReceiptScanner
{
static void Main()
{
var ocr = new IronTesseract();
// Configure OCR for optimal receipt reading
ocr.Configuration.WhiteListCharacters = "0123456789.$,ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz% ";
ocr.Configuration.BlackListCharacters = "~`@#*_}{][|\\";
ocr.Configuration.TesseractVersion = TesseractVersion.Tesseract5;
// Load the image of the receipt
using (var input = new OcrInput(@"r2.png"))
{
// Apply image enhancement filters
input.Deskew(); // Fix image rotation
input.EnhanceResolution(225); // Optimal DPI for receipts
input.DeNoise(); // Remove background noise
input.Sharpen(); // Improve text clarity
// Perform OCR on the input image
var result = ocr.Read(input);
// Regular expression patterns to extract relevant details from the OCR result
var descriptionPattern = @"\w+\s+(.*?)\s+(\d+\.\d+)\s+Units\s+(\d+\.\d+)\s+Tax15%\s+\$(\d+\.\d+)";
var pricePattern = @"\$\d+(\.\d{2})?";
var datePattern = @"\d{1,2}[/-]\d{1,2}[/-]\d{2,4}";
// Variables to store extracted data
var descriptions = new List<string>();
var unitPrices = new List<decimal>();
var taxes = new List<decimal>();
var amounts = new List<decimal>();
var lines = result.Text.Split('\n');
foreach (var line in lines)
{
// Match each line against the description pattern
var descriptionMatch = Regex.Match(line, descriptionPattern);
if (descriptionMatch.Success)
{
descriptions.Add(descriptionMatch.Groups[1].Value.Trim());
unitPrices.Add(decimal.Parse(descriptionMatch.Groups[2].Value));
// Calculate tax and total amount for each item
var tax = unitPrices[unitPrices.Count - 1] * 0.15m;
taxes.Add(tax);
amounts.Add(unitPrices[unitPrices.Count - 1] + tax);
}
// Extract date if found
var dateMatch = Regex.Match(line, datePattern);
if (dateMatch.Success)
{
Console.WriteLine($"Receipt Date: {dateMatch.Value}");
}
}
// Output the extracted data
for (int i = 0; i < descriptions.Count; i++)
{
Console.WriteLine($"Description: {descriptions[i]}");
Console.WriteLine($"Quantity: 1.00 Units");
Console.WriteLine($"Unit Price: ${unitPrices[i]:0.00}");
Console.WriteLine($"Taxes: ${taxes[i]:0.00}");
Console.WriteLine($"Amount: ${amounts[i]:0.00}");
Console.WriteLine("-----------------------");
}
// Calculate and display totals
var subtotal = unitPrices.Sum();
var totalTax = taxes.Sum();
var grandTotal = amounts.Sum();
Console.WriteLine($"\nSubtotal: ${subtotal:0.00}");
Console.WriteLine($"Total Tax: ${totalTax:0.00}");
Console.WriteLine($"Grand Total: ${grandTotal:0.00}");
}
}
}Imports IronOcr
Imports System
Imports System.Collections.Generic
Imports System.Text.RegularExpressions
Class ReceiptScanner
Shared Sub Main()
Dim ocr = New IronTesseract()
' Configure OCR for optimal receipt reading
ocr.Configuration.WhiteListCharacters = "0123456789.$,ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz% "
ocr.Configuration.BlackListCharacters = "~`@#*_}{][|\"
ocr.Configuration.TesseractVersion = TesseractVersion.Tesseract5
' Load the image of the receipt
Using input = New OcrInput("r2.png")
' Apply image enhancement filters
input.Deskew() ' Fix image rotation
input.EnhanceResolution(225) ' Optimal DPI for receipts
input.DeNoise() ' Remove background noise
input.Sharpen() ' Improve text clarity
' Perform OCR on the input image
Dim result = ocr.Read(input)
' Regular expression patterns to extract relevant details from the OCR result
Dim descriptionPattern = "\w+\s+(.*?)\s+(\d+\.\d+)\s+Units\s+(\d+\.\d+)\s+Tax15%\s+\$(\d+\.\d+)"
Dim pricePattern = "\$\d+(\.\d{2})?"
Dim datePattern = "\d{1,2}[/-]\d{1,2}[/-]\d{2,4}"
' Variables to store extracted data
Dim descriptions = New List(Of String)()
Dim unitPrices = New List(Of Decimal)()
Dim taxes = New List(Of Decimal)()
Dim amounts = New List(Of Decimal)()
Dim lines = result.Text.Split(ControlChars.Lf)
For Each line In lines
' Match each line against the description pattern
Dim descriptionMatch = Regex.Match(line, descriptionPattern)
If descriptionMatch.Success Then
descriptions.Add(descriptionMatch.Groups(1).Value.Trim())
unitPrices.Add(Decimal.Parse(descriptionMatch.Groups(2).Value))
' Calculate tax and total amount for each item
Dim tax = unitPrices(unitPrices.Count - 1) * 0.15D
taxes.Add(tax)
amounts.Add(unitPrices(unitPrices.Count - 1) + tax)
End If
' Extract date if found
Dim dateMatch = Regex.Match(line, datePattern)
If dateMatch.Success Then
Console.WriteLine($"Receipt Date: {dateMatch.Value}")
End If
Next
' Output the extracted data
For i As Integer = 0 To descriptions.Count - 1
Console.WriteLine($"Description: {descriptions(i)}")
Console.WriteLine("Quantity: 1.00 Units")
Console.WriteLine($"Unit Price: ${unitPrices(i):0.00}")
Console.WriteLine($"Taxes: ${taxes(i):0.00}")
Console.WriteLine($"Amount: ${amounts(i):0.00}")
Console.WriteLine("-----------------------")
Next
' Calculate and display totals
Dim subtotal = unitPrices.Sum()
Dim totalTax = taxes.Sum()
Dim grandTotal = amounts.Sum()
Console.WriteLine(vbCrLf & $"Subtotal: ${subtotal:0.00}")
Console.WriteLine($"Total Tax: ${totalTax:0.00}")
Console.WriteLine($"Grand Total: ${grandTotal:0.00}")
End Using
End Sub
End ClassImports IronOcr
Imports System
Imports System.Collections.Generic
Imports System.Text.RegularExpressions
Class ReceiptScanner
Shared Sub Main()
Dim ocr = New IronTesseract()
' Configure OCR for optimal receipt reading
ocr.Configuration.WhiteListCharacters = "0123456789.$,ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz% "
ocr.Configuration.BlackListCharacters = "~`@#*_}{][|\"
ocr.Configuration.TesseractVersion = TesseractVersion.Tesseract5
' Load the image of the receipt
Using input = New OcrInput("r2.png")
' Apply image enhancement filters
input.Deskew() ' Fix image rotation
input.EnhanceResolution(225) ' Optimal DPI for receipts
input.DeNoise() ' Remove background noise
input.Sharpen() ' Improve text clarity
' Perform OCR on the input image
Dim result = ocr.Read(input)
' Regular expression patterns to extract relevant details from the OCR result
Dim descriptionPattern = "\w+\s+(.*?)\s+(\d+\.\d+)\s+Units\s+(\d+\.\d+)\s+Tax15%\s+\$(\d+\.\d+)"
Dim pricePattern = "\$\d+(\.\d{2})?"
Dim datePattern = "\d{1,2}[/-]\d{1,2}[/-]\d{2,4}"
' Variables to store extracted data
Dim descriptions = New List(Of String)()
Dim unitPrices = New List(Of Decimal)()
Dim taxes = New List(Of Decimal)()
Dim amounts = New List(Of Decimal)()
Dim lines = result.Text.Split(ControlChars.Lf)
For Each line In lines
' Match each line against the description pattern
Dim descriptionMatch = Regex.Match(line, descriptionPattern)
If descriptionMatch.Success Then
descriptions.Add(descriptionMatch.Groups(1).Value.Trim())
unitPrices.Add(Decimal.Parse(descriptionMatch.Groups(2).Value))
' Calculate tax and total amount for each item
Dim tax = unitPrices(unitPrices.Count - 1) * 0.15D
taxes.Add(tax)
amounts.Add(unitPrices(unitPrices.Count - 1) + tax)
End If
' Extract date if found
Dim dateMatch = Regex.Match(line, datePattern)
If dateMatch.Success Then
Console.WriteLine($"Receipt Date: {dateMatch.Value}")
End If
Next
' Output the extracted data
For i As Integer = 0 To descriptions.Count - 1
Console.WriteLine($"Description: {descriptions(i)}")
Console.WriteLine("Quantity: 1.00 Units")
Console.WriteLine($"Unit Price: ${unitPrices(i):0.00}")
Console.WriteLine($"Taxes: ${taxes(i):0.00}")
Console.WriteLine($"Amount: ${amounts(i):0.00}")
Console.WriteLine("-----------------------")
Next
' Calculate and display totals
Dim subtotal = unitPrices.Sum()
Dim totalTax = taxes.Sum()
Dim grandTotal = amounts.Sum()
Console.WriteLine(vbCrLf & $"Subtotal: ${subtotal:0.00}")
Console.WriteLine($"Total Tax: ${totalTax:0.00}")
Console.WriteLine($"Grand Total: ${grandTotal:0.00}")
End Using
End Sub
End Class有哪些技術可提高收據掃描的準確率?
提高收據掃描準確率的關鍵技術:
輸出
如何提取完整的收據內容?
提取保持格式化的完整收據內容:
using IronOcr;
using System;
using System.Linq;
class WholeReceiptExtractor
{
static void Main()
{
var ocr = new IronTesseract();
// Configure for receipt scanning
ocr.Configuration.ReadBarCodes = true; // Enable barcode detection
ocr.Configuration.TesseractVersion = TesseractVersion.Tesseract5; // Use latest engine
ocr.Configuration.EngineMode = TesseractEngineMode.TesseractAndLstm; // Best accuracy
using (var input = new OcrInput(@"r3.png"))
{
// Apply automatic image correction
input.WithTitle("Receipt Scan");
// Use computer vision to find text regions
var textRegions = input.FindTextRegions();
Console.WriteLine($"Found {textRegions.Count()} text regions");
// Apply optimal filters for receipt processing
input.ApplyOcrInputFilters();
// Perform OCR on the entire receipt
var result = ocr.Read(input);
// Display extracted text
Console.WriteLine("=== EXTRACTED RECEIPT TEXT ===");
Console.WriteLine(result.Text);
// Get detailed results
Console.WriteLine($"\n=== OCR STATISTICS ===");
Console.WriteLine($"OCR Confidence: {result.Confidence:F2}%");
Console.WriteLine($"Pages Processed: {result.Pages.Length}");
Console.WriteLine($"Paragraphs Found: {result.Paragraphs.Length}");
Console.WriteLine($"Lines Detected: {result.Lines.Length}");
Console.WriteLine($"Words Recognized: {result.Words.Length}");
// Extract any barcodes found
if (result.Barcodes.Any())
{
Console.WriteLine("\n=== BARCODES DETECTED ===");
foreach(var barcode in result.Barcodes)
{
Console.WriteLine($"Type: {barcode.Type}");
Console.WriteLine($"Value: {barcode.Value}");
Console.WriteLine($"Location: X={barcode.X}, Y={barcode.Y}");
}
}
// Save as searchable PDF
result.SaveAsSearchablePdf("receipt_searchable.pdf");
Console.WriteLine("\nSearchable PDF saved as: receipt_searchable.pdf");
// Export as hOCR for preservation
result.SaveAsHocrFile("receipt_hocr.html");
Console.WriteLine("hOCR file saved as: receipt_hocr.html");
}
}
}using IronOcr;
using System;
using System.Linq;
class WholeReceiptExtractor
{
static void Main()
{
var ocr = new IronTesseract();
// Configure for receipt scanning
ocr.Configuration.ReadBarCodes = true; // Enable barcode detection
ocr.Configuration.TesseractVersion = TesseractVersion.Tesseract5; // Use latest engine
ocr.Configuration.EngineMode = TesseractEngineMode.TesseractAndLstm; // Best accuracy
using (var input = new OcrInput(@"r3.png"))
{
// Apply automatic image correction
input.WithTitle("Receipt Scan");
// Use computer vision to find text regions
var textRegions = input.FindTextRegions();
Console.WriteLine($"Found {textRegions.Count()} text regions");
// Apply optimal filters for receipt processing
input.ApplyOcrInputFilters();
// Perform OCR on the entire receipt
var result = ocr.Read(input);
// Display extracted text
Console.WriteLine("=== EXTRACTED RECEIPT TEXT ===");
Console.WriteLine(result.Text);
// Get detailed results
Console.WriteLine($"\n=== OCR STATISTICS ===");
Console.WriteLine($"OCR Confidence: {result.Confidence:F2}%");
Console.WriteLine($"Pages Processed: {result.Pages.Length}");
Console.WriteLine($"Paragraphs Found: {result.Paragraphs.Length}");
Console.WriteLine($"Lines Detected: {result.Lines.Length}");
Console.WriteLine($"Words Recognized: {result.Words.Length}");
// Extract any barcodes found
if (result.Barcodes.Any())
{
Console.WriteLine("\n=== BARCODES DETECTED ===");
foreach(var barcode in result.Barcodes)
{
Console.WriteLine($"Type: {barcode.Type}");
Console.WriteLine($"Value: {barcode.Value}");
Console.WriteLine($"Location: X={barcode.X}, Y={barcode.Y}");
}
}
// Save as searchable PDF
result.SaveAsSearchablePdf("receipt_searchable.pdf");
Console.WriteLine("\nSearchable PDF saved as: receipt_searchable.pdf");
// Export as hOCR for preservation
result.SaveAsHocrFile("receipt_hocr.html");
Console.WriteLine("hOCR file saved as: receipt_hocr.html");
}
}
}Imports IronOcr
Imports System
Imports System.Linq
Class WholeReceiptExtractor
Shared Sub Main()
Dim ocr = New IronTesseract()
' Configure for receipt scanning
ocr.Configuration.ReadBarCodes = True ' Enable barcode detection
ocr.Configuration.TesseractVersion = TesseractVersion.Tesseract5 ' Use latest engine
ocr.Configuration.EngineMode = TesseractEngineMode.TesseractAndLstm ' Best accuracy
Using input = New OcrInput("r3.png")
' Apply automatic image correction
input.WithTitle("Receipt Scan")
' Use computer vision to find text regions
Dim textRegions = input.FindTextRegions()
Console.WriteLine($"Found {textRegions.Count()} text regions")
' Apply optimal filters for receipt processing
input.ApplyOcrInputFilters()
' Perform OCR on the entire receipt
Dim result = ocr.Read(input)
' Display extracted text
Console.WriteLine("=== EXTRACTED RECEIPT TEXT ===")
Console.WriteLine(result.Text)
' Get detailed results
Console.WriteLine(vbCrLf & "=== OCR STATISTICS ===")
Console.WriteLine($"OCR Confidence: {result.Confidence:F2}%")
Console.WriteLine($"Pages Processed: {result.Pages.Length}")
Console.WriteLine($"Paragraphs Found: {result.Paragraphs.Length}")
Console.WriteLine($"Lines Detected: {result.Lines.Length}")
Console.WriteLine($"Words Recognized: {result.Words.Length}")
' Extract any barcodes found
If result.Barcodes.Any() Then
Console.WriteLine(vbCrLf & "=== BARCODES DETECTED ===")
For Each barcode In result.Barcodes
Console.WriteLine($"Type: {barcode.Type}")
Console.WriteLine($"Value: {barcode.Value}")
Console.WriteLine($"Location: X={barcode.X}, Y={barcode.Y}")
Next
End If
' Save as searchable PDF
result.SaveAsSearchablePdf("receipt_searchable.pdf")
Console.WriteLine(vbCrLf & "Searchable PDF saved as: receipt_searchable.pdf")
' Export as hOCR for preservation
result.SaveAsHocrFile("receipt_hocr.html")
Console.WriteLine("hOCR file saved as: receipt_hocr.html")
End Using
End Sub
End ClassImports IronOcr
Imports System
Imports System.Linq
Class WholeReceiptExtractor
Shared Sub Main()
Dim ocr = New IronTesseract()
' Configure for receipt scanning
ocr.Configuration.ReadBarCodes = True ' Enable barcode detection
ocr.Configuration.TesseractVersion = TesseractVersion.Tesseract5 ' Use latest engine
ocr.Configuration.EngineMode = TesseractEngineMode.TesseractAndLstm ' Best accuracy
Using input = New OcrInput("r3.png")
' Apply automatic image correction
input.WithTitle("Receipt Scan")
' Use computer vision to find text regions
Dim textRegions = input.FindTextRegions()
Console.WriteLine($"Found {textRegions.Count()} text regions")
' Apply optimal filters for receipt processing
input.ApplyOcrInputFilters()
' Perform OCR on the entire receipt
Dim result = ocr.Read(input)
' Display extracted text
Console.WriteLine("=== EXTRACTED RECEIPT TEXT ===")
Console.WriteLine(result.Text)
' Get detailed results
Console.WriteLine(vbCrLf & "=== OCR STATISTICS ===")
Console.WriteLine($"OCR Confidence: {result.Confidence:F2}%")
Console.WriteLine($"Pages Processed: {result.Pages.Length}")
Console.WriteLine($"Paragraphs Found: {result.Paragraphs.Length}")
Console.WriteLine($"Lines Detected: {result.Lines.Length}")
Console.WriteLine($"Words Recognized: {result.Words.Length}")
' Extract any barcodes found
If result.Barcodes.Any() Then
Console.WriteLine(vbCrLf & "=== BARCODES DETECTED ===")
For Each barcode In result.Barcodes
Console.WriteLine($"Type: {barcode.Type}")
Console.WriteLine($"Value: {barcode.Value}")
Console.WriteLine($"Location: X={barcode.X}, Y={barcode.Y}")
Next
End If
' Save as searchable PDF
result.SaveAsSearchablePdf("receipt_searchable.pdf")
Console.WriteLine(vbCrLf & "Searchable PDF saved as: receipt_searchable.pdf")
' Export as hOCR for preservation
result.SaveAsHocrFile("receipt_hocr.html")
Console.WriteLine("hOCR file saved as: receipt_hocr.html")
End Using
End Sub
End Class
掃描收據API輸出
有哪些先進的功能可以提升收據掃描?
IronOCR提供了一些顯著提高收據掃描準確率的先進功能:
IronOCR支持哪些語言?
- 多語言支持:處理125+種語言的收據或在一個文件中使用多種語言。
IronOCR能讀取收據上的條碼嗎?
- 條碼讀取:自動檢測並讀取條碼和QR碼。
計算機視覺如何幫助收據處理?
- 計算機視覺:使用先進文字檢測在OCR之前定位文字區域。
我可以為獨特的收據格式訓練自定義模型嗎?
- 自定義訓練:訓練自定義字體以獲取專業化的收據格式。
如何提高批量處理的性能?
// Example: Async receipt processing for high-volume scenarios
using IronOcr;
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.IO;
class BulkReceiptProcessor
{
static async Task Main()
{
var ocr = new IronTesseract();
// Configure for optimal performance
ocr.Configuration.TesseractVersion = TesseractVersion.Tesseract5;
ocr.Configuration.UseMultiThreading = true;
ocr.Configuration.ProcessorCount = Environment.ProcessorCount;
// Process multiple receipts asynchronously
var receiptFiles = Directory.GetFiles(@"C:\Receipts\", "*.jpg");
var tasks = new List<Task<OcrResult>>();
foreach (var file in receiptFiles)
{
tasks.Add(ProcessReceiptAsync(ocr, file));
}
// Wait for all receipts to be processed
var results = await Task.WhenAll(tasks);
// Aggregate results
decimal totalAmount = 0;
foreach (var result in results)
{
// Extract total from each receipt
var match = System.Text.RegularExpressions.Regex.Match(
result.Text, @"Total:?\s*\$?(\d+\.\d{2})");
if (match.Success && decimal.TryParse(match.Groups[1].Value, out var amount))
{
totalAmount += amount;
}
}
Console.WriteLine($"Processed {results.Length} receipts");
Console.WriteLine($"Combined total: ${totalAmount:F2}");
}
static async Task<OcrResult> ProcessReceiptAsync(IronTesseract ocr, string filePath)
{
using (var input = new OcrInput(filePath))
{
// Apply preprocessing
input.DeNoise();
input.Deskew();
input.EnhanceResolution(200);
// Process asynchronously
return await ocr.ReadAsync(input);
}
}
}// Example: Async receipt processing for high-volume scenarios
using IronOcr;
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.IO;
class BulkReceiptProcessor
{
static async Task Main()
{
var ocr = new IronTesseract();
// Configure for optimal performance
ocr.Configuration.TesseractVersion = TesseractVersion.Tesseract5;
ocr.Configuration.UseMultiThreading = true;
ocr.Configuration.ProcessorCount = Environment.ProcessorCount;
// Process multiple receipts asynchronously
var receiptFiles = Directory.GetFiles(@"C:\Receipts\", "*.jpg");
var tasks = new List<Task<OcrResult>>();
foreach (var file in receiptFiles)
{
tasks.Add(ProcessReceiptAsync(ocr, file));
}
// Wait for all receipts to be processed
var results = await Task.WhenAll(tasks);
// Aggregate results
decimal totalAmount = 0;
foreach (var result in results)
{
// Extract total from each receipt
var match = System.Text.RegularExpressions.Regex.Match(
result.Text, @"Total:?\s*\$?(\d+\.\d{2})");
if (match.Success && decimal.TryParse(match.Groups[1].Value, out var amount))
{
totalAmount += amount;
}
}
Console.WriteLine($"Processed {results.Length} receipts");
Console.WriteLine($"Combined total: ${totalAmount:F2}");
}
static async Task<OcrResult> ProcessReceiptAsync(IronTesseract ocr, string filePath)
{
using (var input = new OcrInput(filePath))
{
// Apply preprocessing
input.DeNoise();
input.Deskew();
input.EnhanceResolution(200);
// Process asynchronously
return await ocr.ReadAsync(input);
}
}
}' Example: Async receipt processing for high-volume scenarios
Imports IronOcr
Imports System
Imports System.Threading.Tasks
Imports System.Collections.Generic
Imports System.IO
Class BulkReceiptProcessor
Shared Async Function Main() As Task
Dim ocr = New IronTesseract()
' Configure for optimal performance
ocr.Configuration.TesseractVersion = TesseractVersion.Tesseract5
ocr.Configuration.UseMultiThreading = True
ocr.Configuration.ProcessorCount = Environment.ProcessorCount
' Process multiple receipts asynchronously
Dim receiptFiles = Directory.GetFiles("C:\Receipts\", "*.jpg")
Dim tasks = New List(Of Task(Of OcrResult))()
For Each file In receiptFiles
tasks.Add(ProcessReceiptAsync(ocr, file))
Next
' Wait for all receipts to be processed
Dim results = Await Task.WhenAll(tasks)
' Aggregate results
Dim totalAmount As Decimal = 0
For Each result In results
' Extract total from each receipt
Dim match = System.Text.RegularExpressions.Regex.Match(result.Text, "Total:?\s*\$?(\d+\.\d{2})")
If match.Success AndAlso Decimal.TryParse(match.Groups(1).Value, amount) Then
totalAmount += amount
End If
Next
Console.WriteLine($"Processed {results.Length} receipts")
Console.WriteLine($"Combined total: ${totalAmount:F2}")
End Function
Shared Async Function ProcessReceiptAsync(ocr As IronTesseract, filePath As String) As Task(Of OcrResult)
Using input = New OcrInput(filePath)
' Apply preprocessing
input.DeNoise()
input.Deskew()
input.EnhanceResolution(200)
' Process asynchronously
Return Await ocr.ReadAsync(input)
End Using
End Function
End Class' Example: Async receipt processing for high-volume scenarios
Imports IronOcr
Imports System
Imports System.Threading.Tasks
Imports System.Collections.Generic
Imports System.IO
Class BulkReceiptProcessor
Shared Async Function Main() As Task
Dim ocr = New IronTesseract()
' Configure for optimal performance
ocr.Configuration.TesseractVersion = TesseractVersion.Tesseract5
ocr.Configuration.UseMultiThreading = True
ocr.Configuration.ProcessorCount = Environment.ProcessorCount
' Process multiple receipts asynchronously
Dim receiptFiles = Directory.GetFiles("C:\Receipts\", "*.jpg")
Dim tasks = New List(Of Task(Of OcrResult))()
For Each file In receiptFiles
tasks.Add(ProcessReceiptAsync(ocr, file))
Next
' Wait for all receipts to be processed
Dim results = Await Task.WhenAll(tasks)
' Aggregate results
Dim totalAmount As Decimal = 0
For Each result In results
' Extract total from each receipt
Dim match = System.Text.RegularExpressions.Regex.Match(result.Text, "Total:?\s*\$?(\d+\.\d{2})")
If match.Success AndAlso Decimal.TryParse(match.Groups(1).Value, amount) Then
totalAmount += amount
End If
Next
Console.WriteLine($"Processed {results.Length} receipts")
Console.WriteLine($"Combined total: ${totalAmount:F2}")
End Function
Shared Async Function ProcessReceiptAsync(ocr As IronTesseract, filePath As String) As Task(Of OcrResult)
Using input = New OcrInput(filePath)
' Apply preprocessing
input.DeNoise()
input.Deskew()
input.EnhanceResolution(200)
' Process asynchronously
Return Await ocr.ReadAsync(input)
End Using
End Function
End Class如何應對常見的收據掃描挑戰?
收據掃描帶來了IronOCR可以幫助解決的獨特挑戰:
我該如何應對質量差的收據圖像?
- 質量差的圖像:使用篩選嚮導自動找到最佳的預處理設置。
怎麼處理傾斜或旋轉的收據?
- 傾斜或旋轉的收據:自動頁面旋轉檢測確保正確的方向。
如何處理褪色或低對比度的收據?
IronOCR能處理揉皺或損壞的收據嗎?
- 揉皺或損壞的收據:先進預處理從複雜的圖像中恢復文字。
如何管理不同的收據格式和佈局?
收據格式在零售商之間差異很大。 IronOCR提供了靈活的方法:
using IronOcr;
using System;
using System.Collections.Generic;
using System.Linq;
class ReceiptLayoutHandler
{
static void Main()
{
var ocr = new IronTesseract();
// Configure for different receipt layouts
ocr.Configuration.PageSegmentationMode = TesseractPageSegmentationMode.AutoOsd;
ocr.Configuration.EngineMode = TesseractEngineMode.TesseractAndLstm;
using (var input = new OcrInput(@"complex_receipt.jpg"))
{
// Apply region-specific processing
var cropRegion = new CropRectangle(x: 0, y: 100, width: 400, height: 800);
input.AddImage(@"complex_receipt.jpg", cropRegion);
// Process with confidence tracking
var result = ocr.Read(input);
// Parse using confidence scores
var highConfidenceLines = result.Lines
.Where(line => line.Confidence > 85)
.Select(line => line.Text)
.ToList();
// Extract data with fallback strategies
var total = ExtractTotal(highConfidenceLines)
?? ExtractTotalAlternative(result.Text);
Console.WriteLine($"Receipt Total: {total}");
}
}
static decimal? ExtractTotal(List<string> lines)
{
// Primary extraction method
foreach (var line in lines)
{
if (line.Contains("TOTAL") &&
System.Text.RegularExpressions.Regex.IsMatch(line, @"\d+\.\d{2}"))
{
var match = System.Text.RegularExpressions.Regex.Match(line, @"(\d+\.\d{2})");
if (decimal.TryParse(match.Value, out var total))
return total;
}
}
return null;
}
static decimal? ExtractTotalAlternative(string fullText)
{
// Fallback extraction method
var pattern = @"(?:Total|TOTAL|Grand Total|Amount Due).*?(\d+\.\d{2})";
var match = System.Text.RegularExpressions.Regex.Match(fullText, pattern);
if (match.Success && decimal.TryParse(match.Groups[1].Value, out var total))
return total;
return null;
}
}using IronOcr;
using System;
using System.Collections.Generic;
using System.Linq;
class ReceiptLayoutHandler
{
static void Main()
{
var ocr = new IronTesseract();
// Configure for different receipt layouts
ocr.Configuration.PageSegmentationMode = TesseractPageSegmentationMode.AutoOsd;
ocr.Configuration.EngineMode = TesseractEngineMode.TesseractAndLstm;
using (var input = new OcrInput(@"complex_receipt.jpg"))
{
// Apply region-specific processing
var cropRegion = new CropRectangle(x: 0, y: 100, width: 400, height: 800);
input.AddImage(@"complex_receipt.jpg", cropRegion);
// Process with confidence tracking
var result = ocr.Read(input);
// Parse using confidence scores
var highConfidenceLines = result.Lines
.Where(line => line.Confidence > 85)
.Select(line => line.Text)
.ToList();
// Extract data with fallback strategies
var total = ExtractTotal(highConfidenceLines)
?? ExtractTotalAlternative(result.Text);
Console.WriteLine($"Receipt Total: {total}");
}
}
static decimal? ExtractTotal(List<string> lines)
{
// Primary extraction method
foreach (var line in lines)
{
if (line.Contains("TOTAL") &&
System.Text.RegularExpressions.Regex.IsMatch(line, @"\d+\.\d{2}"))
{
var match = System.Text.RegularExpressions.Regex.Match(line, @"(\d+\.\d{2})");
if (decimal.TryParse(match.Value, out var total))
return total;
}
}
return null;
}
static decimal? ExtractTotalAlternative(string fullText)
{
// Fallback extraction method
var pattern = @"(?:Total|TOTAL|Grand Total|Amount Due).*?(\d+\.\d{2})";
var match = System.Text.RegularExpressions.Regex.Match(fullText, pattern);
if (match.Success && decimal.TryParse(match.Groups[1].Value, out var total))
return total;
return null;
}
}Imports IronOcr
Imports System
Imports System.Collections.Generic
Imports System.Linq
Class ReceiptLayoutHandler
Shared Sub Main()
Dim ocr = New IronTesseract()
' Configure for different receipt layouts
ocr.Configuration.PageSegmentationMode = TesseractPageSegmentationMode.AutoOsd
ocr.Configuration.EngineMode = TesseractEngineMode.TesseractAndLstm
Using input = New OcrInput("complex_receipt.jpg")
' Apply region-specific processing
Dim cropRegion = New CropRectangle(x:=0, y:=100, width:=400, height:=800)
input.AddImage("complex_receipt.jpg", cropRegion)
' Process with confidence tracking
Dim result = ocr.Read(input)
' Parse using confidence scores
Dim highConfidenceLines = result.Lines _
.Where(Function(line) line.Confidence > 85) _
.Select(Function(line) line.Text) _
.ToList()
' Extract data with fallback strategies
Dim total = ExtractTotal(highConfidenceLines) _
OrElse ExtractTotalAlternative(result.Text)
Console.WriteLine($"Receipt Total: {total}")
End Using
End Sub
Shared Function ExtractTotal(lines As List(Of String)) As Decimal?
' Primary extraction method
For Each line In lines
If line.Contains("TOTAL") AndAlso _
System.Text.RegularExpressions.Regex.IsMatch(line, "\d+\.\d{2}") Then
Dim match = System.Text.RegularExpressions.Regex.Match(line, "(\d+\.\d{2})")
Dim total As Decimal
If Decimal.TryParse(match.Value, total) Then
Return total
End If
End If
Next
Return Nothing
End Function
Shared Function ExtractTotalAlternative(fullText As String) As Decimal?
' Fallback extraction method
Dim pattern = "(?:Total|TOTAL|Grand Total|Amount Due).*?(\d+\.\d{2})"
Dim match = System.Text.RegularExpressions.Regex.Match(fullText, pattern)
Dim total As Decimal
If match.Success AndAlso Decimal.TryParse(match.Groups(1).Value, total) Then
Return total
End If
Return Nothing
End Function
End ClassImports IronOcr
Imports System
Imports System.Collections.Generic
Imports System.Linq
Class ReceiptLayoutHandler
Shared Sub Main()
Dim ocr = New IronTesseract()
' Configure for different receipt layouts
ocr.Configuration.PageSegmentationMode = TesseractPageSegmentationMode.AutoOsd
ocr.Configuration.EngineMode = TesseractEngineMode.TesseractAndLstm
Using input = New OcrInput("complex_receipt.jpg")
' Apply region-specific processing
Dim cropRegion = New CropRectangle(x:=0, y:=100, width:=400, height:=800)
input.AddImage("complex_receipt.jpg", cropRegion)
' Process with confidence tracking
Dim result = ocr.Read(input)
' Parse using confidence scores
Dim highConfidenceLines = result.Lines _
.Where(Function(line) line.Confidence > 85) _
.Select(Function(line) line.Text) _
.ToList()
' Extract data with fallback strategies
Dim total = ExtractTotal(highConfidenceLines) _
OrElse ExtractTotalAlternative(result.Text)
Console.WriteLine($"Receipt Total: {total}")
End Using
End Sub
Shared Function ExtractTotal(lines As List(Of String)) As Decimal?
' Primary extraction method
For Each line In lines
If line.Contains("TOTAL") AndAlso _
System.Text.RegularExpressions.Regex.IsMatch(line, "\d+\.\d{2}") Then
Dim match = System.Text.RegularExpressions.Regex.Match(line, "(\d+\.\d{2})")
Dim total As Decimal
If Decimal.TryParse(match.Value, total) Then
Return total
End If
End If
Next
Return Nothing
End Function
Shared Function ExtractTotalAlternative(fullText As String) As Decimal?
' Fallback extraction method
Dim pattern = "(?:Total|TOTAL|Grand Total|Amount Due).*?(\d+\.\d{2})"
Dim match = System.Text.RegularExpressions.Regex.Match(fullText, pattern)
Dim total As Decimal
If match.Success AndAlso Decimal.TryParse(match.Groups(1).Value, total) Then
Return total
End If
Return Nothing
End Function
End Class關於收據掃描API我應該記住哪些重要要點?
收據掃描API如IronOCR為自動提取收據資料提供可靠的解決方案。使用先進的OCR技術,企業可以自動提取供應商名稱、採購日期、分項列表、價格、稅金和總額。 支持多種語言、貨幣和條碼支持,企業可以簡化收據管理、節省時間並做出資料驅動的決策。
IronOCR提供開發者所需的工具,為準確有效的文字提取,實現任務自動化並提高效率。 該程式庫的完整功能集包括對各種文件型別的支持及98%的記憶體減少等近期改進。
通過滿足先決條件並整合IronOCR,您可以揭示自動收據處理的優勢。 該程式庫的文件、範例和疑難排解指南確保平滑的實施。
欲了解更多資訊,請存取授權頁面或探索C# Tesseract OCR教程。
相關文章
