Passer au contenu du pied de page
UTILISATION D'IRONOCR
Comment effectuer la reconnaissance optique de caractères sur les plaques d'immatriculation en C#

Comment effectuer la reconnaissance de plaques d'immatriculation en C# (Tutoriel)

License plate recognition has become an essential tool in many industries, from traffic management and parking systems to law enforcement and tolling solutions. By leveraging Optical Character Recognition (OCR) technology, developers can efficiently extract text from images, automating the process of identifying license plates. In this tutorial, we will demonstrate how to use IronOCR, a powerful C# OCR library, to accurately read license plates from images. With its seamless integration with OpenCV source code for computer vision tasks, IronOCR offers a robust solution for recognizing text even from complex or noisy image sources. Whether you're working with a clean license plate image or a full vehicle photo, this guide will walk you through the steps to build a reliable license plate recognition system using modern OCR techniques.

How to Use License Plate Recognition C#

  1. Install the C# Library to use license plate recognition
  2. Import the license plate image to a new OcrImageInput instance.
  3. Apply image filters to improve text extraction in C#.
  4. Improve recognition speed by specifying the license plate region in the photo.
  5. Print the extracted text using an OcrLicensePlateResult instance.

Getting Started with IronOCR

IronOCR is a C# OCR library built on the Tesseract OCR engine, specifically designed to bring high accuracy and efficiency to text recognition projects in .NET applications. Ideal for handling noisy or low-quality images, IronOCR includes powerful image preprocessing capabilities like automatic noise reduction and grayscale conversion, which enhance the clarity of text extraction.

Some of IronOCR’s standout features include:

  • High OCR Accuracy: Optimized for various languages and fonts, IronOCR excels in accuracy even when working with complex or distorted text.
  • Image and PDF Support: It can read text from multiple image formats and PDF files, making it versatile for different document types.
  • Integration with OpenCV: Through OpenCV support, IronOCR can perform computer vision tasks like detecting specific text regions within an image, which is particularly useful for license plate recognition.
  • Advanced Preprocessing: Includes filters for grayscale conversion, rotation, de-skewing, and contrast enhancement to improve recognition quality.
  • Flexible Input Options: Supports multi-page documents and adjustable regions, letting developers focus OCR processing on selected areas for faster and more targeted results.

With these capabilities, IronOCR is a powerful solution for building OCR applications that demand accuracy, flexibility, and ease of integration with other computer vision tools.

Create a Visual Studio Project

Start by opening Visual Studio and selecting "Create a New Project". This will bring you to a page where you can select the type of project you want to build (in our case, we will be making a Console Application). Select the desired application type and click "Next".

Visual Studio Project Type

Now, give your project a name and choose the location it will be saved to.

Project Name and Location

Finally, select your target .NET framework and click the "Create" button. This will create the project, as shown below.

Created Project

The next step is to install the IronOCR library so we can start processing license plates.

Installing IronOCR

To get started with IronOCR in your C# project, you’ll need to install the IronOCR package from NuGet. IronOCR is compatible with .NET Framework and .NET Core, making it easy to integrate into various .NET applications.

Step 1: Open Package Manager Console

In Visual Studio, navigate to Tools > NuGet Package Manager > Package Manager Console.

Step 2: Install the IronOCR Package

Enter the following command in the Package Manager Console:

Install-Package IronOcr

This command installs the IronOCR library, including all dependencies needed to run OCR functions in your project. As our application requires advanced features like license plate detection using computer vision, you can also install the optional IronOcr.ComputerVision.Windows package this way:

Install-Package IronOcr.ComputerVision.Windows

Ensure you have the IronOcr.Extensions.AdvancedScan extension installed so you can utilize its powerful ReadLicensePlate method:

Install-Package IronOcr.Extensions.AdvancedScan

Alternatively, you can install the packages using Tools > NuGet Package Manager > Manage NuGet Packages for Solution and search for the packages you need:

NuGet Package Manager

Setting Up the Code

Finally, we must add the necessary imports and using statements to the top of our code:

using IronOcr;
using IronOcr;
Imports IronOcr
$vbLabelText   $csharpLabel

Reading License Plates with Optical Character Recognition

In this section, we will create a program to read license plates using IronOCR, a Tesseract OCR Engine that excels at extracting text from images. To implement vehicle detection, we may also incorporate additional machine-learning libraries. Notably, IronOCR integrates with OpenCV, a leading open-source computer vision library, allowing us to perform object detection tasks like identifying vehicles and license plates.

Example License Plate Image

We'll be working with the following license plate:

License Plate Example

Example Code to Perform OCR on License Plate

using IronOcr;

var ocr = new IronTesseract();

using (var input = new OcrImageInput("licensePlate.jpeg"))
{
    // Fixes digital noise and makes the image easier to read
    input.DeNoise();
    input.ToGrayScale();

    // Reads the license plate information and stores it for further use
    OcrLicensePlateResult result = ocr.ReadLicensePlate(input);

    // Saves the license plate text to a string variable
    string output = result.Text;

    // Outputs the license plate text to the console
    Console.WriteLine(output);
}
using IronOcr;

var ocr = new IronTesseract();

using (var input = new OcrImageInput("licensePlate.jpeg"))
{
    // Fixes digital noise and makes the image easier to read
    input.DeNoise();
    input.ToGrayScale();

    // Reads the license plate information and stores it for further use
    OcrLicensePlateResult result = ocr.ReadLicensePlate(input);

    // Saves the license plate text to a string variable
    string output = result.Text;

    // Outputs the license plate text to the console
    Console.WriteLine(output);
}
Imports IronOcr

Private ocr = New IronTesseract()

Using input = New OcrImageInput("licensePlate.jpeg")
	' Fixes digital noise and makes the image easier to read
	input.DeNoise()
	input.ToGrayScale()

	' Reads the license plate information and stores it for further use
	Dim result As OcrLicensePlateResult = ocr.ReadLicensePlate(input)

	' Saves the license plate text to a string variable
	Dim output As String = result.Text

	' Outputs the license plate text to the console
	Console.WriteLine(output)
End Using
$vbLabelText   $csharpLabel

OCR Output

Code Breakdown:

  • Initialization: var ocr = new IronTesseract(); creates a new instance of the IronTesseract class, which provides methods for Optical Character Recognition (OCR).

  • Image Input: The using statement creates a new OcrImageInput object with the specified image file "licensePlate.jpeg". This object is designed to hold the image data for OCR processing.

  • Image Preprocessing:

    • input.DeNoise(); applies a digital noise reduction filter to enhance the quality of the image, making it easier for the OCR engine to read the text.
    • input.ToGrayScale(); converts the image to grayscale, which can improve recognition accuracy and processing speed.
  • License Plate Recognition: The line OcrLicensePlateResult result = ocr.ReadLicensePlate(input); uses the ReadLicensePlate method to analyze the processed image and extract any license plate information it detects, storing the results in an OcrLicensePlateResult object.

  • Output Storage: The license plate text is stored in the string variable output by accessing result.Text, which contains the recognized text from the license plate.

  • Console Output: Finally, Console.WriteLine(output); prints the extracted license plate text to the console for verification.

Scanning License Plate Numbers from a Car

If we have an image of an entire car rather than just the license plate, we can specify a rectangular region to focus on the license plate area. We can use System.Drawing.Rectangle to define this area in pixels.

Original Image

We’ll use the following image file for our example:

Car with License Plate

By specifying the area of interest, we improve processing speed and avoid extracting unnecessary text.

Implementation Code

using IronOcr;
using System.Drawing;

var ocr = new IronTesseract();

using (var input = new OcrInput())
{
    var contentArea = new Rectangle(x: 252, y: 282, width: 148, height: 47);
    input.LoadImage("CarPlate.jpeg", contentArea);
    OcrLicensePlateResult result = ocr.ReadLicensePlate(input);
    Console.WriteLine(result.Text);
}
using IronOcr;
using System.Drawing;

var ocr = new IronTesseract();

using (var input = new OcrInput())
{
    var contentArea = new Rectangle(x: 252, y: 282, width: 148, height: 47);
    input.LoadImage("CarPlate.jpeg", contentArea);
    OcrLicensePlateResult result = ocr.ReadLicensePlate(input);
    Console.WriteLine(result.Text);
}
Imports IronOcr
Imports System.Drawing

Private ocr = New IronTesseract()

Using input = New OcrInput()
	Dim contentArea = New Rectangle(x:= 252, y:= 282, width:= 148, height:= 47)
	input.LoadImage("CarPlate.jpeg", contentArea)
	Dim result As OcrLicensePlateResult = ocr.ReadLicensePlate(input)
	Console.WriteLine(result.Text)
End Using
$vbLabelText   $csharpLabel

Focused OCR Output

Code Breakdown:

  • Initialization: var ocr = new IronTesseract(); creates a new instance of the IronTesseract class, which is responsible for executing the OCR operations.
  • OCR Input: The using (var input = new OcrInput()) statement creates a new OcrInput object, which will be used to load and process the image for OCR.
  • Defining the Area of Interest: var contentArea = new Rectangle(x: 252, y: 282, width: 148, height: 47); defines a rectangular area (contentArea) within the image. This rectangle specifies the coordinates and dimensions (width and height) where the license plate is expected to be located.
  • Loading the Image: input.LoadImage("CarPlate.jpeg", contentArea); loads the specified image file ("CarPlate.jpeg") and focuses on the defined rectangle (contentArea) to limit the OCR processing to that specific region.
  • Reading the License Plate: OcrLicensePlateResult result = ocr.ReadLicensePlate(input); invokes the ReadLicensePlate method, which analyzes the input image for license plate characters and returns an OcrLicensePlateResult object containing the extracted text.
  • Output: Console.WriteLine(result.Text); prints the recognized text from the license plate to the console.

Automatic Number Plate Recognition

IronOCR leverages OpenCV to identify text regions within images, employing various image processing techniques. This functionality enables programs to detect license plates by locating text areas in the image and then utilizing Tesseract to read those regions.

Installation

To enable the license plate detection model, install the required package via the Package Manager Console:

Example using automatic region detection for license plates:

var ocr = new IronTesseract();

using (var input = new OcrImageInput("CarPlate.jpeg"))
{
    input.FindTextRegion();
    OcrLicensePlateResult result = ocr.ReadLicensePlate(input);
    Console.WriteLine(result.Text);
}
var ocr = new IronTesseract();

using (var input = new OcrImageInput("CarPlate.jpeg"))
{
    input.FindTextRegion();
    OcrLicensePlateResult result = ocr.ReadLicensePlate(input);
    Console.WriteLine(result.Text);
}
Dim ocr = New IronTesseract()

Using input = New OcrImageInput("CarPlate.jpeg")
	input.FindTextRegion()
	Dim result As OcrLicensePlateResult = ocr.ReadLicensePlate(input)
	Console.WriteLine(result.Text)
End Using
$vbLabelText   $csharpLabel

Automatic OCR Output

Code Breakdown:

  • Initialization: An instance of the IronTesseract class is created, which will be used for optical character recognition (OCR) with the Tesseract engine.
  • Image Input: A new OcrImageInput object is instantiated with the specified image file ("CarPlate.jpeg"). This object will serve as the input for the OCR process and is enclosed in a using statement to ensure proper resource management.
  • Text Region Detection: The FindTextRegion() method is called on the input object. This method employs computer vision techniques to automatically identify areas within the image that likely contain text, specifically targeting the license plate.
  • License Plate Recognition: The ReadLicensePlate method is invoked to analyze the detected text regions and extract the license plate number. The result is stored in an OcrLicensePlateResult object, which holds the recognized text and any associated metadata.
  • Output: The detected license plate text is printed to the console, allowing the user to see the extracted license plate number.

IronOCR Licensing

IronOCR License

For those wanting to try IronOCR out for themselves, IronOCR offers a free trial which grants you access to the entire range of tools it has to offer, meaning you can try them out in your own projects before buying a license. Once your free trial runs out, IronOCR licensing starts from just $liteLicense for the lite license. It also provides optional add-ons for an additional cost, such as the royalty-free redistribution coverage and uninterrupted support and ongoing product updates.

Beyond this, if you find yourself needing to use more Iron Software products beyond just IronOCR, such as IronPDF for your PDF-related tasks or IronWord for working with Word documents, then Iron Software also offers Iron Suite, which is a great way to have access to the entire range of tools for a great price.

Conclusion

In this guide, we’ve explored how to build a reliable license plate recognition system in C# using IronOCR. With its powerful text extraction capabilities and integration with OpenCV, IronOCR provides an efficient, easy-to-use solution for applications that require accurate text recognition from vehicle images. From preprocessing the image to setting specific detection regions, IronOCR simplifies the OCR process with tools tailored for noisy or complex images, like license plates in traffic and surveillance footage.

Whether you’re developing for traffic monitoring, parking enforcement, or any application requiring automated license plate recognition, IronOCR offers a comprehensive library that integrates seamlessly into .NET environments. By following these steps, you’re equipped to deploy OCR-powered solutions that enhance efficiency and accuracy across various real-world scenarios. With additional features like region selection and noise reduction, IronOCR ensures your license plate recognition tasks are optimized for the best possible results.

Questions Fréquemment Posées

Comment puis-je utiliser l'OCR pour identifier les numéros de plaques d'immatriculation en C# ?

Vous pouvez utiliser IronOCR pour identifier les numéros de plaques d'immatriculation en C# en employant la classe IronTesseract pour créer une instance OCR, charger l'image contenant la plaque d'immatriculation, appliquer des filtres de prétraitement tels que réduction de bruit, et extraire le texte en utilisant la méthode ReadLicensePlate.

Quels sont les avantages de l'utilisation de l'OCR pour la reconnaissance des plaques d'immatriculation ?

L'utilisation de l'OCR pour la reconnaissance des plaques d'immatriculation automatise le processus d'extraction de texte, offrant une haute précision et efficacité. IronOCR améliore cela en offrant la prise en charge de plusieurs formats d'image et une intégration avec la vision par ordinateur, ce qui le rend idéal pour des applications telles que la gestion du trafic et l'application de la loi.

Comment puis-je gérer des images bruyantes ou de faible qualité dans le traitement OCR ?

IronOCR fournit des capacités puissantes de prétraitement d'image, telles que la réduction automatique de bruit et la conversion en niveaux de gris, qui améliorent la précision de l'extraction de texte même en traitant avec des images bruyantes ou de faible qualité.

Est-il possible de focaliser le traitement OCR sur des régions spécifiques d'une image ?

Oui, IronOCR permet de spécifier des régions d'intérêt rectangulaires dans une image pour concentrer le traitement OCR, améliorant à la fois la vitesse et la précision de l'extraction de texte à partir de zones telles que les plaques d'immatriculation.

Comment commencer avec l'OCR dans un projet Visual Studio ?

Pour commencer à utiliser l'OCR dans un projet Visual Studio, créez une nouvelle Application Console, installez le package IronOCR via NuGet et implémentez la logique OCR en utilisant les classes et méthodes IronOCR. Cette configuration vous permet de réaliser facilement des tâches OCR au sein de votre application.

Quelles fonctionnalités IronOCR offre-t-il pour la reconnaissance des plaques d'immatriculation ?

IronOCR offre une haute précision OCR, une intégration avec OpenCV pour des tâches de vision par ordinateur améliorées, des filtres de prétraitement avancés et la prise en charge de plusieurs formats d'image et de PDF, ce qui en fait un outil polyvalent pour la reconnaissance des plaques d'immatriculation.

Comment IronOCR s'intègre-t-il avec les tâches de vision par ordinateur ?

IronOCR s'intègre avec OpenCV pour réaliser diverses tâches de vision par ordinateur, telles que la détection automatique des régions de texte, améliorant le processus OCR pour des applications comme la reconnaissance des plaques d'immatriculation.

Quelles options de licences sont disponibles pour IronOCR ?

IronOCR propose un essai gratuit ainsi que diverses options de licence, à partir d'une licence légère. Des add-ons supplémentaires et l'Iron Suite sont disponibles pour les utilisateurs recherchant des fonctionnalités étendues à travers différentes applications.

La technologie OCR peut-elle être appliquée aux images complètes de véhicules ?

Oui, IronOCR peut être utilisé avec des images de véhicules entiers. En spécifiant la région de la plaque d'immatriculation, vous pouvez focaliser le traitement OCR sur la zone souhaitée, évitant une extraction de texte inutile et améliorant l'efficacité du traitement.

Kannaopat Udonpant
Ingénieur logiciel
Avant de devenir ingénieur logiciel, Kannapat a obtenu un doctorat en ressources environnementales à l'université d'Hokkaido au Japon. Pendant qu'il poursuivait son diplôme, Kannapat est également devenu membre du laboratoire de robotique de véhicules, qui fait partie du département de bioproduction. En 2022, il a utilisé ses compé...
Lire la suite