Lohith Final Report - Lohith N
Lohith Final Report - Lohith N
A PROJECT REPORT
ON
“AUTOMATIC NUMBER PLATE RECOGNITION”
LOHITH N 208MSB7036
CERTIFICATE
1)...........................
2)...........................
ACKNOWLEDGEMENT
I express my sincere thanks to our beloved Principal, Dr. SUDEER PAI K L, for
providing us all the facilities for laboratory and library.
I express my gratitude to our Vice Principal Prof. SHILPA SARNAD, for her
continuous support and assistance during the course of my project.
CHAPTER – 1 INTRODUCTION 1
1.1 Overview
1.2 Scope of the project
1.3 Modules
CHAPTER–5 TESTING 34
CHAPTER–6 SCREENSHOTS 44
7.1 Admin
7.2 Apps
7.3 Pips
7.4 Manage
7.5 ASGI
7.6 Django
7.7 Views
7.8 Forms
7.9 Models
7.10 Test
7.11 DECORATOR
BIBLIOGRAPHY 104
AUTOMATIC NUMBER PLATE RECOGNITION
CHAPTER-1
INTRODUCTION
1
AUTOMATIC NUMBER PLATE RECOGNITION
CHAPTER-1
INTRODUCTION
1.1 Overview
Automatic Number Plate Recognition (ANPR) is a technology that uses optical
character recognition (OCR) and image processing techniques to read and recognize
license plates on vehicles. Extract the characters on the plate, and convert them into
machine-readable text. The extracted characters from the image number plate, and
finally comparing them to database of registered vehicles to identify the vehicles.
Overall, ANPR systems can provide significant benefits for a wide range of
applications, including increased efficiency, improved accuracy, and reduced labor
costs. However, they also raise concerns about privacy and data protection, as they can
be used to track the movements of individuals and vehicles.
Automatic number plate recognition can be used in the many fields like law
Enforcement, parking enforcement, toll collection, border control, fleet management,
Traffic management. Overall, ANPR technology has a broad range of applications
can be used to improve public safety, enforce laws and regulations, and manage
traffic and transportation infrastructure.
License Plate recognition is one of the techniques used for vehicle identification
purposes. The sole intention of this project is to find the most efficient way to recognize
the registration information from the digital image (obtained from the camera). This
process usually comprises of three steps. First step is the license plate localization,
regardless of the license-plate size and orientation. The second step is the segmentation
of the characters and last step is the recognition.
2
AUTOMATIC NUMBER PLATE RECOGNITION
characters from the license plate. Thus, this project uncovers the fundamental idea
of various algorithms required to accomplish character recognition from the license
plate during Template Matching.
This feature of the algorithm mentioned above helped in achieving faster character
recognition of the license plate. This process of character recognition consists of
steps like Image processing, Defragmentation, Resizing and Character localization
that are required to be performed on the image in order for Template Matching to be
done.
1.3. Modules
• User authentication
• Read image
• Add vehicle number table
• Validation of number plate
• Display number plate
• Display allowed number plate
• Login
• Sign in
• Logout
User authentication:
User authentication is the process of verifying the identity of a user or entity attempting
to access a system, network, or application. It is a crucial aspect of security in various
domains, including computer systems, online services, and mobile applications.
3
AUTOMATIC NUMBER PLATE RECOGNITION
Read image:
1. Preprocessing: The input image is preprocessed to enhance the license plate region
and improve the recognition accuracy. This may involve operations such as image
resizing, noise removal, contrast adjustment, and image normalization.
3. Character Segmentation: Once the license plate region is identified, the characters
on the license plate need to be segmented individually. Various segmentation
algorithms can be used to separate each character and create individual character
images.
4. Character Recognition: The segmented character images are then fed into an optical
character recognition (OCR) system to recognize the alphanumeric characters. OCR
algorithms analyze the shape, patterns, and features of each character to identify the
corresponding text. Machine learning techniques, such as neural networks or support
vector machines, are commonly used in ANPR systems for character recognition.
We then add a few vehicle number plates to the table using the add_vehicle_plate()
function and retrieve the owner names for specific number plates using the
get_owner_name() function.
4
AUTOMATIC NUMBER PLATE RECOGNITION
The re.match() function is used to check if the number plate matches the pattern.
If it matches, the number plate is considered valid; otherwise, it is considered
invalid.
You can customize the regular expression pattern according to the specific rules
and format requirements for the number plates in your jurisdiction.
5
AUTOMATIC NUMBER PLATE RECOGNITION
Login:
To implement a basic login functionality, you need to have a user
authentication system in place. Here's a simplified example of how you
can create a login system using Python:
6
AUTOMATIC NUMBER PLATE RECOGNITION
The program prompts the user to enter their username and password using
the input() function. The entered credentials are then validated using the
validate_credentials() function. If the login is successful, a corresponding
message is printed, and you can perform further actions or grant access to
specific resources. If the login fails, an appropriate message is displayed,
and you can handle the unsuccessful login scenario accordingly.
Sign in:
To implement a sign-in functionality, you typically need a user
authentication system in place. Here's an example of how you can create
a sign-in system using Python:
7
AUTOMATIC NUMBER PLATE RECOGNITION
The program prompts the user to enter their username and password
using the input() function. The entered credentials are then validated
using the validate_credentials() function. If the sign-in is
8
AUTOMATIC NUMBER PLATE RECOGNITION
Logout:
To implement a logout functionality, you need to consider the context
in which the logout is being performed. If you're working on a web
application or a session-based system, the logout process typically
involves terminating the user session and clearing any associated
session data. Here's a general example of how you can implement a
logout feature:
# Function to perform logout
def logout():
# Clear the user session data or perform any necessary cleanup
# Redirect the user to the login page or any other appropriate
page
print("Logout successful!")
# Example usage
logout()
In a web application, the logout functionality is often implemented on
the server-side and triggered by a request from the client-side (e.g.,
clicking on a "Logout" button). The server would typically invalidate
the user's session and clear any associated session data.
It's important to note that the implementation details of the logout process
may vary depending on the web framework or technology you are using.
The above example provides a basic framework for implementing a
9
AUTOMATIC NUMBER PLATE RECOGNITION
10
AUTOMATIC NUMBER PLATE RECOGNITION
CHAPTER-2
SYSTEM ANALYSIS
11
AUTOMATIC NUMBER PLATE RECOGNITION
CHAPTER-2
SYSTEM ANALYSIS
The high performance fibre optic sensors are used for detection of moving vehicles.
A typical installation consists of an interface device with transmitter (LED), receiver
(photo detector), and light guide connection cable (feeder) and fibre optic sensor. As
the vehicle passes over the sensors there is a change in the signal levels obtained
from the sensors The output signals from the fibre optic sensors are fed into a signal
processing and data evaluation unit which comprises of the algorithm, which
computes axle count, axle spacing, vehicle lengths and vehicle classes based on time,
distance formula, and amount of micro bending.
12
AUTOMATIC NUMBER PLATE RECOGNITION
• Camera(s) - that take the images of the car (front or rear side)
• Illumination - a controlled light that can bright up the plate, and allow day and
night operation. In most cases the illumination is Infra-Red (IR) which is invisible
to the driver.
• Computer - normally a PC running Windows or Linux. It runs the ANPR
application which controls the system, reads the images, analyzes and identifies
the plate, and interfaces with other applications and systems.
• Software - the application and the recognition package. Usually the recognition
package is supplied as a DLL (Dynamic Link Library).
• Hardware - various input/output boards used to interface the external world
(such as control boards and networking boards)
There are a number of possible difficulties that the software must be able to cope
with. These include:
1. Poor image resolution, usually because the plate is too far away but sometimes
resulting from the use of a low-quality camera.
4. An object obscuring (part of) the plate, quite often a tow bar, or dirt on the plate.
5. A different font, popular for vanity plates (some countries do not allow such
plates, eliminating the problem).
13
AUTOMATIC NUMBER PLATE RECOGNITION
14
AUTOMATIC NUMBER PLATE RECOGNITION
Assumptions:
• Only the most common type of license plates (single line)will be dealt
with.
• The license Plate has a yellow background with text written in Black.
Constraints:
• If the image contains too much spoiled license plate or has designs on it,
the program can fail to localize the license plate.
• If the license plate happens to be much tilted from horizontal, then again
the result of segmentation of the license plate is very poor.
2.3.2: ER Diagram
15
AUTOMATIC NUMBER PLATE RECOGNITION
ER NOTATION
• entities are represented by labeled rectangles. The label is the name of the entity.
Entity names should be singular nouns.
• relationships are represented by a solid line connecting two entities. The name of
the relationship is written above the line. Relationship names should be verbs
• attributes, when included, are listed inside the entity rectangle. Attributes which are
identifiers are underlined. Attribute names should be singular nouns.
• cardinality of many is represented by a line ending in a crow's foot. If the crow's foot
16
AUTOMATIC NUMBER PLATE RECOGNITION
Steps followed:
Number plate recognition basically consists of three concrete steps namely:
Activity diagram
17
AUTOMATIC NUMBER PLATE RECOGNITION
ER Diagram:
18
AUTOMATIC NUMBER PLATE RECOGNITION
CHAPTER-3
System requirement Specification
19
AUTOMATIC NUMBER PLATE RECOGNITION
20
AUTOMATIC NUMBER PLATE RECOGNITION
3. 2 Interface Design
3.2.1 . Front –end Design
• HTML
Hypertext Markup Language (HTML) is the standard markup language for
documents designed to be displayed in a web browser. It can be assisted by
technologies such as Cascading Style Sheets (CSS) and scripting languages such
as JavaScript.
Web browsers receive HTML documents from a web server or from local
storage and render the documents into multimedia web pages. HTML describes the
structure of a web page semantically and originally included cues for the
appearance of the document.
HTML elements are the building blocks of HTML pages. With HTML constructs,
images and other objects such as interactive forms may be embedded into the rendered
page. HTML provides a means to create structured documents by denoting structural
semantics for text such as headings, paragraphs, lists, links, quotes and other items.
HTML elements are delineated by tags, written using angle brackets.
• JAVA SCRIPT
JavaScript often abbreviated as JS, is a programming language that conforms to the
ECMAScript specification. JavaScript is high-level, often just-in-time compiled, and
multi-paradigm. It has curly-bracket syntax, dynamic typing, prototype-based object
orientation, and first-class functions.
Alongside HTML, JavaScript is one of the core technologies of the Web. JavaScript
enables interactive web pages and is an essential part of web applications. The vast
21
AUTOMATIC NUMBER PLATE RECOGNITION
majority of websites use it for client-side page behavior, and all major web browsers have
a dedicated JavaScript engine to execute it.
itself does not include any input/output (I/O), such as networking, storage, or graphics
facilities, as the host environment (usually a web browser) provides those APIs.
JavaScript engines were originally used only in web browsers, but they are now
embedded in some servers, usually via Node.js. They are also embedded in a variety
of applications created with frameworks such as Electron and Cordova.
Although there are similarities between JavaScript and Java, including language
name, syntax, and respective standard libraries, the two languages are distinct and
differ greatly in design.
• CSS
CSS stands for Cascading Style Sheet, it is a style sheet language used
to shape the HTML elements that will be displayed in the browsers as a web-page.
By using CSS, the website which has been created by using HTML will look
attractive. Basically CSS gives the outer cover on any HTML elements. If you
consider HTML as a skeleton of the web-page then the CSS will be the skin of
the skeleton. The Internet media type (MIME type) of CSS is text/CSS.
Extensions of CSS are .CSS, .CSS3. Three types of CSS which are given below:
22
AUTOMATIC NUMBER PLATE RECOGNITION
• Inline CSS
• Internal or Embedded CSS
• External CSS
Inline CSS:
Inline CSS refers to the practice of including CSS code directly within HTML
elements using the style attribute. This allows you to apply specific styles to individual
elements without having to define a separate CSS file.
Embedded CSS, also known as internal CSS, involves placing CSS code within the
<style> element within the <head> section of an HTML document. It allows you to
define styles specific to that HTML document without the need for an external CSS file.
External CSS:
External CSS refers to the practice of storing CSS code in separate files and linking
those files to HTML documents. This approach allows for the separation of style and
content, making it easier to manage and apply consistent styles across multiple web
pages.
23
AUTOMATIC NUMBER PLATE RECOGNITION
Database
A database is similar to a data file in that it is a storage place for data. Like a data file, a
database does not present information directly to a user; the user runs an application that
accesses data from the database and presents it to the user in an understandable format.
A database typically has two components: the files holding the physical database and
the database management system (DBMS) software that applications use to
access data. The DBMS is responsible for enforcing the database structure,
including:
Relational Database
There are different ways to organize data in a database but relational databases are
one of the most effective. Relational database systems are an application of
mathematical set theory to the problem of effectively organizing data. In a relational
database, data is collected into tables (called relations in relational theory).
24
AUTOMATIC NUMBER PLATE RECOGNITION
When organizing data into tables, you can usually find many different
ways to define tables. Relational database theory defines a process, normalization,
which ensures that the set of tables you define will organize your data effectively.
SQL Server includes a set of administrative and development tools that improve your
ability to install, deploy, manage, and use SQL Server across several sites.
Ability to install, deploy, manage, and use SQL Server across several sites.
25
AUTOMATIC NUMBER PLATE RECOGNITION
Scalability
The same database engine can be used across platforms ranging from
laptop computers running Microsoft Windows® 95/98 to large, multiprocessor
servers running Microsoft Windows NT®, Enterprise Edition.
Data warehousing
SQL Server includes tools for extracting and analyzing summary data
for online analytical processing (OLAP). SQL Server also includes tools
for visually designing databases and analyzing data using English-based
questions.
Databases
A database in Microsoft SQL Server consists of a collection of tables that
contain data, and other objects, such as views, indexes, stored procedures, and
triggers, defined to support activities performed with the data. The data stored in a
database is usually related to a particular subject or process, such as inventory
information for a manufacturing warehouse.
SQL Server can support many databases, and each database can store either
interrelated data or data unrelated to that in the other databases. For example, a server
can have one database that stores personnel data and another that stores product-
related data. Alternatively, one database can store current customer order data, and
another; related database can store historical customer orders that are used for yearly
26
AUTOMATIC NUMBER PLATE RECOGNITION
27
AUTOMATIC NUMBER PLATE RECOGNITION
CHAPTER-4
SYSTEM DESIGN
28
AUTOMATIC NUMBER PLATE RECOGNITION
CHAPTER-4
SYSTEM DESIGN
It's important to note that system design can vary depending on the specific
context, such as the type of system being designed (e.g., software system, hardware
system, distributed system) and the domain in which it will be used. The above
steps provide a general framework for system design, but the actual process may
differ based on the project requirements and the methodology followed by the
development team.
29
AUTOMATIC NUMBER PLATE RECOGNITION
The basic architecture of the system is demonstrated in Fig 5.1. The system has
the following set of modules:
30
AUTOMATIC NUMBER PLATE RECOGNITION
• Number Plate Recognition System: The input image is captured by the system
through a camera feed or an image file. The image is pre-processed by converting
the image to a grayscale image and then bilateral filter is applied to smoothen the
image further. The edges in the image are detected using the canny edge detection
algorithm. Once the canny edges are detected. Contours with 4 edges are ranked .
The contour with the highest rank is considered as the number plate region and it
is cropped. Pytesseract is an OCR which performs character recognition on this
region of the image.
• Web Crawler: The web driver opens the website Vahan.nic.in and captures the
captcha. Once the captcha is captured, it is recognized and converted to a string.
The string is then solved as a mathematical equation and then it is sent back to the
captcha input field. The vehicle number plate is also sent the input field of the
registration number.
• Application: The data of the vehicle extracted is converted to JSON format and
stored MySQL database and Firebase database. The data is then read by a Tkinter
application and displayed to the user.
31
AUTOMATIC NUMBER PLATE RECOGNITION
Fig 5.2 shows the use case diagram of the User. The main function of the
User is to upload or capture an image and then view the details and analyse the
vehicle information that is extracted.
32
AUTOMATIC NUMBER PLATE RECOGNITION
33
AUTOMATIC NUMBER PLATE RECOGNITION
CHAPTER-5
TESTING
34
AUTOMATIC NUMBER PLATE RECOGNITION
CHAPTER 5
TESTING
Testing is a process of executing a program with the indent of finding an error. Testing
is a crucial element of software quality assurance and presents ultimate review of
specification, design and coding.
A good test case is one that has a high probability of finding an as undiscovered error. A
successful test is one that uncovers an as undiscovered error.
Testing Objectives:
35
AUTOMATIC NUMBER PLATE RECOGNITION
Testing Principles:
The primary objective for test case design is to derive a set of tests that has the highest
livelihood for uncovering defects in software. To accomplish this objective two
different categories of test case design techniques are used. They are
White-box testing:
White box testing focus on the program control structure. Test cases are derived to
ensure that all statements in the program have been executed at least once during
testing and that all logical conditions have been executed.
Block-box testing:
36
AUTOMATIC NUMBER PLATE RECOGNITION
Testing strategies:
A strategy for software testing must accommodate low-level tests that are necessary
to verify that all small source code segment has been correctly implemented as well
as high-level tests that validate major system functions against customer
requirements.
Testing fundamentals:
Testing is a process of executing program with the intent of finding error. A good
test case is one that has high probability of finding an undiscovered error. If testing
is conducted successfully it uncovers the errors in the software. Testing cannot show
the absence of defects, it can only show that software defects present.
Information flow for testing flows the pattern. Two class of input provided to
test the process. The software configuration includes a software requirements
specification, a design specification and source code.
Test configuration includes test plan and test cases and test tools. Tests are
conducted and all the results are evaluated. That is test results are compared with
expected results. When erroneous data are uncovered, an error is implied and
debugging commences.
37
AUTOMATIC NUMBER PLATE RECOGNITION
Unit testing:
Unit testing is essential for the verification of the code produced during the
coding phase and hence the goal is to test the internal logic of the modules. Using the
detailed design description as a guide, important paths are tested to uncover errors with
in the boundary of the modules. These tests were carried out during the programming
stage itself. All units of Vienna SQL were successfully tested.
Integration testing:
Integration testing focuses on unit tested modules and build the program structure
that is dictated by the design phase.
System testing:
System testing tests the integration of each module in the system. It also tests to find
discrepancies between the system and it’s original objective, current specification and
system documentation. The primary concern is the compatibility of individual modules.
Entire system is working properly or not will be tested here, and specified path ODBC
connection will correct or not, and giving output or not are tested here these verifications
and validations are done by giving input values to the system and by comparing with
expected output. Top-down testing implementing here.
Acceptance Testing:
This testing is done to verify the readiness of the system for the implementation.
Acceptance testing begins when the system is complete. Its purpose is to provide the end
user with the confidence that the system is ready for use. It involves planning and
execution of functional tests, performance tests and stress tests in order to demonstrate
that the implemented system satisfies its requirements.
38
AUTOMATIC NUMBER PLATE RECOGNITION
Test coverage Analyzer – records the control paths followed for each test case.
Timing Analyzer – also called a profiler, reports the time spent in various regions of
the code are areas to concentrate on to improve system performance.
Coding standards – static analyzers and standard checkers are used to inspect code
for deviations from standards and guidelines.
Test Cases:
Test cases are derived to ensure that all statements in the program have been
executed at least once during testing and that all logical conditions have been
executed. Using White-Box testing methods, the software engineer can drive test
cases that
• Guarantee that logical decisions on their true and false sides.
• Exercise all logical decisions on their true and false sides.
• Execute all loops at their boundaries and with in their operational bounds.
• Exercise internal data structure to assure their validity.
The test case specification for system testing has to be submitted for review before
system testing commences.
correctness, validity and also determine any missing operations and to verify
whether the objectives have been met. Errors are noted down and corrected
immediately. Unit testing is the important and major part of the project. So errors
are rectified easily in particular module and program clarity is increased. In this
39
AUTOMATIC NUMBER PLATE RECOGNITION
project entire system is divided into several modules and is developed individually.
So unit testing is conducted to individual modules.
2. The second step includes Integration testing. It need not be the case, the software whose
modules when run individually and showing perfect results, will also show perfect
results when run as a whole. The individual modules are clipped under this major
module and tested again and verified the results. This is due to poor interfacing, which
may results in data being lost across an interface. A module can have inadvertent,
adverse effect on any other or on the global data structures, causing serious problems.
3. The final step involves validation and testing which determines which the software
functions as the user expected. Here also some modifications were. In the completion
of the project it is satisfied fully by the end user.
The maintenance phase focuses on change that is associated with error correction,
adaptations required as the software's environment evolves, and changes due to
enhancements brought about by changing customer requirements. Four types of
changes are encountered during the maintenance phase.
40
AUTOMATIC NUMBER PLATE RECOGNITION
• Correction
• Adaptation
• Enhancement
• Prevention
Correction:
Even with the best quality assurance activities is lightly that the customer will
uncover defects in the software. Corrective maintenance changes the software to
correct defects.
We may define maintenance by describing four activities that are undertaken after
a program is released for use:
• Corrective Maintenance
• Adaptive Maintenance
• Perfective Maintenance or Enhancement
• Preventive Maintenance or reengineering
Only about 20 percent of all maintenance work are spent "fixing mistakes". The
remaining 80 percent are spent adapting existing systems to changes in their external
environment, making enhancements requested by users, and reengineering an
application for use.
41
AUTOMATIC NUMBER PLATE RECOGNITION
ADAPTATION:
Over time, the original environment (E>G., CPU, operating system, business
rules, external product characteristics) for which the software was developed is likely to
change.
ENHANCEMENT:
As software is used, the customer/user will recognize additional functions that will
provide benefit. Perceptive maintenance extends the software beyond its original
function requirements.
PREVENTION :
42
AUTOMATIC NUMBER PLATE RECOGNITION
CHAPTER-6
SCREENSHOTS
43
AUTOMATIC NUMBER PLATE RECOGNITION
Chapter 6
Screenshots
1.Home page
44
AUTOMATIC NUMBER PLATE RECOGNITION
2. Login page
45
AUTOMATIC NUMBER PLATE RECOGNITION
4.Upload
5.Index
46
AUTOMATIC NUMBER PLATE RECOGNITION
6.Display
Figure 6.6:Display
47
AUTOMATIC NUMBER PLATE RECOGNITION
CHAPTER-7
SOURCE CODE
48
AUTOMATIC NUMBER PLATE RECOGNITION
CHAPTER 7
SOURCE CODE
Manage:
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE',
'ocrprj.settings')
try:
from django.core.management import
execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable?
Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
49
AUTOMATIC NUMBER PLATE RECOGNITION
if __name__ == '__main__':
main()
7.2 Admin
7.3 Apps
from django.apps import AppConfig
class OcrappConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'ocrapp'
7.4 Forms
from django import forms
from .models import *
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class RegisterForm(forms.ModelForm):
50
AUTOMATIC NUMBER PLATE RECOGNITION
class Meta:
model = Register
fields = "__all__"
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username','email','password1','password2',]
class CheckInForm(forms.ModelForm):
class Meta:
model = CheckIn_model
fields = "__all__"
7.4 Models
from django.db import models
class CheckIn_model(models.Model):
date = models.DateTimeField(auto_now_add=True)
file = models.FileField(upload_to='documents/')
class Register(models.Model):
51
AUTOMATIC NUMBER PLATE RECOGNITION
7.6 Tests
52
AUTOMATIC NUMBER PLATE RECOGNITION
7.7 Views
from django.shortcuts import render
from django.views.generic import FormView,DetailView
import pytesseract
from PIL import Image
import pandas as pd
from .models import *
from .forms import *
from django.db.models import Q
import cv2
import pytesseract
# # Create your views here.
def CheckIn(request):
form = CheckInForm(request.POST, request.FILES)
if request.method == 'POST':
if form.is_valid():
form.save()
return render(request, 'form.html', context={'form': form})
def conv(request):
img = cv2.imread('/Volumes/Macintosh HD/ocr-
django/venv/ocrprj/ocrapp/images/nubs.jpeg')
gray= cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
53
AUTOMATIC NUMBER PLATE RECOGNITION
thresh =cv2.threshold(gray,0,255,cv2.THRESH_BINARY +
cv2.THRESH_OTSU)[1]
noise= cv2.medianBlur(thresh,5)
text = pytesseract.image_to_string(noise)
text = text.replace("\n", "")
search_post = text
query = seek(search_post)
return
render(request,'index.html',context={'text':text,'query':query})
def seek(search_post):
if search_post:
query =
Register.objects.filter(Q(numplate__icontains=search_post) &
Q(numplate__icontains=search_post))
else:
print("Hello")
return query
# def index(request):
# img1 = CheckIn_model.objects.last()
## Authentication
from django.contrib.auth import authenticate,login,logout
54
AUTOMATIC NUMBER PLATE RECOGNITION
context={'form':form, }
return render(request,'register.html',context)
# @unauthenticated_user
# @allowed_users(allowed_roles=['admin'])
# @admin_only
def loginPage(request):
if request.method =='POST':
username = request.POST.get('username')
55
AUTOMATIC NUMBER PLATE RECOGNITION
password = request.POST.get('password')
user = authenticate(request,username = username,password =
password)
if user is not None:
login(request,user)
return redirect('home')
else:
messages.info(request,'User or Password is incorrect')
return render(request,'login.html',context={})
def signout(request):
logout(request)
return redirect('')
def registerUser(request):
form = RegisterForm(request.POST or None)
if request.method=="POST":
if form.is_valid():
form.save()
return render(request, 'form.html', {'form':form})
def home(request):
return render(request,'home.html',context={})
def allUser(request):
56
AUTOMATIC NUMBER PLATE RECOGNITION
query = Register.objects.all()
return render(request,'all.html',context = {
'query':query,
})
7.8 URL
"""ocrprj URL Configuration
57
AUTOMATIC NUMBER PLATE RECOGNITION
urlpatterns = [
path('admin/', admin.site.urls),
path('reg', views.registerUser, name='reg'),
path('register',views.registerPage,name ='register'),
path('',views.loginPage,name =''),
path('signout',views.signout,name ='signout'),
# path('index',views.index,name ='index'),
path('conv',views.conv,name ='conv'),
path('seek',views.seek,name ='seek'),
path('checkin',views.CheckIn,name ='checkin'),
path('home',views.home,name ='home'),
path('all',views.allUser,name ='all'),
58
AUTOMATIC NUMBER PLATE RECOGNITION
7.9 Settings
"""
Django settings for ocrprj project.
59
AUTOMATIC NUMBER PLATE RECOGNITION
SECRET_KEY = 'django-insecure-
h%2@6)jta(k=8_42yfxtmo8z(7&ohdm8!gsx_q0&^1ihi5bts+'
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'ocrapp',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
60
AUTOMATIC NUMBER PLATE RECOGNITION
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'ocrprj.urls'
TEMPLATES = [
{
'BACKEND':
'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
61
AUTOMATIC NUMBER PLATE RECOGNITION
WSGI_APPLICATION = 'ocrprj.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-
validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME':
'django.contrib.auth.password_validation.UserAttributeSimilarityVali
dator',
},
{
62
AUTOMATIC NUMBER PLATE RECOGNITION
'NAME':
'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME':
'django.contrib.auth.password_validation.CommonPasswordValidator
',
},
{
'NAME':
'django.contrib.auth.password_validation.NumericPasswordValidator'
,
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
63
AUTOMATIC NUMBER PLATE RECOGNITION
STATIC_URL = 'static/'
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
WSGI
"""
WSGI config for ocrprj project.
import os
64
AUTOMATIC NUMBER PLATE RECOGNITION
os.environ.setdefault('DJANGO_SETTINGS_MODULE',
'ocrprj.settings')
application = get_wsgi_application()
ASGI
"""
ASGI config for ocrprj project.
import os
65
AUTOMATIC NUMBER PLATE RECOGNITION
os.environ.setdefault('DJANGO_SETTINGS_MODULE',
'ocrprj.settings')
application = get_asgi_application()
DECORATOR
from django.http import HttpResponse
from django.shortcuts import redirect
def unauthenticated_user(view_func):
def wrapper_func(request,*args,**kwargs):
if request.user.is_authenticated:
return redirect('upload')
else:
return view_func(request,*args,**kwargs)
return wrapper_func
def allowed_users(allowed_roles=[]):
def decorator(view_func):
def wrapper_func(request,*args,**kwargs):
group = None
if request.user.groups.exists():
group = request.user.groups.all()[0].name
if group in allowed_roles:
return view_func(request,*args,**kwargs)
66
AUTOMATIC NUMBER PLATE RECOGNITION
else:
return HttpResponse("your not authorised to views this
page")
return wrapper_func
return decorator
def admin_only(view_func):
def wrapper_func(request,*args,**kwargs):
group = None
if request.user.groups.exists():
group = request.user.groups.all()[0].name
if group == 'customer':
return redirect('')
if group =='admin':
return view_func(request,*args,**kwargs)
return wrapper_func
67
AUTOMATIC NUMBER PLATE RECOGNITION
CODES:
import cv2
import imutils
import pytesseract
image = cv2.imread('IMAGE.jpg')
image = imutils.resize(image , width = 500)
cv2.imshow("original Image",image)
cv2.waitkey(0)
68
AUTOMATIC NUMBER PLATE RECOGNITION
Source bin:
# This file must be used with "source bin/activate" *from bash*
# you cannot run it directly
deactivate () {
unset -f pydoc >/dev/null 2>&1 || true
69
AUTOMATIC NUMBER PLATE RECOGNITION
if ! [ -z "${_OLD_VIRTUAL_PS1+_}" ] ; then
PS1="$_OLD_VIRTUAL_PS1"
export PS1
unset _OLD_VIRTUAL_PS1
fi
unset VIRTUAL_ENV
if [ ! "${1-}" = "nondestructive" ] ; then
# Self destruct!
unset -f deactivate
fi
}
VIRTUAL_ENV='/Volumes/Macintosh HD/ocr-django/venv'
if ([ "$OSTYPE" = "cygwin" ] || [ "$OSTYPE" = "msys" ]) && $(command -v
cygpath &> /dev/null) ; then
VIRTUAL_ENV=$(cygpath -u "$VIRTUAL_ENV")
fi
export VIRTUAL_ENV
_OLD_VIRTUAL_PATH="$PATH"
70
AUTOMATIC NUMBER PLATE RECOGNITION
PATH="$VIRTUAL_ENV/bin:$PATH"
export PATH
if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT-}" ] ; then
_OLD_VIRTUAL_PS1="${PS1-}"
if [ "x" != x ] ; then
PS1="() ${PS1-}"
else
PS1="(`basename \"$VIRTUAL_ENV\"`) ${PS1-}"
fi
export PS1
fi
pydoc () {
python -m pydoc "$@"
}
71
AUTOMATIC NUMBER PLATE RECOGNITION
PIP:
#!/bin/sh
'''exec' "/Volumes/Macintosh HD/ocr-django/venv/bin/python" "$0"
"$@"
' '''
# -*- coding: utf-8 -*-
import re
import sys
from pip._internal.cli.main import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(main())
Django:
#!/bin/sh
'''exec' "/Volumes/Macintosh HD/ocr-django/venv/bin/python" "$0" "$@"
' '''
# -*- coding: utf-8 -*-
import re
import sys
from django.core.management import execute_from_command_line
if __name__ == '__main__':
72
AUTOMATIC NUMBER PLATE RECOGNITION
Tesseract:
#!/bin/sh
'''exec' "/Volumes/Macintosh HD/ocr-django/venv/bin/python" "$0" "$@"
' '''
# -*- coding: utf-8 -*-
import re
import sys
from pytesseract.pytesseract import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(main())
#!/bin/sh
'''exec' "/Volumes/Macintosh HD/ocr-django/venv/bin/python" "$0" "$@"
' '''
# -*- coding: utf-8 -*-
import re
import sys
from Cython.Build.Cythonize import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(main())
73
AUTOMATIC NUMBER PLATE RECOGNITION
#!/bin/sh
'''exec' "/Volumes/Macintosh HD/ocr-django/venv/bin/python" "$0" "$@"
' '''
# -*- coding: utf-8 -*-
import re
import sys
from sqlparse.__main__ import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(main())
#!/bin/sh
'''exec' "/Volumes/Macintosh HD/ocr-django/venv/bin/python" "$0" "$@"
' '''
# -*- coding: utf-8 -*-
import re
import sys
from sqlparse.__main__ import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(main())
#!/bin/sh
'''exec' "/Volumes/Macintosh HD/ocr-django/venv/bin/python" "$0" "$@"
' '''
# -*- coding: utf-8 -*-
import re
import sys
74
AUTOMATIC NUMBER PLATE RECOGNITION
Django Admin:
from django.utils.version import get_version
__version__ = get_version(VERSION)
def setup(set_prefix=True):
"""
Configure the settings (this happens as a side effect of accessing the
first setting), configure logging and populate the app registry.
Set the thread-local urlresolvers script prefix if `set_prefix` is True.
"""
from django.apps import apps
from django.conf import settings
from django.urls import set_script_prefix
from django.utils.log import configure_logging
configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
if set_prefix:
set_script_prefix(
"/" if settings.FORCE_SCRIPT_NAME is None else
settings.FORCE_SCRIPT_NAME
75
AUTOMATIC NUMBER PLATE RECOGNITION
)
apps.populate(settings.INSTALLED_APPS)
"""
Invokes django-admin when the django module is run as a script.
if __name__ == "__main__":
management.execute_from_command_line()
def render(
request, template_name, context=None, content_type=None, status=None, using=None
):
"""
76
AUTOMATIC NUMBER PLATE RECOGNITION
77
AUTOMATIC NUMBER PLATE RECOGNITION
def _get_queryset(klass):
"""
Return a QuerySet or a Manager.
Duck typing in action: any class with a `get()` method (for
get_object_or_404) or a `filter()` method (for get_list_or_404) might do
the job.
"""
# If it is a model class or anything else with ._default_manager
if hasattr(klass, "_default_manager"):
return klass._default_manager.all()
return klass
)
raise ValueError(
"First argument to get_object_or_404() must be a Model, Manager, "
"or QuerySet, not '%s'." % klass__name
)
try:
return queryset.get(*args, **kwargs)
except queryset.model.DoesNotExist:
raise Http404(
"No %s matches the given query." % queryset.model._meta.object_name
)
)
obj_list = list(queryset.filter(*args, **kwargs))
if not obj_list:
raise Http404(
"No %s matches the given query." % queryset.model._meta.object_name
)
return obj_list
if isinstance(to, Promise):
# Expand the lazy instance, as it can cause issues when it is passed
# further to some Python functions like urlparse.
80
AUTOMATIC NUMBER PLATE RECOGNITION
to = str(to)
Screen:
try:
from screen.str_util import *
except ImportError:
from screen.old_str_util import *
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
81
AUTOMATIC NUMBER PLATE RECOGNITION
import sys
82
AUTOMATIC NUMBER PLATE RECOGNITION
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Urwid unicode character processing tables
# Copyright (C) 2004-2011 Ian Ward
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
83
AUTOMATIC NUMBER PLATE RECOGNITION
import re
_byte_encoding = None
# GENERATED DATA
# generated from
# http://www.unicode.org/Public/4.0-Update/EastAsianWidth-4.0.0.txt
widths = [
(126, 1),
(159, 0),
(687, 1),
84
AUTOMATIC NUMBER PLATE RECOGNITION
(710, 0),
(711, 1),
(727, 0),
(733, 1),
(879, 0),
(1154, 1),
(1161, 0),
(4347, 1),
(4447, 2),
(7467, 1),
(7521, 0),
(8369, 1),
(8426, 0),
(9000, 1),
(9002, 2),
(11021, 1),
(12350, 2),
(12351, 1),
(12438, 2),
(12442, 0),
(19893, 2),
(19967, 1),
(55203, 2),
(63743, 1),
(64106, 2),
(65039, 1),
(65059, 0),
(65131, 2),
(65279, 1),
85
AUTOMATIC NUMBER PLATE RECOGNITION
(65376, 2),
(65500, 1),
(65510, 2),
(120831, 1),
(262141, 2),
(1114109, 1),
]
# ACCESSOR FUNCTIONS
def get_width(o):
"""Return the screen column width for unicode ordinal o."""
global widths
if o == 0xe or o == 0xf:
return 0
for num, wid in widths:
if o <= num:
return wid
return 1
b2 = ord2(text[pos + 1])
if b2 & 0xc0 != 0x80:
return error
b3 = ord2(text[pos + 2])
if b3 & 0xc0 != 0x80:
return error
b4 = ord2(text[pos + 2])
if b4 & 0xc0 != 0x80:
return error
o = ((b1 & 0x07) << 18) | ((b2 & 0x3f) << 12) | ((b3 & 0x3f) << 6) | (b4 & 0x3f)
if o < 0x10000:
return error
return o, pos + 4
return error
def set_byte_encoding(enc):
assert enc in ('utf8', 'narrow', 'wide')
global _byte_encoding
_byte_encoding = enc
def get_byte_encoding():
return _byte_encoding
89
AUTOMATIC NUMBER PLATE RECOGNITION
90
AUTOMATIC NUMBER PLATE RECOGNITION
Some characters are wide (take two columns) and others affect the
previous character (take zero columns). Use the widths table above
to calculate the screen column width of text[start_offs:end_offs]
"""
lt = len(text)
i=n
sc += w
return sc
# "wide", "narrow" or all printable ASCII, just return the character count
return end_offs - start_offs
return start_offs + 2
return start_offs + 1
Return values:
0 -- not within dbe char, or double_byte_encoding == False
1 -- pos is on the 1st half of a dbe char
2 -- pos is on the 2nd half of a dbe char
"""
assert isinstance(text, bytes)
v = ord2(text[pos])
94
AUTOMATIC NUMBER PLATE RECOGNITION
if v < 0x80:
return 0
i = pos - 1
while i >= line_start:
if ord2(text[i]) < 0x80:
break
i -= 1
if (pos - i) & 1:
return 1
return 2
def process_east_asian_width():
import sys
out = []
last = None
for line in sys.stdin.readlines():
if line[:1] == "#":
continue
line = line.strip()
hex, rest = line.split(";", 1)
wid, rest = rest.split(" # ", 1)
word1 = rest.split(" ", 1)[0]
if "." in hex:
95
AUTOMATIC NUMBER PLATE RECOGNITION
hex = hex.split("..")[1]
num = int(hex, 16)
if last is None:
out.append((0, l))
last = l
if last == l:
out[-1] = (num, l)
else:
out.append((num, l))
last = l
print("widths = [")
for o in out[1:]: # treat control characters same as ascii
print("\t%r," % (o,))
print("]")
if __name__ == "__main__":
process_east_asian_width()
96
AUTOMATIC NUMBER PLATE RECOGNITION
CHAPTER-8
FUTURE ENHANCEMENT
97
AUTOMATIC NUMBER PLATE RECOGNITION
CHAPTER 8
FUTURE ENHANCEMENT
Future Enhancements
• Deep Learning and Artificial Intelligence: ANPR systems can benefit from the
advancements in deep learning and artificial intelligence (AI) techniques. By
training ANPR algorithms with large datasets, using convolutional neural
networks (CNNs) and other AI models, the accuracy and reliability of license
plate recognition can be significantly enhanced.
• Integration with Big Data and Analytics: ANPR systems can be integrated with
big data analytics platforms to provide valuable insights. By analyzing the
collected license plate data, patterns can be identified, and useful information can
be extracted for applications such as traffic flow analysis, crime prevention, and
parking optimization.
98
AUTOMATIC NUMBER PLATE RECOGNITION
99
AUTOMATIC NUMBER PLATE RECOGNITION
CHAPTER-9
CONCLUSION
100
AUTOMATIC NUMBER PLATE RECOGNITION
Chapter-9
CONCLUSION
Conclusion
101
AUTOMATIC NUMBER PLATE RECOGNITION
102
AUTOMATIC NUMBER PLATE RECOGNITION
BIBLIOGRAPHY
103
AUTOMATIC NUMBER PLATE RECOGNITION
BIBLIOGRAPHY
The following books were referred during the analysis and execution phase of project
104
AUTOMATIC NUMBER PLATE RECOGNITION
WEBSITES:
• www.w3schools.com
• www.python.com
• www.geeksforgeeks.org
• www.pythonpoint.com
• www.online-python.com
• www.pythonanywhere.com
105