0% found this document useful (0 votes)
65 views

Driver Drowsiness Detection System

The document describes a driver drowsiness detection system that uses a camera placed in front of the driver to monitor their eyes and detect if they are closed, which could indicate drowsiness. It analyzes the video stream from the camera to detect drowsiness and alerts the driver with a beep sound if their eyes are closed for too long. The system provides drowsiness detection and accident prevention in a low-cost way using the camera from a normal smartphone. It aims to reduce the number of accidents caused by drowsy driving.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
65 views

Driver Drowsiness Detection System

The document describes a driver drowsiness detection system that uses a camera placed in front of the driver to monitor their eyes and detect if they are closed, which could indicate drowsiness. It analyzes the video stream from the camera to detect drowsiness and alerts the driver with a beep sound if their eyes are closed for too long. The system provides drowsiness detection and accident prevention in a low-cost way using the camera from a normal smartphone. It aims to reduce the number of accidents caused by drowsy driving.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 44

DRIVER DROWSINESS DETECTION SYSTEM

ABSTRACT

In today’s busy and hectic world, people are unable to get full rest and complete bedtime sleep.
Due to this when they drive after a sleepless night, they end up dozing off while driving which
can be very fatal. A lot of accidents are caused due to drowsy driving every year and it often
goes undetected thereby leading to huge loss of lives and resources. We are presenting a system
that detects drowsiness while driving and alerts the driver for the same. Such systems are
available in high end cars only. Our system uses the front camera of the driver’s mobile phone
placed in front of the driver. The detection of eyes closed is efficient and works under different
situations, it uses camera of any normal android phone. Hence we provide users with a cheap
technology.

Existing System:

It is very dangerous to drive while being tired or after not sleeping for long hours. It is estimated
that drowsy driving caused approximately 70,000 crashes, 50,000 injuries, and around 1000
deaths.Today a large number of these accidents caused are not recognized because the driver do
not inform that had fallen asleep as it would make them responsible for the accident and in worst
cases it may also lead to loss of life. Hence it is important to track drowsiness detection and alert
the driver at the same time to prevent such fatal accidents and loss oflife.

In the present working system, it detects the drowsiness and alert the driver with a beep sound.
But if he not alert by this sound this may cause loss of life.

Disadvantages:

In This system, when drowsiness detects the buzzer will sound. But sometimes it's not prevent
the accident occurrence.
Proposed System:

Almost everyone has experienced this drowsiness problem while driving. The people worst
affected by drowsy driving are teenagers, professional truck drivers who have to drive on long
routes for a long period of time without breaks, cab drivers who also drive for a long period,
sometimes to complete their targets to get bonus profit and shift workers who work at night or
for late hours also get affected due to tiredness. Drowsy driving can be due to driving on
highways for long time without any breaks particularly at night.

To overcome the above problem, the drowsiness detection and prevention system is
implemented. This paper describes the solution to this drowsiness problem.

Our system uses the camera to monitors the driver .It is placedin front to the driverto analyze the
behavior of the driver i.e. whether the driver’s eyes are closed or not.The front camera constantly
captures the image of the driver and with the help of this checks whether the eyes of the driver
are closed or not.

Advantages:

 This system provides Drowsiness detection and accident prevention.


 It detects the Driver Continuously.

LITERATURE REVIEW

Title:

Intelligent driver drowsiness detection through fusion of yawning and eye closure
Author:

M. Omidyeganeh; A. Javadtalab; S. Shirmohammadi

Content:

Driver drowsiness is a major factor in most driving accidents. In this paper we present a robust
and intelligent scheme for driver drowsiness detection employing the fusion of eye closure and
yawning detection methods. In this approach, the driver's facial appearance is captured via a
camera installed in the car. In the first step, the face region is detected and tracked in the
captured video sequence utilizing computer vision techniques. Next, the eye and mouth areas are
extracted from the face; and they are studied to find signs of driver fatigue. Finally, in a fusion
phase the driver state is determined and a warning message is sent to the driver if the drowsiness
is detected. Our experiments prove the high efficiency of the proposed idea.

Title:

Portable Prevention and Monitoring of Driver’s Drowsiness Focuses to Eyelid Movement Using
Internet of Things
Author:

Menchie Miranda;Alonica Villanueva;Mark Jomar Buo

Content:

This paper includes a drowsiness prevention device since recently vehicular count of accidents
increases yearly in the Philippines. Current safety measures are followed to increase the driver's
awareness which includes the use of standard rumble strips on roads reference, installation of
GPS, speed limiters, sensors and other studies uses signal processing embedded of an expensive
vehicle. The technology uses internet of things so that the vehicle owner can monitor the driver's
drowsiness everywhere during work hours. The study focuses at the eyelid movement that is not
yet mentioned to the previous study. This proposed system continuously scans the eyelid
movements of the driver and once drowsiness is detected the device automatically alerts him
using a random-typed alarm. It automatically forwards the report to the vehicle owner from the
web application through internet access. The project received consistent results through
evaluation and testing as it is 95% successfully detects and alerts a drowsy driver.

REQUIREMENT SPECIFICATION

Functional Requirements

 Graphical User interface with the User.

Software Requirements
For developing the application the following are the Software Requirements:

1. Python

Operating Systems supported

1. Windows 7

2. Windows XP

3. Windows 8

Technologies and Languages used to Develop

1. Python

Debugger and Emulator


 Any Browser (Particularly Chrome)
Hardware Requirements

For developing the application the following are the Hardware Requirements:

 Processor: Pentium IV or higher


 RAM: 2 GB
 Space on Hard Disk: minimum 512MB
System Design:
MODULES
Detection Stage:

This is the initialization stage of the system. Every time the system is started it needs to be set
up and optimized for current user and conditions. The key step in this stage is successful head
detection (Figure 2). If the driver’s head is correctly located we can proceed to extract the
features necessary for setting up the system. Setup steps include: (i) extracting driver’s skin color
and using that information to create custom skin color model and (ii) collecting a set of
open/closed eyes samples, along with driver’s normal head position. To help achieve these goals,
user interaction might be required. The driver might be asked to sit comfortably in its normal
driving position so that system can determine upper and lower thresholds needed for detecting
potential nodding. The driver might also be asked to hold their eyes closed and then open for a
matter of few seconds each time. This is enough to get the system started. Over time, the system
will expand the dataset of obtained images and will become more error resistant and overall
more robust.

Tracking Stage :

Once the driver’s head and eyes are properly located and all the necessary features are extracted,
the system enters the regular tracking (monitoring) stage. A key step in this stage is the
continuous monitoring of the driver’s eyes within a dynamically allocated tracking area. More
specifically, in order to save some processing time, the system will determine the size of the
tracking area based on the previous history of eye movements. For example, if the eyes were
moving horizontally to the left for a number of frames it is to be expected that that trend with
continue in the following frame also. So it is logical to expand the tracking area towards the
expected direction of the eyes and shrink the area in other three directions. During this stage, the
system must also determine the state of the eyes. All these tasks must be carried out in realtime;
depending on the processor’s abilities and current load, it might be necessary to occasionally
skip a few frames, without sacrificing algorithmic accuracy.

Warning Stage:

If the driver keeps his eyes closed for prolonged period of time or starts to nod, alertness has to
be raised. The key step within this stage is close monitoring of drivers eyes. The system must
determine whether the eyes are still closed, and what is the eyes’ position relative to previously
established thresholds. We cannot afford to skip frames in this stage. In practice, tracking of eyes
is performed much in the same way as in the tracking stage with the addition of the following
processes: calculation of velocity and trajectory of the eyes and threshold monitoring. These
additional computations are required to improve the system’s ability to determine whether the
driver is drowsy or not.

Alert Stage :

Once it has been determined that the driver appears to be in an abnormal driving state, the system
has to be proactive and alert the driver of potential dangers that can arise. Combination of
audio/visual alerts are used to attract the driver’s attention and raise their alertness level. Alerting
has to be implemented in such a way as not to cause the opposite effect of intended and startle
the driver into causing an accident.

PYTHON INTRODUCTION:

Python is a general purpose, dynamic, high level, and interpreted programming language. It
supports Object Oriented programming approach to develop applications. It is simple and easy to
learn and provides lots of high-level data structures.

Python is easy to learn yet powerful and versatile scripting language, which makes it attractive
for Application Development.

Python's syntax and dynamic typing with its interpreted nature make it an ideal language for
scripting and rapid application development.

Python supports multiple programming pattern, including object-oriented, imperative, and


functional or procedural programming styles.

Python is not intended to work in a particular area, such as web programming. That is why it is
known as multipurpose programming language because it can be used with web, enterprise, 3D
CAD, etc.

We don't need to use data types to declare variable because it is dynamically typed so we can
write a=10 to assign an integer value in an integer variable.

Python makes the development and debugging fast because there is no compilation step included
in Python development, and edit-test-debug cycle is very fast.

Python 2 vs. Python 3

In most of the programming languages, whenever a new version releases, it supports the features
and syntax of the existing version of the language, therefore, it is easier for the projects to switch
in the newer version. However, in the case of Python, the two versions Python 2 and Python 3
are very much different from each other.

A list of differences between Python 2 and Python 3 are given below:

1. Python 2 uses print as a statement and used as print "something" to print some string on
the console. On the other hand, Python 3 uses print as a function and used as
print("something") to print something on the console.
2. Python 2 uses the function raw_input() to accept the user's input. It returns the string
representing the value, which is typed by the user. To convert it into the integer, we need
to use the int() function in Python. On the other hand, Python 3 uses input() function
which automatically interpreted the type of input entered by the user. However, we can
cast this value to any type by using primitive functions (int(), str(), etc.).
3. In Python 2, the implicit string type is ASCII, whereas, in Python 3, the implicit string
type is Unicode.
4. Python 3 doesn't contain the xrange() function of Python 2. The xrange() is the variant of
range() function which returns a xrange object that works similar to Java iterator. The
range() returns a list for example the function range(0,3) contains 0, 1, 2.
5. There is also a small change made in Exception handling in Python 3. It defines a
keyword as which is necessary to be used. We will discuss it in Exception handling
section of Python programming tutorial.

Python Features

Python provides lots of features that are listed below.

1) Easy to Learn and Use


Python is easy to learn and use. It is developer-friendly and high level programming
language.

2) Expressive Language
Python language is more expressive means that it is more understandable and readable.

3) Interpreted Language
Python is an interpreted language i.e. interpreter executes the code line by line at a time. This
makes debugging easy and thus suitable for beginners.
4) Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, Unix and Macintosh
etc. So, we can say that Python is a portable language.

5) Free and Open Source


Python language is freely available at offical web address.The source-code is also available.
Therefore it is open source.

6) Object-Oriented Language
Python supports object oriented language and concepts of classes and objects come into
existence.

7) Extensible
It implies that other languages such as C/C++ can be used to compile the code and thus it can
be used further in our python code.

8) Large Standard Library


Python has a large and broad library and prvides rich set of module and functions for rapid
application development.

9) GUI Programming Support


Graphical user interfaces can be developed using Python.

10) Integrated
It can be easily integrated with languages like C, C++, JAVA etc.

Python History and Versions

o Python laid its foundation in the late 1980s.


o The implementation of Python was started in the December 1989 by Guido Van
Rossum at CWI in Netherland.
o In February 1991, van Rossum published the code (labeled version 0.9.0) to
alt.sources.
o In 1994, Python 1.0 was released with new features like: lambda, map, filter, and
reduce.
o Python 2.0 added new features like: list comprehensions, garbage collection system.
o On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed
to rectify fundamental flaw of the language.
o ABC programming language is said to be the predecessor of Python language which
was capable of Exception Handling and interfacing with Amoeba Operating System.
o Python is influenced by following programming languages:
o ABC language.
o Modula.

Python programming language is being updated regularly with new features and supports. There
are lots of updations in python versions, started from 1994 to current release.

Python Applications

Python is known for its general purpose nature that makes it applicable in almost each domain
of software development. Python as a whole can be used in any sphere of development.

Here, we are specifing applications areas where python can be applied.

1) Web Applications
We can use Python to develop web applications. It provides libraries to handle internet
protocols such as HTML and XML, JSON, Email processing, request, beautifulSoup,
Feedparser etc. It also provides Frameworks such as Django, Pyramid, Flask etc to design and
delelop web based applications. Some important developments are: PythonWikiEngines,
Pocoo, PythonBlogSoftware etc.

2) Desktop GUI Applications


Python provides Tk GUI library to develop user interface in python based application. Some
other useful toolkits wxWidgets, Kivy, pyqt that are useable on several platforms. The Kivy is
popular for writing multitouch applications.

3) Software Development
Python is helpful for software development process. It works as a support language and can
be used for build control and management, testing etc.
4) Scientific and Numeric
Python is popular and widely used in scientific and numeric computing. Some useful library
and package are SciPy, Pandas, IPython etc. SciPy is group of packages of engineering,
science and mathematics.

5) Business Applications
Python is used to build Bussiness applications like ERP and e-commerce systems. Tryton is a
high level application platform.

6) Console Based Application


We can use Python to develop console based applications. For example: IPython.

7) Audio or Video based Applications


Python is awesome to perform multiple tasks and can be used to develop multimedia
applications. Some of real applications are: TimPlayer, cplay etc.

8) 3D CAD Applications
To create CAD application Fandango is a real application which provides full features of
CAD.

9) Enterprise Applications
Python can be used to create applications which can be used within an Enterprise or an
Organization. Some real time applications are: OpenErp, Tryton, Picalo etc.

10) Applications for Images


Using Python several application can be developed for image. Applications developed are:
VPython, Gogh, imgSeek etc.
There are several such applications which can be developed using Python

How to Install Python (Environment Set-up)

In this section of the tutorial, we will discuss the installation of python on various operating
systems.

Installation on Windows
Visit the link https://www.python.org/downloads/ to download the latest release of Python. In
this process, we will install Python 3.6.7 on our Windows operating system.
Double-click the executable file which is downloaded; the following window will open.
Select Customize installation and proceed.

The following window shows all the optional features. All the features need to be installed
and are checked by default; we need to click next to continue.
The following window shows a list of advanced options. Check all the options which you
want to install and click next. Here, we must notice that the first check-box (install for all
users) must be checked.

Now, we are ready to install python-3.6.7. Let's install it.


Now, try to run python on the command prompt. Type the command python in case of
python2 or python3 in case of python3. It will show an error as given in the below image. It
is because we haven't set the path.

To set the path of python, we need to the right click on "my computer" and go to Properties
→ Advanced → Environment Variables.
Add the new path variable in the user variable section.
Type PATH as the variable name and set the path to the installation directory of the python
shown in the below image.
Now, the path is set, we are ready to run python on our local system. Restart CMD, and
type python again. It will open the python interpreter shell where we can execute the python
statements.

First Python Program

In this Section, we will discuss the basic syntax of python by using which, we will run a
simple program to print hello world on the console.

Python provides us the two ways to run a program:

o Using Interactive interpreter prompt


o Using a script file
Let's discuss each one of them in detail.

Interactive interpreter prompt


Python provides us the feature to execute the python statement one by one at the interactive
prompt. It is preferable in the case where we are concerned about the output of each line of
our python program.

To open the interactive mode, open the terminal (or command prompt) and type python
(python3 in case if you have python2 and python3 both installed on your system).

It will open the following prompt where we can execute the python statement and check their
impact on the console.

Let's run a python statement to print the traditional hello world on the console. Python3
provides print() function to print some message on the console. We can pass the message as a
string into this function. Consider the following image.

Here, we get the message "Hello World !" printed on the console.
Using a script file
Interpreter prompt is good to run the individual statements of the code. However, we can not
write the code every-time on the terminal.

We need to write our code into a file which can be executed later. For this purpose, open an
editor like notepad, create a file named first.py (python used .py extension) and write the
following code in it.

1. Print ("hello world"); #here, we have used print() function to print the message on the console
.
To run this file named as first.py, we need to run the following command on the terminal.

$ python3 first.py

Hence, we get our output as the message Hello World ! is printed on the console.

Get Started with PyCharm


In our first program, we have used gedit on our CentOS as an editor. On Windows, we have
an alternative like notepad or notepad++ to edit the code. However, these editors are not used
as IDE for python since they are unable to show the syntax related suggestions.

JetBrains provides the most popular and a widely used cross-platform IDE PyCharm to run
the python programs.

PyCharm installation
As we have already stated, PyCharm is a cross-platform IDE, and hence it can be installed on
a variety of the operating systems. In this section of the tutorial, we will cover the installation
process of PyCharm on Windows, MacOS, CentOS, and Ubuntu.
Windows
Installing PyCharm on Windows is very simple. To install PyCharm on Windows operating
system, visit the link https://www.jetbrains.com/pycharm/download/download-thanks.html?
platform=windows to download the executable installer. Double click the installer (.exe) file and
install PyCharm by clicking next at each step.

next →← prev

Python Variables

Variable is a name which is used to refer memory location. Variable also known as identifier
and used to hold value.

In Python, we don't need to specify the type of variable because Python is a type infer
language and smart enough to get variable type.

Variable names can be a group of both letters and digits, but they have to begin with a letter
or an underscore.

It is recomended to use lowercase letters for variable name. Rahul and rahul both are two
different variables.

Identifier Naming
Variables are the example of identifiers. An Identifier is used to identify the literals used in
the program. The rules to name an identifier are given below.

o The first character of the variable must be an alphabet or underscore ( _ ).


o All the characters except the first character may be an alphabet of lower-case(a-z),
upper-case (A-Z), underscore or digit (0-9).
o Identifier name must not contain any white-space, or special character (!, @, #, %, ^,
&, *).
o Identifier name must not be similar to any keyword defined in the language.
o Identifier names are case sensitive for example my name, and MyName is not the
same.
o Examples of valid identifiers : a123, _n, n_9, etc.
o Examples of invalid identifiers: 1a, n%4, n 9, etc.
Declaring Variable and Assigning Values
Python does not bound us to declare variable before using in the application. It allows us to
create variable at required time.

We don't need to declare explicitly variable in Python. When we assign any value to the
variable that variable is declared automatically.

The equal (=) operator is used to assign value to a variable.

Eg:

Output:

1. >>>
2. 10
3. ravi
4. 20000.67
5. >>>

Multiple Assignment
Python allows us to assign a value to multiple variables in a single statement which is also
known as multiple assignment.

We can apply multiple assignments in two ways either by assigning a single value to multiple
variables or assigning multiple values to multiple variables. Lets see given examples.

1. Assigning single value to multiple variables


Eg:

1. x=y=z=50
2. print iple
3. print y
4. print z
Output:

1. >>>
2. 50
3. 50
4. 50
5. >>>
2.Assigning multiple values to multiple variables:

Eg:

1. a,b,c=5,10,15
2. print a
3. print b
4. print c
Output:

1. >>>
2. 5
3. 10
4. 15
5. >>>
The values will be assigned in the order in which variables appears.

Basic Fundamentals:

This section contains the basic fundamentals of Python like :

i)Tokens and their types.

ii) Comments

a)Tokens:

o Tokens can be defined as a punctuator mark, reserved words and each individual word
in a statement.
o Token is the smallest unit inside the given program.
There are following tokens in Python:

o Keywords.
o Identifiers.
o Literals.
o Operators.

Tuples:
o Tuple is another form of collection where different type of data can be stored.
o It is similar to list where data is separated by commas. Only the difference is that list
uses square bracket and tuple uses parenthesis.
o Tuples are enclosed in parenthesis and cannot be changed.

Eg:

1. >>> tuple=('rahul',100,60.4,'deepak')
2. >>> tuple1=('sanjay',10)
3. >>> tuple
4. ('rahul', 100, 60.4, 'deepak')
5. >>> tuple[2:]
6. (60.4, 'deepak')
7. >>> tuple1[0]
8. 'sanjay'
9. >>> tuple+tuple1
10. ('rahul', 100, 60.4, 'deepak', 'sanjay', 10)
11. >>>

Dictionary:
o Dictionary is a collection which works on a key-value pair.
o It works like an associated array where no two keys can be same.
o Dictionaries are enclosed by curly braces ({}) and values can be retrieved by square
bracket([]).

Eg:

1. >>> dictionary={'name':'charlie','id':100,'dept':'it'}
2. >>> dictionary
3. {'dept': 'it', 'name': 'charlie', 'id': 100}
4. >>> dictionary.keys()
5. ['dept', 'name', 'id']
6. >>> dictionary.values()
7. ['it', 'charlie', 100]
8. >>>

Python Data Types

Variables can hold values of different data types. Python is a dynamically typed language
hence we need not define the type of the variable while declaring it. The interpreter implicitly
binds the value with its type.

Python enables us to check the type of the variable used in the program. Python provides us
the type() function which returns the type of the variable passed.

Consider the following example to define the values of different data types and checking its
type.

1. A=10
2. b="Hi Python"
3. c = 10.5
4. print(type(a));
5. print(type(b));
6. print(type(c));
Output:

<type 'int'>
<type 'str'>
<type 'float'>

Standard data types


A variable can hold different types of values. For example, a person's name must be stored as
a string whereas its id must be stored as an integer.

Python provides various standard data types that define the storage method on each of them.
The data types defined in Python are given below.

1. Numbers
2. String
3. List
4. Tuple
5. Dictionary
In this section of the tutorial, we will give a brief introduction of the above data types. We
will discuss each one of them in detail later in this tutorial.

Numbers
Number stores numeric values. Python creates Number objects when a number is assigned to
a variable. For example;

1. a = 3 , b = 5 #a and b are number objects


Python supports 4 types of numeric data.

1. int (signed integers like 10, 2, 29, etc.)


2. long (long integers used for a higher range of values like 908090800L, -0x1929292L,
etc.)
3. float (float is used to store floating point numbers like 1.9, 9.902, 15.2, etc.)
4. complex (complex numbers like 2.14j, 2.0 + 2.3j, etc.)

Python allows us to use a lower-case L to be used with long integers. However, we must
always use an upper-case L to avoid confusion.

A complex number contains an ordered pair, i.e., x + iy where x and y denote the real and
imaginary parts respectively).

String
The string can be defined as the sequence of characters represented in the quotation marks. In
python, we can use single, double, or triple quotes to define a string.

String handling in python is a straightforward task since there are various inbuilt functions
and operators provided.

In the case of string handling, the operator + is used to concatenate two strings as the
operation "hello"+" python" returns "hello python".

The operator * is known as repetition operator as the operation "Python " *2 returns "Python
Python ".

The following example illustrates the string handling in python.

1. str1 = 'hello javatpoint' #string str1


2. str2 = ' how are you' #string str2
3. print (str1[0:2]) #printing first two character using slice operator
4. print (str1[4]) #printing 4th character of the string
5. print (str1*2) #printing the string twice
6. print (str1 + str2) #printing the concatenation of str1 and str2
Output:

he
o
hello javatpointhello javatpoint
hello javatpoint how are you

List
Lists are similar to arrays in C. However; the list can contain data of different types. The
items stored in the list are separated with a comma (,) and enclosed within square brackets [].

We can use slice [:] operators to access the data of the list. The concatenation operator (+) and
repetition operator (*) works with the list in the same way as they were working with the
strings.

Consider the following example.

1. l = [1, "hi", "python", 2]


2. print (l[3:]);
3. print (l[0:2]);
4. print (l);
5. print (l + l);
6. print (l * 3);
Output:

[2]
[1, 'hi']
[1, 'hi', 'python', 2]
[1, 'hi', 'python', 2, 1, 'hi', 'python', 2]
[1, 'hi', 'python', 2, 1, 'hi', 'python', 2, 1, 'hi', 'python', 2]

Tuple
A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of the
items of different data types. The items of the tuple are separated with a comma (,) and
enclosed in parentheses ().
A tuple is a read-only data structure as we can't modify the size and value of the items of a
tuple.

Let's see a simple example of the tuple.

1. t = ("hi", "python", 2)
2. print (t[1:]);
3. print (t[0:1]);
4. print (t);
5. print (t + t);
6. print (t * 3);
7. print (type(t))
8. t[2] = "hi";
Output:

('python', 2)
('hi',)
('hi', 'python', 2)
('hi', 'python', 2, 'hi', 'python', 2)
('hi', 'python', 2, 'hi', 'python', 2, 'hi', 'python', 2)
<type 'tuple'>
Traceback (most recent call last):
File "main.py", line 8, in <module>
t[2] = "hi";
TypeError: 'tuple' object does not support item assignment

Dictionary
Dictionary is an ordered set of a key-value pair of items. It is like an associative array or a
hash table where each key stores a specific value. Key can hold any primitive data type
whereas value is an arbitrary Python object.

The items in the dictionary are separated with the comma and enclosed in the curly braces {}.

Consider the following example.

1. d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'};


2. print("1st name is "+d[1]);
3. print("2nd name is "+ d[4]);
4. print (d);
5. print (d.keys());
6. print (d.values());
Output:

1st name is Jimmy


2nd name is mike
{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}
[1, 2, 3, 4]
['Jimmy', 'Alex', 'john', 'mike']

next →← prev

Python Functions

Functions are the most important aspect of an application. A function can be defined as the
organized block of reusable code which can be called whenever required.

Python allows us to divide a large program into the basic building blocks known as function.
The function contains the set of programming statements enclosed by {}. A function can be
called multiple times to provide reusability and modularity to the python program.

In other words, we can say that the collection of functions creates a program. The function is
also known as procedure or subroutine in other programming languages.

Python provide us various inbuilt functions like range() or print(). Although, the user can
create its functions which can be called user-defined functions.

Advantage of functions in python


There are the following advantages of C functions.

o By using functions, we can avoid rewriting same logic/code again and again in a
program.
o We can call python functions any number of times in a program and from any place in
a program.
o We can track a large python program easily when it is divided into multiple functions.
o Reusability is the main achievement of python functions.
o However, Function calling is always overhead in a python program.
Creating a function
In python, we can use def keyword to define the function. The syntax to define a function in
python is given below.

1. def my_function():
2. function-suite
3. return <expression>
The function block is started with the colon (:) and all the same level block statements remain
at the same indentation.

A function can accept any number of parameters that must be the same in the definition and
function calling.

Function calling
In python, a function must be defined before the function calling otherwise the python
interpreter gives an error. Once the function is defined, we can call it from another function or
the python prompt. To call the function, use the function name followed by the parentheses.

A simple function that prints the message "Hello Word" is given below.

1. def hello_world():
2. print("hello world")
3.
4. hello_world()
Output:

hello world

Parameters in function
The information into the functions can be passed as the parameters. The parameters are
specified in the parentheses. We can give any number of parameters, but we have to separate
them with a comma.

Consider the following example which contains a function that accepts a string as the
parameter and prints it.

Example 1
1. #defining the function
2. def func (name):
3. print("Hi ",name);
4.
5. #calling the function
6. func("Ayush")

Example 2
1. #python function to calculate the sum of two variables
2. #defining the function
3. def sum (a,b):
4. return a+b;
5.
6. #taking values from the user
7. a = int(input("Enter a: "))
8. b = int(input("Enter b: "))
9.
10. #printing the sum of a and b
11. print("Sum = ",sum(a,b))
Output:

Enter a: 10
Enter b: 20
Sum = 30

Call by reference in Python


In python, all the functions are called by reference, i.e., all the changes made to the reference
inside the function revert back to the original value referred by the reference.

However, there is an exception in the case of mutable objects since the changes made to the
mutable objects like string do not revert to the original string rather, a new string object is
made, and therefore the two different objects are printed.

Example 1 Passing Immutable Object (List)


1. #defining the function
2. def change_list(list1):
3. list1.append(20);
4. list1.append(30);
5. print("list inside function = ",list1)
6.
7. #defining the list
8. list1 = [10,30,40,50]
9.
10. #calling the function
11. change_list(list1);
12. print("list outside function = ",list1);
Output:

list inside function = [10, 30, 40, 50, 20, 30]


list outside function = [10, 30, 40, 50, 20, 30]

Example 2 Passing Mutable Object (String)


1. #defining the function
2. def change_string (str):
3. str = str + " Hows you";
4. print("printing the string inside function :",str);
5.
6. string1 = "Hi I am there"
7.
8. #calling the function
9. change_string(string1)
10.
11. print("printing the string outside function :",string1)
Output:

printing the string inside function : Hi I am there Hows you


printing the string outside function : Hi I am there

Types of arguments
There may be several types of arguments which can be passed at the time of function calling.

1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments

Required Arguments
Till now, we have learned about function calling in python. However, we can provide the
arguments at the time of function calling. As far as the required arguments are concerned,
these are the arguments which are required to be passed at the time of function calling with
the exact match of their positions in the function call and function definition. If either of the
arguments is not provided in the function call, or the position of the arguments is changed,
then the python interpreter will show the error.

Consider the following example.


Example 1
1. #the argument name is the required argument to the function func
2. def func(name):
3. message = "Hi "+name;
4. return message;
5. name = input("Enter the name?")
6. print(func(name))
Output:

Enter the name?John


Hi John

Example 2
1. #the function simple_interest accepts three arguments and returns the simple interest accordin
gly
2. def simple_interest(p,t,r):
3. return (p*t*r)/100
4. p = float(input("Enter the principle amount? "))
5. r = float(input("Enter the rate of interest? "))
6. t = float(input("Enter the time in years? "))
7. print("Simple Interest: ",simple_interest(p,r,t))
Output:

Enter the principle amount? 10000


Enter the rate of interest? 5
Enter the time in years? 2
Simple Interest: 1000.0

Example 3
1. #the function calculate returns the sum of two arguments a and b
2. def calculate(a,b):
3. return a+b
4. calculate(10) # this causes an error as we are missing a required arguments b.
Output:

TypeError: calculate() missing 1 required positional argument: 'b'

Keyword arguments
Python allows us to call the function with the keyword arguments. This kind of function call
will enable us to pass the arguments in the random order.
The name of the arguments is treated as the keywords and matched in the function calling and
definition. If the same match is found, the values of the arguments are copied in the function
definition.

Consider the following example.

Example 1
1. #function func is called with the name and message as the keyword arguments
2. def func(name,message):
3. print("printing the message with",name,"and ",message)
4. func(name = "John",message="hello") #name and message is copied with the values John and
hello respectively
Output:

printing the message with John and hello

Example 2 providing the values in different order at the calling


1. #The function simple_interest(p, t, r) is called with the keyword arguments the order of argum
ents doesn't matter in this case
2. def simple_interest(p,t,r):
3. return (p*t*r)/100
4. print("Simple Interest: ",simple_interest(t=10,r=10,p=1900))
Output:

Simple Interest: 1900.0


If we provide the different name of arguments at the time of function call, an error will be
thrown.

Consider the following example.

Example 3
1. #The function simple_interest(p, t, r) is called with the keyword arguments.
2. def simple_interest(p,t,r):
3. return (p*t*r)/100
4.
5. print("Simple Interest: ",simple_interest(time=10,rate=10,principle=1900)) # doesn't find the
exact match of the name of the arguments (keywords)
Output:

TypeError: simple_interest() got an unexpected keyword argument 'time'


The python allows us to provide the mix of the required arguments and keyword arguments at
the time of function call. However, the required argument must not be given after the
keyword argument, i.e., once the keyword argument is encountered in the function call, the
following arguments must also be the keyword arguments.

Consider the following example.

Example 4
1. def func(name1,message,name2):
2. print("printing the message with",name1,",",message,",and",name2)
3. func("John",message="hello",name2="David") #the first argument is not the keyword argume
nt
Output:

printing the message with John , hello ,and David


The following example will cause an error due to an in-proper mix of keyword and required
arguments being passed in the function call.

Example 5
1. def func(name1,message,name2):
2. print("printing the message with",name1,",",message,",and",name2)
3. func("John",message="hello","David")
Output:

SyntaxError: positional argument follows keyword argument

Default Arguments
Python allows us to initialize the arguments at the function definition. If the value of any of
the argument is not provided at the time of function call, then that argument can be initialized
with the value given in the definition even if the argument is not specified at the function call.

Example 1
1. def printme(name,age=22):
2. print("My name is",name,"and age is",age)
3. printme(name = "john") #the variable age is not passed into the function however the default
value of age is considered in the function
Output:

My name is john and age is 22

Example 2
1. def printme(name,age=22):
2. print("My name is",name,"and age is",age)
3. printme(name = "john") #the variable age is not passed into the function however the default
value of age is considered in the function
4. printme(age = 10,name="David") #the value of age is overwritten here, 10 will be printed as a
ge
Output:

My name is john and age is 22


My name is David and age is 10

Variable length Arguments


In the large projects, sometimes we may not know the number of arguments to be passed in
advance. In such cases, Python provides us the flexibility to provide the comma separated
values which are internally treated as tuples at the function call.

However, at the function definition, we have to define the variable with * (star) as *<variable
- name >.

Consider the following example.

Example
1. def printme(*names):
2. print("type of passed argument is ",type(names))
3. print("printing the passed arguments...")
4. for name in names:
5. print(name)
6. printme("john","David","smith","nick")
Output:

type of passed argument is <class 'tuple'>


printing the passed arguments...
john
David
smith
nick

Scope of variables
The scopes of the variables depend upon the location where the variable is being declared.
The variable declared in one part of the program may not be accessible to the other parts.

In python, the variables are defined with the two types of scopes.
1. Global variables
2. Local variables

The variable defined outside any function is known to have a global scope whereas the
variable defined inside a function is known to have a local scope.

Consider the following example.

Example 1
1. def print_message():
2. message = "hello !! I am going to print a message." # the variable message is local to the fu
nction itself
3. print(message)
4. print_message()
5. print(message) # this will cause an error since a local variable cannot be accessible here.
Output:

hello !! I am going to print a message.


File "/root/PycharmProjects/PythonTest/Test1.py", line 5, in
print(message)
NameError: name 'message' is not defined

Example 2
1. def calculate(*args):
2. sum=0
3. for arg in args:
4. sum = sum +arg
5. print("The sum is",sum)
6. sum=0
7. calculate(10,20,30) #60 will be printed as the sum
8. print("Value of sum outside the function:",sum) # 0 will be printed
Output:

The sum is 60
Value of sum outside the function: 0

Python Class and Objects

As we have already discussed, a class is a virtual entity and can be seen as a blueprint of an
object. The class came into existence when it instantiated. Let's understand it by an example.
Suppose a class is a prototype of a building. A building contains all the details about the floor,
doors, windows, etc. we can make as many buildings as we want, based on these details.
Hence, the building can be seen as a class, and we can create as many objects of this class.

On the other hand, the object is the instance of a class. The process of creating an object can
be called as instantiation.

In this section of the tutorial, we will discuss creating classes and objects in python. We will
also talk about how an attribute is accessed by using the class object.

Creating classes in python


In python, a class can be created by using the keyword class followed by the class name. The
syntax to create a class is given below.

Syntax
1. class ClassName:
2. #statement_suite
In python, we must notice that each class is associated with a documentation string which can
be accessed by using <class-name>.__doc__. A class contains a statement suite including
fields, constructor, function, etc. definition.

Consider the following example to create a class Employee which contains two fields as
Employee id, and name.

The class also contains a function display() which is used to display the information of the
Employee.

Example
1. class Employee:
2. id = 10;
3. name = "ayush"
4. def display (self):
5. print(self.id,self.name)
Here, the self is used as a reference variable which refers to the current class object. It is
always the first argument in the function definition. However, using self is optional in the
function call.

Creating an instance of the class


A class needs to be instantiated if we want to use the class attributes in another class or
method. A class can be instantiated by calling the class using the class name.

The syntax to create the instance of the class is given below.


1. <object-name> = <class-name>(<arguments>)
The following example creates the instance of the class Employee defined in the above
example.

Example
1. class Employee:
2. id = 10;
3. name = "John"
4. def display (self):
5. print("ID: %d \nName: %s"%(self.id,self.name))
6. emp = Employee()
7. emp.display()
Output:

ID: 10
Name: ayush

UMLDIAGRAMS:

USE CASE DIAGRAM:

A use case diagram in the Unified Modeling Language (UML) is a type of behavioral
diagram defined by and created from a Use-case analysis. Its purpose is to present a graphical
overview of the functionality provided by a system in terms of actors, their goals (represented as
use cases), and any dependencies between those use cases. The main purpose of a use case
diagram is to show what system functions are performed for which actor. Roles of the actors in
the system can be depicted.
CLASS DIAGRAM:

In software engineering, a class diagram in the Unified Modeling Language (UML) is a type of
static structure diagram that describes the structure of a system by showing the system's classes,
their attributes, operations (or methods), and the relationships among the classes. It explains
which class contains information.

SEQUENCE DIAGRAM:

A sequence diagram in Unified Modeling Language (UML) is a kind of interaction diagram that
shows how processes operate with one another and in what order. It is a construct of a Message
Sequence Chart. Sequence diagrams are sometimes called event diagrams, event scenarios, and
timing diagrams.
ACTIVITY DIAGRAM:

Activity diagrams are graphical representations of workflows of stepwise activities and actions
with support for choice, iteration and concurrency. In the Unified Modeling Language, activity
diagrams can be used to describe the business and operational step-by-step workflows of
components in a system. An activity diagram shows the overall flow of control.
SOFTWARE TESTING
8.1 Introduction:

Testing is a set of activities that can be planned in advance and conducted


systematically.For this reason a template for software testing a set of steps into which you can
placespecific test case design techniques and testing methods should be defined for the
softwareprocess.Testing is an integral part of any system or project.Software testing is an
investigationconducted to provide stakeholders with information about the quality of the product
orservice under test. Software testing can also provide an objective, independent view of
thesoftware to allow the business to appreciate and understand the risks of software
implementation. Test techniques include, but are not limited to, the process of executing a
programor application with the intent of finding software bugs. Software testing can be stated as
theprocess of validating and verifying that a computer program/application/product:
1. To uncover the errors in function logic or implementation for the software.
2. To verify that software needs the specific requirement
3. To verify that software has been implemented according to predefined standard.

8.1.1 Unit Testing:


It is basically done by the developers to make sure that their code is working fine
andmeet the user specifications.They test their piece of code which they have written like
classes,functions, interfaces and procedures.
8.1.2 Integration Testing:
Integration testing is done when two modules are integrated, in order to test the
behaviorand functionality of both the modules after integration [15]. Below are few types of
integrationtesting:
1. Big bang integration testing
2. Top down
3. Bottom up
4. Functional incremental
8.1.3 System integration testing:

System integration testing is a testing where testers basically test that in the same
environmentall the related systems should maintain data integrity and can operate in
coordinationwith other systems.It also uses black box testing technique that evaluates the
systems complianceagainst specified requirement.System Integration Testing is usually
performed on acomplete system and is preceded by the user acceptance test (UAT).

8.1.4 System testing:

In system testing the testers basically test the compatibility of the application with
thesystem.System testing of software or hardware is testing conducted on a complete,
integratedsystem to evaluate the system’s compliance with its specified requirements.
Systemtesting falls within the scope of black-box testing, and as such, should require no
knowledgeof the inner design of the code or logic.

8.1.5 Component integration testing:

This testing is basically done to ensure that the code should not break after integratingthe
two modules.Component integration testing tests the interactions between softwarecomponents
and is done after component testing.

8.1.6 Positive testing:

Positive testing is type of testing that can be performed on system by providing the
validdata as input. It checks whether an application behave as expected with the positive input.

8.1.7 Negative testing:

Negative testing is performed to ensure that the product or application under test does
notfail when an unexpected input is given.The purpose of negative testing is to break the
systemand to verify the application response during unintentional inputs.

8.1.8 Regression testing:

It verifies that software which has previously developed and tested still performs
correctly after it was changed or interfaced with other software.

8.1.9 Smoke testing:


Smoke testing is also known as build verification testing is a type of software testingthat
comprises of a non-exhaustive set of test that aim at insuring that the most importantfunctions
work.The result of this testing is used to decide if a build is stable enough toproceed with further
testing.

8.2 Creating User Account


Expected Actual
Sr. Description for output for test Output for Remar
No Test cases Test Data cases Testcases k Comments

1 Start camera camera started success pass success


Real time success
2 capturing vedio captured Pass success

Eye status
3 Eye status analyzed analyzed success Pass success
Eye variable
4 storage storage stored success pass success

Drowsiness Drowsines
5 detection s detection detected success pass success

Expected
Descriptio output Actual
n for Test for test Output for Remar
Sr. No cases Test Data cases Testcases k Comments
Alarm
runnin Alarm
g running alarm run success Pass success
CONCLUSION

A lot of accidents are caused due to drowsy driving every year and it often goes undetected
thereby leading to huge loss of lives and resources. We are presenting a system that detects
drowsiness while driving and alerts the driver for the same. Such systems are available in high
end cars only. Our system uses the IR camera which is placed in front of the driver. The
detection of eyes closed is efficient and works under different situations. Hence we provide users
with a cheap technology.

You might also like