Saltar al pie de página
USANDO IRONOCR

Recibos de supermercado OCR en C# (Tutorial para desarrolladores)

Receipts and Automation

Receipts are essential in today's fast-paced world. Whether you're buying groceries or dining in a restaurant, a receipt helps track the amount spent and can assist in budgeting. Meanwhile, grocery stores may use receipt scanners to analyze sales data, aiding them in forecasting demand.

However, receipts can be difficult to read, and it can be unclear how totals are calculated. Manual data entry from receipts for budgeting purposes is tedious and error-prone, especially when many items are involved. Losing a receipt can suddenly make it unclear why you exceeded your monthly budget.

To address this problem, budgeting and financial apps have adopted OCR (Optical Character Recognition) technology. By scanning receipts and converting them into digital format, OCR minimizes human error, automates data entry, tracks expenses, and provides insights into purchasing behavior.

OCR technology works by using machine learning algorithms to identify and extract text and numbers from images. However, OCR systems are not perfect, especially when dealing with images affected by noise, such as blurring or smudges, which can lead to incorrect data extraction. Thus, selecting a reliable OCR library that can efficiently process and optimize reading methods is crucial.

Why IronOCR?

IronOCR is a C# library based on a customized version of the Tesseract OCR engine. Here are some of its key features:

  1. Cross-Compatibility: Fully compatible with .NET platforms, including .NET 8, 7, 6, 5, and Framework 4.6.2 onwards. It supports Windows, macOS, Azure, and Linux.
  2. Flexibility and Scalability: Handles various input formats like jpg, png, and gif. It integrates smoothly with native "System.Drawing" objects in C#.
  3. Ease of Use and Support: Well-documented, with a robust API and 24/5 support available.
  4. Multi-Language Capabilities: Supports up to 125 languages, ideal for international documents. It excels at recognizing product names and prices, essential for receipt processing.

Implementing Receipt OCR

License Key

Before using IronOCR, obtain a license key. A free trial is available here.

// Replace the license key variable with the trial key you obtained
IronOcr.License.LicenseKey = "REPLACE-WITH-YOUR-KEY";
// Replace the license key variable with the trial key you obtained
IronOcr.License.LicenseKey = "REPLACE-WITH-YOUR-KEY";
' Replace the license key variable with the trial key you obtained
IronOcr.License.LicenseKey = "REPLACE-WITH-YOUR-KEY"
$vbLabelText   $csharpLabel

Example: Reading a Supermarket Receipt

Let's explore how IronOCR can be used in an app to scan supermarket receipts with a smartphone, extracting data like product names and prices to reward points based on total purchases.

Input Image

Example supermarket receipt

C# Code Implementation

using IronOcr;

class ReceiptScanner
{
    static void Main()
    {
        // Set the license key for IronOCR
        IronOcr.License.LicenseKey = "YOUR-KEY";

        // Instantiate OCR engine
        var ocr = new IronTesseract();

        using var inputPhoto = new OcrInput();
        inputPhoto.LoadImage("supermarketexample.jpg");

        // Perform OCR on the loaded image
        OcrResult result = ocr.Read(inputPhoto);

        // Output the text extracted from the receipt
        string text = result.Text;
        Console.WriteLine(text);
    }
}
using IronOcr;

class ReceiptScanner
{
    static void Main()
    {
        // Set the license key for IronOCR
        IronOcr.License.LicenseKey = "YOUR-KEY";

        // Instantiate OCR engine
        var ocr = new IronTesseract();

        using var inputPhoto = new OcrInput();
        inputPhoto.LoadImage("supermarketexample.jpg");

        // Perform OCR on the loaded image
        OcrResult result = ocr.Read(inputPhoto);

        // Output the text extracted from the receipt
        string text = result.Text;
        Console.WriteLine(text);
    }
}
Imports IronOcr

Friend Class ReceiptScanner
	Shared Sub Main()
		' Set the license key for IronOCR
		IronOcr.License.LicenseKey = "YOUR-KEY"

		' Instantiate OCR engine
		Dim ocr = New IronTesseract()

		Dim inputPhoto = New OcrInput()
		inputPhoto.LoadImage("supermarketexample.jpg")

		' Perform OCR on the loaded image
		Dim result As OcrResult = ocr.Read(inputPhoto)

		' Output the text extracted from the receipt
		Dim text As String = result.Text
		Console.WriteLine(text)
	End Sub
End Class
$vbLabelText   $csharpLabel
  1. Import the IronOcr library.
  2. Instantiate the OCR engine (IronTesseract).
  3. Create a new OcrInput to load the image of the receipt.
  4. Use the Read method from IronTesseract to extract text.
  5. Output the results to the console.

Debugging and Confidence Testing

To ensure consistency, verify the extracted data's confidence level, which determines its accuracy.

OcrResult result = ocr.Read(inputPhoto);
string text = result.Text;
Console.WriteLine(text);
Console.WriteLine($"Confidence: {result.Confidence}");
OcrResult result = ocr.Read(inputPhoto);
string text = result.Text;
Console.WriteLine(text);
Console.WriteLine($"Confidence: {result.Confidence}");
Dim result As OcrResult = ocr.Read(inputPhoto)
Dim text As String = result.Text
Console.WriteLine(text)
Console.WriteLine($"Confidence: {result.Confidence}")
$vbLabelText   $csharpLabel

The Confidence property provides a statistical accuracy measure. It ranges from 0 (low confidence) to 1 (high confidence). Adjust your data handling strategies based on these confidence levels for reliability.

Noise Removal and Filtering

Before processing images, use these methods to clean and prepare images for better OCR results:

inputPhoto.DeNoise();      // Removes noise from the image
inputPhoto.ToGrayScale();  // Converts image to grayscale
inputPhoto.DeNoise();      // Removes noise from the image
inputPhoto.ToGrayScale();  // Converts image to grayscale
inputPhoto.DeNoise() ' Removes noise from the image
inputPhoto.ToGrayScale() ' Converts image to grayscale
$vbLabelText   $csharpLabel

These preprocessing steps help increase the accuracy of data extraction.

Conclusion

IronOCR

Receipt OCR technology is an asset for businesses and individuals, aiding in budgeting, preventing fraud by verifying transaction details, and automating data collection. IronOCR stands out for its accuracy, speed, and ease of integration with existing platforms, making it an excellent choice for developers aiming to implement receipt scanning solutions.

Try IronOCR's trial license to explore its capabilities.

Preguntas Frecuentes

¿Cómo puede usarse la tecnología OCR para automatizar el procesamiento de recibos de supermercado?

La tecnología OCR puede automatizar el procesamiento de recibos de supermercado convirtiendo recibos escaneados en datos digitales. Usando IronOCR, los recibos pueden ser leídos y el texto puede ser extraído automáticamente, reduciendo la necesidad de ingresar datos manualmente y minimizando el error humano.

¿Qué ventajas ofrece IronOCR para el procesamiento de recibos de supermercado?

IronOCR ofrece varias ventajas para procesar recibos de supermercado, incluyendo compatibilidad multiplataforma, soporte para múltiples formatos de imagen, una API robusta para fácil integración, y la capacidad de procesar hasta 125 idiomas, lo que lo hace ideal para recibos internacionales.

¿Cómo integrar IronOCR en una aplicación C# para leer recibos de supermercado?

Para integrar IronOCR en una aplicación C#, necesitas obtener una clave de licencia, importar la biblioteca IronOcr, y usar el motor IronTesseract para leer y extraer texto de imágenes de recibos de supermercado.

¿Qué técnicas de preprocesamiento mejoran la precisión del OCR en el escaneo de recibos?

IronOCR proporciona técnicas de preprocesamiento como DeNoise y ToGrayScale para mejorar la precisión del OCR. Estas técnicas ayudan a eliminar el ruido de la imagen y a convertir imágenes a escala de grises, mejorando la extracción de texto de los recibos.

¿Por qué es importante la prueba de confianza en el OCR y cómo se aplica?

La prueba de confianza en IronOCR es importante porque mide la precisión de los datos extraídos, con valores que van de 0 (bajo) a 1 (alto). Ayuda a los usuarios a evaluar la fiabilidad de los resultados de OCR e informa las decisiones de manejo de datos.

¿Puede IronOCR manejar recibos de supermercado multilingües?

Sí, IronOCR soporta el procesamiento OCR en hasta 125 idiomas, lo que le permite manejar recibos de supermercado multilingües eficientemente.

¿Está disponible una versión de prueba para desarrolladores interesados en IronOCR?

Sí, una prueba gratuita de IronOCR está disponible para desarrolladores, permitiéndoles explorar sus características y capacidades antes de comprometerse a una compra.

¿Qué plataformas son compatibles con IronOCR para el escaneo de recibos?

IronOCR es compatible con plataformas .NET, incluyendo .NET 8, 7, 6, 5, y Framework 4.6.2 en adelante, y soporta operación en entornos Windows, macOS, Azure y Linux.

¿Qué hace que IronOCR sea adecuado para integrar el escaneo de recibos en aplicaciones?

IronOCR es adecuado para integrar el escaneo de recibos en aplicaciones debido a su alta precisión, facilidad de uso, soporte multiplataforma y su capacidad de manejar varios formatos de entrada e idiomas sin problemas.

Kannaopat Udonpant
Ingeniero de Software
Antes de convertirse en Ingeniero de Software, Kannapat completó un doctorado en Recursos Ambientales de la Universidad de Hokkaido en Japón. Mientras perseguía su grado, Kannapat también se convirtió en miembro del Laboratorio de Robótica de Vehículos, que es parte del Departamento de Ingeniería ...
Leer más