Professional Documents
Culture Documents
By:
Advisor:
Dr. Dereje S.
Addis Ababa
Ethiopia, June, 2016
i|Page
Camera based traffic light control system on raspberry-pi 2016
By:
Approval by:
Advisor
Examiner 1 Signature
ii | P a g e
Camera based traffic light control system on raspberry-pi 2016
Certification
The undersigned certify that he has read the thesis entitled: camera based traffic light
control system using raspberry pi and hereby recommend for acceptance by the Addis
Ababa University in partial fulfillment of the requirements for the degree of Bachelors of
Science.
____________________________________
iii | P a g e
Camera based traffic light control system on raspberry-pi 2016
We, declare that this thesis paper is our own original work and that it has not been presented
and will not be presented by us to any other University for similar or any other degree award. This
paper is copyright material protected. It may not be reproduced by any means, in full or in part,
except for short extracts in fair dealing, for research or private study, critical scholarly review or
discourse with an acknowledgement, without written permission of the school of Electrical and
Computer Engineering, on behalf of both the author and Addis Ababa University.
Signature
iv | P a g e
Camera based traffic light control system on raspberry-pi 2016
Acknowledgment
First and foremost, we would like to thank the God Almighty who blessed and supported us
in every step of our journey and entitled us for this opportunity.
Our families, friends and are second only to God, in creating good working environment by
sharing our other responsibilities.
We would like also thank the staff members of School of Electrical and Computer
Engineering for their cooperation and assistance during our study.
This project would not be successfully completed without the supervision and critical
leading of our advisor Dr. Dereje Shiferaw.
v|Page
Camera based traffic light control system on raspberry-pi 2016
Abstract
The availability and the growing number of automobiles in Ethiopia, especially in Addis
Ababa brought some problems. Some of the problems are happening because of the operating
technique of conventional traffic lights. They work by allocating equal and fixed time for every
road that is regardless of their respective load. Mostly as a result of this, we see traffic conjunctions
around several road junction areas of the city. Hence, we can say the very approaches that are made
to solve the problem, sometimes become cause of the problem.
We have learned that the Addis Ababa City Road Administration has tried to solve the
problem, using the statistical way of time allocation at some areas of the city, but the problem is yet
far from removed. This all implies that another way of solution should be proposed.
This project is designed to develop a system which performs execution based on density of
vehicles (Vehicle Count). After calculating the number of vehicles we will came to know in which
lane the density is high and based on which signals will be allotted for a particular lane.
Raspberry pi is used as a microcontroller for image processing and also provides the
signaling time based on the traffic density.
Hence, in this project a density based Traffic Light Controlling System simulation and
prototype is developed to improve the conventional traffic lights of our city.
Key words: raspberry-pi, image processing, traffic congestion, lane, traffic signal
vi | P a g e
Camera based traffic light control system on raspberry-pi 2016
Table of Contents
Declaration and Copy Right .......................................................................................................................... iv
Acknowledgment .............................................................................................................................................. v
Abstract ........................................................................................................................................................... vi
List of acronyms ............................................................................................................................................. xii
Chapter One ..................................................................................................................................................... 1
1. Introduction.............................................................................................................................................. 1
1.1. Overview of the project ................................................................................................................... 1
1.2. Problem Statement .......................................................................................................................... 2
1.3. Objective of the project ................................................................................................................... 5
1.3.1. General Objective ...................................................................................................................... 5
1.3.2. Specific Objectives ..................................................................................................................... 5
1.4. Scope of the project.......................................................................................................................... 6
1.5. Document Organization .................................................................................................................. 7
1.6. Limitation ......................................................................................................................................... 7
Chapter Two..................................................................................................................................................... 8
2. Literature Review .................................................................................................................................... 8
2.1. Traffic light system .......................................................................................................................... 8
2.1.1. Definition of Traffic Conjunction ............................................................................................... 9
2.1.2. Source of Traffic Conjunction .................................................................................................... 9
2.1.3. Solutions of traffic conjunction................................................................................................ 10
2.2. Image processing ............................................................................................................................ 13
2.2.1. Types image processing ........................................................................................................... 15
Chapter Three ................................................................................................................................................ 16
3. Detail about System Components of the Project ................................................................................. 16
3.1. Hardware Components ................................................................................................................. 16
3.1.1. RASPBERY – PI .......................................................................................................................... 16
3.1.2. USB Web Camera ..................................................................................................................... 24
3.1.3. Stepper Motor ......................................................................................................................... 25
vii | P a g e
Camera based traffic light control system on raspberry-pi 2016
viii | P a g e
Camera based traffic light control system on raspberry-pi 2016
ix | P a g e
Camera based traffic light control system on raspberry-pi 2016
List of Tables
x|Page
Camera based traffic light control system on raspberry-pi 2016
List of Figures
xi | P a g e
Camera based traffic light control system on raspberry-pi 2016
List of acronyms
RGB- Red-Green-Blue
xii | P a g e
Camera based traffic light control system on raspberry-pi 2016
Chapter One
1. Introduction
Traffic lights, which may also be known as stoplights, traffic lamps, traffic signals, stop-
and-go lights are signaling devices positioned at road intersections, pedestrian crossings and other
locations to control competing flows of traffic. Traffic lights have been installed in most cities
around the world.
The most common traffic lights consist of a set of three lights: red, yellow (umber), and
green (the colors of the lights are shown in Figure 1. When illuminated, the red light indicates for
vehicles facing the light to stop; the yellow indicates caution, either because lights are about to
turn green or because lights are about to turn red; and the green light to proceed (if it is safe to do
so). There are some variations in the use and legislation of traffic lights, depending on the
customs of a country and the special need of a particular intersection.
Traffic problems nowadays are increasing because of the growing number of vehicles, and
the limited resources provided by current infrastructure in roads. As we know in Ethiopia the
population in cities and number of cars is increasing day to day. With increasing urban population
and hence the number of cars, need of controlling streets, highways and roads is vital. Traffic is the
major problem which Ethiopia, especially down towns in Addis Ababa, faces today.
1|Page
Camera based traffic light control system on raspberry-pi 2016
The increase in number of vehicles resulting to the need of a smart system that could
efficiently handle traffic congestion based on the density of traffic.
We proposed a system design for controlling the traffic light by image processing. A
camera will be installed on a stepper motor alongside the traffic light and will rotate in some pre
specified direction which could capture image sequence from the road. A step by step approach of
image acquisition, image processing and implementation of algorithm to change the traffic light
duration as per the density of vehicles on different roads at a traffic signal is followed. The number
of objects in a given image is counted and enough time is given according to their density.
The proposed control system solves the current traffic problem which frequently happens
due to a time based traffic control system.
Although one of the benefits of traffic lights is to minimize the high traffic conjunction and
to facilitate the traffic flow, sometimes the very system that is built to avoid the traffic conjunction
becomes a reason in creating it. Poor traffic signal timing accounts for an estimated 10 percent of
all traffic delay.
The monitoring and control of city traffic is becoming a major problem in many countries.
Even in Addis Ababa with the ever increasing number of vehicles on the road, the Addis Ababa
City Roads Authority has to find new ways or measures of overcoming such a problem. The
measures taken are development of new roads and flyovers (underpass and overpass) in the
middle of the City; building (rebuilding) large roundabouts in major traffic interchanges, building
of the ring road, planning to build electric buses and city trains and restricting of large vehicles at
some areas of the city during peak hours. Though all these things are being planned or done, the
problem is still far from solved.
How many times have we been sitting at a stoplight for 2, 3 minutes, no cars coming from
any direction? At some selected areas of the city it’s observed that when there were no cars from
some directions, the traffic light system is operating by giving equal time for green light for all
2|Page
Camera based traffic light control system on raspberry-pi 2016
the directions that are with the highest possible load. It’s seen that before the roads with the highest
load completely free from their respective load, the nearly empty roads were getting their next
round green light time consistently, it seems illogical.
Inconvenience will be caused by unnecessary waiting; people will lose time, miss
opportunities and get frustrated. Traffic congestion problems create a deep impact on companies’
3|Page
Camera based traffic light control system on raspberry-pi 2016
productivity and transportation of goods. In addition, the existing traffic control system may have
the following major problems:
It wastes the precious time in commuter caused by traffic lights.
There is an excess expenditure on government on traffic police.
There is an unnecessary road construction for reducing a traffic jam, which can be
reduced by using a smart traffic light control.
There is high fuel consumption which is caused by traffic jam on junctions.
So to solve all the above mentioned problems, we can implement the system that controls
the traffic based on the density of vehicles at any particular lane. With this system, we shall
consider the density of vehicles at each side at the junction and give path to the particular side
which has high density of vehicles and keep the remaining in stop position.
4|Page
Camera based traffic light control system on raspberry-pi 2016
The main objective of this project is to change the current time based traffic control system
by density based, which is by considering the density of the vehicles in each lane and giving
appropriate green signaling time.
5|Page
Camera based traffic light control system on raspberry-pi 2016
There are different types of road junctions in Addis Ababa. But given that a 4 way road
junction (at 4 way road junctions there are a total of four traffic lights, which controls traffic from
every particular direction) is common, we restrict our system to a 4-way junction (as shown in
Figure 3).Hence our traffic control system design based on density is implemented in this four way
road junction.
6|Page
Camera based traffic light control system on raspberry-pi 2016
This thesis work is organized into six chapters and associated reference and appendix.
The first chapter is an introduction that includes overview of the project, statement of the
problem, objectives, and scope of the project and significance of the study as well as the overall
thesis outline.
Chapter two covers the review of the main related facts from references used in the study
and review of earlier studies. The various studies conducted in specific parts of the entire study area
are well described and used in the study. And in this chapter a literature about image processing is
reviewed.
Chapter three covers the detail hardware and software components used to implement the
project. In the hardware part, a description about raspberry pi, stepper motor and its driver which is
L293D, an Intex IT 309 WC is mentioned in detail.
Chapter four covers the methodology and system design of the project.in this chapter the
algorithms followed to implement the proposed project is described and covered in detail.
In Chapter five the hardware implementation of the project is presented. Chapter six
discusses the conclusion, discussions, and recommendations of the implementation of the project.
1.6. Limitation
7|Page
Camera based traffic light control system on raspberry-pi 2016
Chapter Two
2. Literature Review
It is clear that increasing traffic congestion does impose costs upon travelers and affect
broader business operations; it has been difficult to develop and apply empirical measures of the
extent of the traffic congestion and its economic costs. Even though, proper measuring the extent or
level of congestion is an important step for understanding the performance of the existing road
network, for evaluation of proposed congestion mitigation measures and for evaluation of cost of
congestion; (Weisbrod et.al, 2003; Taddesse, 2011).
8|Page
Camera based traffic light control system on raspberry-pi 2016
The definition of congestion is imprecise and is made more difficult since people have
different perceptions and expectations of how the system should perform based on whether they are
in rural or urban areas, in peak or off peak, and as a result of the history of an area (Bertini, 2005).
9|Page
Camera based traffic light control system on raspberry-pi 2016
There are lots of methods in our world to design and build modern traffic light controlling
systems as a solution for the occurring traffic conjunction. The following are some of them:
Lei, Leong; Intelligent traffic lights using GSM. A traffic signal control
system employing Universal Coordinated Time (UTC) of GPS as time base
comprising: a core system for receiving data of GPS, and to include longitude
and latitude data and to convert information to local time as a common time basis
for the traffic signal control system;
Khalid A. S al developed an intelligent RFID traffic control.
RFID stands for Radio Frequency Identification, a technology that uses tiny
computer
10 | P a g e
Camera based traffic light control system on raspberry-pi 2016
chips smaller than a grain of sand to track items at a distance. This technology can
be
applied to a multi vehicle, multi-lane and multi road junction area to provide an
efficient time management scheme. A dynamic time schedule was worked out for
the passage of each column.
The intelligent traffic control system consists of four main parts: the RFID tags, the Cisco
access point, the Cisco location server and Wide Area Network (WAN). The first simulates the
moving vehicles; the second detects the RFID tags, the third acts as RFID software and fourth
simulate the ubiquitous environment. The location server acts as the microcontroller of the traffic
signal. It will collect the location and tagging time of the data from reader. This information is sent
to the management system via Internet. The management system using intelligent algorithm will
then send suitable instructions to control the traffic;
Another expert system uses a set of given rules to decide upon the next action.
In traffic light control, such an action can change some of the control
11 | P a g e
Camera based traffic light control system on raspberry-pi 2016
12 | P a g e
Camera based traffic light control system on raspberry-pi 2016
Maliket et al. use magnetometer sensor for vehicle detection. The sensor
detects distortions of the Earths field caused by a large ferrous object like a
vehicle. Since the distortion depends on the ferrous material, its size and
orientation, a magnetic signature is induced corresponding to the vehicles
shape and configuration. For detecting the presence of a vehicle, measurements
of the (vertical) z-axis is a better choice as it is more localized and the signal
from vehicles on adjacent lanes can be neglected.
All these different types of intelligent traffic light systems give the impression of
performing far better than the conventional traffic light control system. But they are based on
modern, latest and expensive techniques, and these techniques need some support from other
domains as well. Hence, it seems we have to use some other technique to reach the goal of
implementing density based traffic control system. For this reason, we have selected to solve the
problem of the city using an image processing technology to determine the vehicles density with the
help of Raspberry pi.
Image processing usually refers to digital image processing, but optical and analog image
processing also are possible. This article is about general techniques that apply to all of them. The
acquisition of images (producing the input image in the first place) is referred to as imaging.
Closely related to image processing are computer graphics and computer vision. In computer
graphics, images are manually made from physical models of objects, environments, and lighting,
13 | P a g e
Camera based traffic light control system on raspberry-pi 2016
instead of being acquired (via imaging devices such as cameras) from natural scenes, as in most
animated movies. Computer vision, on the other hand, is often considered high-level image
processing out of which a machine/computer/software intends to decipher the physical contents of
an image or a sequence of images (e.g., videos or 3D full-body magnetic resonance scans).
In modern sciences and technologies, images also gain much broader scopes due to the ever
growing importance of scientific visualization (of often large-scale complex scientific/experimental
data). Examples include microarray data in genetic research, or real-time multi-asset portfolio
trading in finance.
Or Image processing is a method to convert an image into digital form and perform some
operations on it, in order to get an enhanced image or to extract some useful information from it. It
is a type of signal dispensation in which input is image, like video frame or photograph and output
may be image or characteristics associated with that image. Usually Image Processing system
includes treating images as two dimensional signals while applying already set signal processing
methods to them.
It is among rapidly growing technologies today, with its applications in various aspects of a
business. Image Processing forms core research area within engineering and computer science
disciplines too.
14 | P a g e
Camera based traffic light control system on raspberry-pi 2016
The two types of methods used for Image Processing are Analog and Digital Image Processing.
Analog or visual techniques of image processing can be used for the hard copies like printouts and
photographs. Image analysts use various fundamentals of interpretation while using these visual
techniques. The image processing is not just confined to area that has to be studied but on
knowledge of analyst. Association is another important tool in image processing through visual
techniques. So analysts apply a combination of personal knowledge and collateral data to image
processing.
Digital Processing techniques help in manipulation of the digital images by using computers.
As raw data from imaging sensors from satellite platform contains deficiencies. To get over such
flaws and to get originality of information, it has to undergo various phases of processing. The three
general phases that all types of data have to undergo while using digital technique are Pre-
processing, enhancement and display, information extraction.
15 | P a g e
Camera based traffic light control system on raspberry-pi 2016
Chapter Three
Raspberry-pi
Stepper motor
Webcam
Breadboard
USB Wi-Fi adapter
LEDs
Resisters
L293D(H-bridge) motor driver
Conducting wires
PCB Board
3.1.1. RASPBERY – PI
16 | P a g e
Camera based traffic light control system on raspberry-pi 2016
17 | P a g e
Camera based traffic light control system on raspberry-pi 2016
Like every computer, the Raspberry Pi needs an operating system, and the preferred one for
the Pi is Linux. That’s partly because it’s free, but mainly it’s because it runs on the Pi’s ARM
processor while most other operating systems work only on the Intel architecture. Still, not every
Linux distribution will run on the Pi, because some do not support the Pi’s particular type of ARM
processor. The Raspbian is the one that supported by the pi and has an image called Debian wheezy
or Debian Jessie (this is the one used in our case).
Raspberry Pi doesn’t have a BIOS or internal persistent storage. It has only an SD card slot.
Preparing the SD card on a Windows box is the most convenient alternative, because of
18 | P a g e
Camera based traffic light control system on raspberry-pi 2016
Win32DiskImager. This application has a nice user interface, and has a single purpose which is
writing images to SD cards.
After completing the above action the SD card will become bootable and consisting of
Raspbian, Jessie operating system.
We use our raspberry pi by connecting it to our pc. This requires wired or wireless network
between the pi and our pc. This mechanism of using raspberry pi as a computer is known as
headless.
One of the best ways to communicate securely between two computers is Secure Shell
(SSH), a network protocol for secure data communication. Raspbain comes with everything needed
to use SSH, there is only a few things have to configured.
This method helps us to use mouse, keyboard, and other accessories from a single computer;
even if there may be a possible disadvantage of using SSH which is it works only in a text terminal.
This limitation on the other hand can be overcome by using virtual network computing (VNC), a
technology that transmits the whole screen and all mouse and keyboard events from one computer
to another.
19 | P a g e
Camera based traffic light control system on raspberry-pi 2016
Basically to enable VNC, there must be a client and server. The server runs on the machine
we would like to control which is in our case is the raspberry pi, and the client runs on the
controlling machine which is a laptop. One thing we have to do is installing the VNC server on our
raspberry pi. This is can be done via apt-get install tightvncserver command in the terminal side.
When tightvncserver is run for the first time, it asks to set a password. This password is
entered when the VNC is connected every time. To address a virtual screen, we need two things:
the IP address of the Pi and the port address of the screen.
20 | P a g e
Camera based traffic light control system on raspberry-pi 2016
Getting the access of internet via raspberry pi was critical desired during project time. The
main areas we need the access of internet was during installing Open CV, which take almost 2 days,
and many other software on pi. Basically whenever we try to install software’s which are not
included in the Raspbian operating system needs an internet access.
Joining wired networks via Ethernet is not usually complex task: plug in the Ethernet cable
and we’re done. However we are using the Ethernet port to connect the pi with our laptop to setup
the headless connection so we can’t use the Ethernet cable as source of internet for the pi. So, we
forced to investigate a possible way of getting an access of internet via wireless mode. To access a
wireless network we need to do a bit more. First, we need a Wi-Fi adapter for the USB port,
because the Pi’s hardware does not support Wi-Fi by default. We plug Wi-Fi adapter into one of
the Pi’s USB ports and run the lsusb command to see if the Pi recognizes it properly:
21 | P a g e
Camera based traffic light control system on raspberry-pi 2016
This command will display the wireless networks which are within reach. The next step
after recognizing the available wireless networks is that connecting the Wi-Fi to pi using the
commands below:
Sudo nano /etc/wpa_supplicant/wpa_supplicant.conf.
The above command is used to open the wpa-supplicant configuration file in nano. In
upcoming window we give the name of the ESSID (Wi-Fi name) and the password of it.
Network= {
ssid="The_ESSID_from_earlier"
psk="A_wifi_password"(if any)
22 | P a g e
Camera based traffic light control system on raspberry-pi 2016
}
Electronic devices such as LEDs, displays, electric motors and other similar input or
output devices are connected to the pi through GPIO pins. In model B there are 26 pins in to rows
containing 13 pins each. The top row contains the even-numbered pins and the other row contains
the odd-numbered pins. That is, the first pin in the lower row is pin 1, for simplification it is
depicted by labeling ―P1‖ on the pi below.
↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑
Pin 2 4 6 8 10 12 14 16 18 20 22 24 26
Pin 1 3 5 7 9 11 13 15 17 19 21 23 25
↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
3V3 GPIO GPIO GPIO - GPIO GPIO GPIO - GPIO GPIO GPIO -
0 4
1 17 21 22 10 9 11
Using pin 1 and pin 2, we can supply voltage + 3.3v and +5v for external electronic
devices connected to pi, respectively. The Pi limits the output of pin 1 to 50mA, while pin 2 allows
for a current draw that depends on the USB input current. If you power the Pi with a 1A power
supply, for example, you can draw up to 300mA from pin 2, because the Pi Model B needs 700mA
for itself. Pin 6 is assigned to share a common ground for electrical device connected to it. Pin 4, 9,
23 | P a g e
Camera based traffic light control system on raspberry-pi 2016
14, 20, and 25 are reserved for future enhancements. Other remaining pins are General-Purpose
Input/output (GPIO).
A webcam is a video camera that feeds or streams its image in real time to or through a
computer network. Unlike an IP camera (which connects using Ethernet or Wi-Fi), a webcam is
generally connected by a USB cable, or similar cable, or built into computer hardware, such as
laptops.
Characteristics
Webcams are known for their low manufacturing cost and their high flexibility. Despite
the low cost, the resolution offered is rather impressive. They have also become a source of security
and privacy issue, as some built in webcams can be remotely activated by spyware.
The most popular use of webcam is the establishment of video links, permitting computers
to act as video phones. Other popular uses include security, computer vision, and video
broadcasting and for recording social videos. The video streams provided by webcams can be used
for a number of purposes.
In our case the USB web camera is used to capture the real time images of the road. We
use an INTEX IT-309WC web camera for this purpose. Its features and specifications are given in
table below:
Resolution 300K pixels to 16 mega pixels
24 | P a g e
Camera based traffic light control system on raspberry-pi 2016
The camera is installed on a stepper motor so that it has a capability of rotating in all four
directions to capture the image on each lane.
25 | P a g e
Camera based traffic light control system on raspberry-pi 2016
There are basically three types of stepping motors; variable reluctance, permanent magnet
and hybrid. They differ in terms of construction based on the use of permanent magnets and/or iron
rotors with laminated steel stators.
Permanent magnet stepper (can be subdivided into 'tin-can' and 'hybrid', tin-can
being a cheaper product, and hybrid with higher quality bearings, smaller step angle,
higher power density)
Variable reluctance stepper
Hybrid synchronous stepper
26 | P a g e
Camera based traffic light control system on raspberry-pi 2016
The permanent magnet motor, also referred to as a "canstack" motor, has, as the name implies,
a permanent magnet rotor. It is a relatively low speed, low torque device with large step angles of
either 45 or 90 degrees. Its simple construction and low cost make it an ideal choice for non-
industrial applications, such as a line printer print wheel positioner.
Unlike the other stepping motors, the PM motor rotor has no teeth and is designed to be
magnetized at a right angle. Applying current to each phase in sequence will cause the rotor to
rotate by adjusting to the changing magnetic fields. Although it operates at fairly low speed the PM
motor has a relatively high torque characteristic to its axis.
The variable reluctance motor does not use a permanent magnet. As a result, the motor rotor
can move without constraint or "detent" torque. This type of construction is good in non-industrial
applications that do not require a high degree of motor torque, such as the positioning of a micro
slide.
27 | P a g e
Camera based traffic light control system on raspberry-pi 2016
The variable reluctance motor in the above illustration has three "stator pole sets" (A, B, C,),
set 15 degrees apart. Current applied to pole A through the motor winding causes a magnetic
attraction that aligns the rotor (tooth) to pole A. Energizing stator pole B causes the rotor to rotate
15 degrees in alignment with pole B. This process will continue with pole C and back to A in a
clockwise direction. Reversing the procedure (C to A) would result in a counterclockwise rotation.
Hybrid motors combine the best characteristics of the variable reluctance and permanent
magnet motors. They are constructed with multi-toothed stator poles and a permanent magnet rotor.
Standard hybrid motors have 200 rotor teeth and rotate at 1.80 step angles. Other hybrid motors are
available in 0.9ºand 3.6º step angle configurations. Because they exhibit high static and dynamic
torque and run at very high step rates, hybrid motors are used in a wide variety of industrial
applications.
28 | P a g e
Camera based traffic light control system on raspberry-pi 2016
A microprocessor cannot drive a motor directly, since it cannot supply enough current. Instead,
there must be some interface circuitry so that the motor power is supplied from another power
source and only the control signals derive from the microprocessor. This interface circuitry can be
implemented by a circuit known as the H-bridge. An H-bridge merely consists of 4 switches
connected in topology of an H, where the motor terminals form the crossbar of the H.
29 | P a g e
Camera based traffic light control system on raspberry-pi 2016
In an H-bridge, the switches are opened and closed in a manner so as to put a voltage of one
polarity across the motor for current to flow through it in one direction or a voltage of the opposite
polarity, causing current to flow through the motor in the opposite direction for reverse direction.
For in case of our project we use an L293D IC for driving of a bipolar stepper motor purpose.
The L293D contains two H-bridges for driving small DC motors. It can also be used to drive
stepper motors because stepper motors are, in fact, two (or more) coils being driven in a sequence,
backwards and forwards.
The L293D is quadruple high-current half-H driver. The L293D is designed to provide
bidirectional drive currents of up to 600-mA at voltages from 4.5 V to 36 V.
30 | P a g e
Camera based traffic light control system on raspberry-pi 2016
A Light emitting diode (LED) is essentially a p-n junction diode. When carriers are injected
across a forward-biased junction, it emits incoherent light. Most of the commercial LEDs are
realized using a highly doped n and a p Junction.
LEDs produce more light per watt than incandescent bulbs; this is useful in battery
powered or energy-saving devices.
LEDs can emit light of an intended color without the use of color filters that traditional
lighting methods require. This is more efficient and can lower initial costs.
The solid package of the LED can be designed to focus its light. In case of other light
sources such as incandescent often require an external reflector to collect light and direct
it in a usable manner.
LEDs are ideal for use in applications that are subject to frequent on-off cycling.
LEDs, being solid state components, are difficult to damage with external shock. So they
can have a relatively long useful life.
LEDs light up very quickly. A typical red indicator LED will achieve full brightness in
microseconds
LEDs can be very small and are easily populated onto printed circuit boards.
In our project LEDs are used to represent the three well known traffic signals (RED, Amber
and Green).
31 | P a g e
Camera based traffic light control system on raspberry-pi 2016
Raspbian OS
Open CV
Python
SSH client
VNC viewer
3.2.1. Raspbian OS
Raspbain is open source software from Unix-like family with ARM platform. It is also a free
operating system based on Debian optimized for the raspberry pi hardware. An operating system is
a set of basic programs and utilities that make our raspberry pi run. However, Raspbian provides
more than a pure OS: it comes with over 35,000 packages precompiled software bundled in a nice
format for easy installation on your raspberry pi.
3.2.2. Python
Python combines remarkable power with very clear syntax. It has modules, classes, exceptions,
very high level dynamic data types, and dynamic typing. There are interfaces to many system calls
and libraries, as well as to various windowing systems. New built-in modules are easily written in C
or C++ (or other languages, depending on the chosen implementation). Python is also usable as an
extension language for applications written in other languages that need easy-to-use scripting or
automation interfaces.
32 | P a g e
Camera based traffic light control system on raspberry-pi 2016
3.2.3. Open CV
Open CV (Open Source Computer Vision) is a library of programming functions mainly aimed
at real-time computer vision, originally developed by Intel's research center in Nizhny Novgorod
(Russia), later supported by Willow Garage and now maintained by Itseez. The library is cross
platform and free for use under the open-source BSD license. Open CV is written in C++ and its
primary interface is in C++, but it still retains a less comprehensive though extensive older C
interface. There are bindings in Python, Java and MATLAB/OCTAVE. All of the new
developments and algorithms in Open CV are now developed in the C++ interface.
History
Officially launched in 1999, the Open CV project was initially an Intel Research initiative to
advance CPU-intensive applications, part of a series of projects including real-time ray tracing and
3D display walls. The main contributors to the project included a number of optimization experts in
Intel Russia, as well as Intel’s Performance Library Team. In the early days of Open CV, the goals
of the project were described as:
Advance vision research by providing not only open but also optimized code for basic vision
infrastructure. No more reinventing the wheel.
33 | P a g e
Camera based traffic light control system on raspberry-pi 2016
To support some of the above areas, Open CV includes a statistical machine learning library
that contains:
Boosting
Decision tree learning
Gradient boosting trees
Expectation-maximization algorithm
k-nearest neighbor algorithm
34 | P a g e
Camera based traffic light control system on raspberry-pi 2016
In computing, virtual network computing (VNC) is graphical desktop sharing system that uses
the remote frame buffer protocol (RFB) to remotely control another computer. It transmits the
keyboard and mouse events from one computer to another, relaying the graphical screen updates
back in the other direction, network.
VNC is a platform-independent. There are clients and servers for many GUI based operating
systems and for java. Multiple clients may connect to a VNC as the same time. Popular uses for this
technology includes remote technical support and accessing files on ones work computer from
one’s home computer, or vice versa. There are number of variants of VNC server which offer their
own particular functionality.
SSH server is designed for all windows NT-series OS. Supported platforms include all desktop
and server versions of windows starting from windows XP and windows server 2003 to the most
recent including windows 8.X and windows 10 both in 32 and 64 bit versions of windows.
35 | P a g e
Camera based traffic light control system on raspberry-pi 2016
Chapter Four
Stepper Camera
Motor
RASPBERRY-PI Hardware
Motor
Software Based Image
Driver processing and Traffic
Density Estimation
using Raspberry Pi
Power Supply
36 | P a g e
Camera based traffic light control system on raspberry-pi 2016
A stepper motor is chosen to hold a camera and rotate in a designed fashion. The stepper motor
rotates 90 degrees and then stops, so that the camera takes a picture of that specific lane and sends
the image for further processing. After that the stepper motor rotates to next lane which is 90
degrees from the current lane.
We have selected OKI KBL42LLB560B model stepper motor for our specific application
(rotating a 200g weighting camera).
This stepper motor has voltage rating of 6.4V and 7.5 stepping degree. So a total of 12 steps
makes the stepper motor rotates 90 degrees.
37 | P a g e
Camera based traffic light control system on raspberry-pi 2016
The Raspberry pi model B generally has 26 pins arranged in two rows containing 13 pins
each. The top row contains the even-numbered pins, and the other row contains the odd-numbered
pins of which 20 of the can be used as GPIO.
By configuring any four of the GPIO pins of the pi, to generate a square wave output, we can
control the stepper motor using through a driver. In order to do so a python script would be a good
coding environment to generate the square wave on the pi GPIOs’.
import time
import sys
GPIO.setmode (GPIO.BCM)
GPIO.output (pin, 0)
[0, 1, 1, 0],
38 | P a g e
Camera based traffic light control system on raspberry-pi 2016
[0, 1, 0, 1],
[1, 0, 0, 1]]
time.sleep (0.05)
GPIO.cleanup ()
In this python script the stepper motor is controlled to move 12 steps in effect rotating 90
degrees.
Using a breads board and jumper wires we have built the stepper controlling circuit as shown
below.
39 | P a g e
Camera based traffic light control system on raspberry-pi 2016
Open CV is an open source image processing library created by Intel. Which is available for
C/C++/Python?
The installation process of Open CV and python on the pi generally take 8-12 hours.
The first thing you should do is expand your file system to include all available space on your
micro-SD card:
40 | P a g e
Camera based traffic light control system on raspberry-pi 2016
Once prompted, you should select the first option, “1. Expand File System”, hit Enter on your
keyboard, arrow down to the “<Finish>” button, and then reboot your Pi.
You then need to install some developer tools, including CMake, which helps us configure
the Open CV build process:
41 | P a g e
Camera based traffic light control system on raspberry-pi 2016
Next, we need to install some image I/O packages that allow us to load various image file
formats from disk. Examples of such file formats include JPEG, PNG, TIFF, etc.:
Just as we need image I/O packages, we also need video I/O packages. These libraries allow
us to read various video file formats from disk as well as work directly with video streams:
The Open CV library comes with a sub-module named high GUI which is used to display
images to our screen and build basic GUIs. In order to compile the high GUI module, we need to
install the GTK development library:
Many operations inside of Open CV (namely matrix operations) can be optimized further by
installing a few extra dependencies
Lastly, let’s install both the Python 2.7 and Python 3 header files so we can compile Open
CV with Python bindings:
42 | P a g e
Camera based traffic light control system on raspberry-pi 2016
Now that we have our dependencies installed, let’s grab the archive of Open CV from the
official Open CV repository.
Before we can start compiling Open CV on our Raspberry Pi 3, we first need to install pip, a
Python package manager
Our only Python dependency is NumPy, a Python package used for numerical processing:
We are now ready to compile and install Open CV! We can setup our build using CMake:
43 | P a g e
Camera based traffic light control system on raspberry-pi 2016
Here we have finished the installation process and we can build different open CV project from
now on
we have web camera which is mounted on our stepper motor, so that it can rotates in all
four directions and connected with our raspberry pi(with a USB connection)in order to capture real
time image and send the image for further image processing.
Open CV and python gives the platform to capture the image using the webcam.
The python code shown below captures image and stores it in the home directory with a
name of real_time.jpg.
camera_port = 0
camera = cv2.VideoCapture(camera_port)
def get_image():
retval, im = camera.read()
return im
temp = get_image()
print("Taking image...")
camera_capture = get_image()
file = "/home/pi/real_time.jpg"
cv2.imwrite(file, camera_capture)
del(camera)
44 | P a g e
Camera based traffic light control system on raspberry-pi 2016
Image Image
enhancement enhancement
Object detection
Object
(mean square
detection
error)
(mean square
error)
Image Matching
Timing Allocation
45 | P a g e
Camera based traffic light control system on raspberry-pi 2016
The acquired image is converted to grey scale image for further processing. The grey scale
image is then converted to a binary image that contains only two colors, black and white. This
image is known as the threshold image. The main purpose of threshold the image is a radical
reduction of information in order to simplify further processing. The threshold image is then
complemented for further image processing.
The desired portion of the image is retained and the rest is cropped. Only the lane at which
there is an incoming traffic at the junction is to be processed. Hence the image is cropped to select
that section of the lane.
In this process the images are adjusted in such a way that the results are more suitable for
further processing. In this, the obtained image is converted into a greyscale image.
4.3.4. Thresholding
Thresholding is transforming the greyscale image into black and white image (binary:
white=1, black=0). The main purpose of thresholding is a radical reduction of information in order
to simplify further processing. White color is assigned to all the pixels that have luminosity greater
than the threshold level and the others as black.
46 | P a g e
Camera based traffic light control system on raspberry-pi 2016
MSE is a mechanism to calculate the mean difference of two images, which takes two
images and returns the mean square error of the two images. It’s important to note that a value of 0
for MSE indicates perfect similarity. A value greater than one implies less similarity and will
continue to grow as the average difference between pixel intensities increases as well.
Object detection is a mechanism of detecting different objects from a given image. Simply
put, object detection in Open CV is one of machine learning. Haar like feature is a good and
recommended way of training your own object detection xml file.
47 | P a g e
Camera based traffic light control system on raspberry-pi 2016
1-5 30
6-10 45
11-15 60
15-20 90
>20 >90
48 | P a g e
Camera based traffic light control system on raspberry-pi 2016
The general flow chart of the overall or the implemented system is given in figure below:
Start
Stepper motor on to
rotate a webcam
Camera on to acquire
image
Image processing
Vehicle density
End
49 | P a g e
Camera based traffic light control system on raspberry-pi 2016
Chapter Five
5. Hardware implementation
This chapter discusses the system development tools and hardware components applied for
implementing the camera based automatic Traffic light Controlling System using raspberry pi.
Moreover, the prototype, hardware components and testing of the system are also detailed in this
chapter.
To make the system close to reality, different tools are applied. The programming language,
the hardware components and the testing mechanisms are major parts of the development tools.
The road selected for the prototype of this camera based Traffic light Controlling System
using raspberry pi is a 4 way junction road. Therefore it has 3 colored traffic lights which are
basically LEDs at each of the four directions.
Basically we can say that the system works based on the dynamic traffic light condition.
Whenever one of the roads is under the green time operation the system will stay in its previous
50 | P a g e
Camera based traffic light control system on raspberry-pi 2016
state and when the system is in yellow state the motor rotates and the camera captures the current
traffic congestion of the remaining lanes. Then the system will set the green signal according the
processed image which is sent from the raspberry pi. Afterward when the time of the current road
expires, the permission will be given for the next road according to the traffic congestion of that
specific lane.
Generally the system checks the traffic state of the four lanes and gives enough green time
signals to the congested lane. This process repeats in a continuous loop.
5.3. Prototype
The system categorizes three different standard lights (GREEN, RED, YELLOW) into 4
groups. Every group has a set of traffic lights (red, green, and yellow) for signaling purpose.
The system prototype is basically the real time system which consists
Cars,
Properly scaled road,
12 LEDs representing the real time traffic signal,
Microcontroller(RASPBERRY PI ),
Web camera and stepper motor
0-0.5 10
0.5-1 20
1-1.5 30
1.5-2 40
2-2.5 50
2.5-3.5 60
>3.5 90
51 | P a g e
Camera based traffic light control system on raspberry-pi 2016
52 | P a g e
Camera based traffic light control system on raspberry-pi 2016
Chapter Six
6.1. Results
53 | P a g e
Camera based traffic light control system on raspberry-pi 2016
54 | P a g e
Camera based traffic light control system on raspberry-pi 2016
6.2. Discussion
Though there are lots of traffic lights in Ethiopia, all of them are controlled conventional traffic
lights. Not a single of them are working in a different way than operating by the pre-decided fixed
time.
Traffic congestion is now a days an unavoidable phenomena due to the rapid growth of traffic
volume and reduction of road capacity due to different reasons. Due to this traffic congestion
measures should be prepared before it is out of control.
This approach has its own drawback. It’s not complex to see that the very technique that is
built to solve the problem sometimes becomes a source of another problem, traffic conjunction.
How many times have we been sitting at a stoplight for 2, 3 minutes, no cars coming from any other
direction?
Obviously, some studies regarding these lights might be taken place in different domains;
but still the statistical way of handling the problem is the only technique chosen for materialization
at Mesqel Square.
However many approaches should be tried in a City like Addis Ababa. And in view of the
fact that no technique is perfect by itself, using different types of techniques might offer us many
advantages. For instance, the strong side of one technique could give some benefit in suppressing
55 | P a g e
Camera based traffic light control system on raspberry-pi 2016
the shortcoming of the other. And one of these other techniques is controlling the traffic light
system dynamically i.e. taking the real time situation in consideration to allocate the signaling time.
So our project, camera based automatic traffic light control system is based on the real time
situation which considers allocating signaling time based on the real time traffic congestion to solve
the current problem of traffic light controlling system which is basically based on fixed time
allocation.
For this reason, it can be said that the new system has a better opportunity in recognizing the
good feature and in overcoming the limitation of the current system. Moreover, this is the basic
feature that makes it to be an improved system than the conventional traffic light controlling
system.
So, this automatic camera based Traffic Light Controlling System can be one of those
possible options in automating the traffic lights we find in the City.
6.3. Conclusions
The following conclusions can be drawn from the implemented system:
Traffic volume distribution and congestion are similar with the theoretical principle.
Traffic volume has the morning and evening peak period for almost all approaches on
the four intersections or junctions. Similarly, traffic congestion during morning and
evening peak period are congested and during midday it is relatively uncongested.so our
system solves and is real to consider the situation in real time.
Image processing is a method to convert an image into digital form and perform some
operations on it, in order to get an enhanced image or to extract some useful information
56 | P a g e
Camera based traffic light control system on raspberry-pi 2016
from it. Image processing has three phases i.e. Image acquisition (pre-processing),
Image processing (image enhancement and display) and information extraction.
There are different image processing tools and environments like MATLAB and Open
CV. To implement our proposed system we choose Open CV due to
Faster in competition
Low system resources i.e. low RAM usage
Cost free( free software)
The main purpose or objective of this project was to solve the current traffic load problem
and in terms of achieving the specific objective
Interfacing a web camera with and controlling stepper motor using RASPBERRY-PI
was successful.
Image processing using RASPBERRY-PI and appropriate image processing software or
tool for vehicle counting was also successful.
Design a system that decides the timing of the traffic light based on the processed image
and Prototyping the overall system was successful.
6.4. Recommendations
Through the course of conducting this project, it was learned that camera based automatic
Traffic Light Controlling System performs better than the current conventional system. But there
are rooms for improvement to incorporate additional features related with different aspects of the
system. These are based on the shortcomings of this proposed system.
To further enhance the results of this study the following recommendations are formulated:
57 | P a g e
Camera based traffic light control system on raspberry-pi 2016
Further research and study should be conducted to extend all aspects of this research
like taking in to considerations in the case of night shift.
To override the light management of the system in case of arrival of emergency
vehicles little modification of the system must be considered.
58 | P a g e
Camera based traffic light control system on raspberry-pi 2016
References
59 | P a g e
Camera based traffic light control system on raspberry-pi 2016
12. Lei, Leong C. (2003). Traffic signal control system employing universal co-ordinated time
(UTC) of GPS as time base. Retrieved March 28, 2010, from
http://www.computer.org/portal/web/csdl/doi/10.1109/ ICETET.2009.76
13. Levinson, D. (2003). The value of advanced traveler information systems for route choice.
Transportation Research Part C: Emerging Technologies, 11-1:75–87.
14. Findler, N. and Stapp, J. (1992). A distributed approach to optimized control of street traffic
signals. Journal of Transportation Engineering, 118-1:99–110.
15. Tavladakis, K. and Voulgaris, N. C. (1999). Development of an autonomous adaptive traffic
control system. In ESIT ’99 - The European Symposium on Intelligent Techniques.
16. Liu, H. L., Oh, J.-S., and Recker, W. (2002). Adaptive signal control system with on-line
performance measure. In 81st Annual Meeting of the Transportation Research Board.
17. Malik Tubaishat, Yi Shang and Hongchi Shi. Adaptive Traffic Light Control with Wireless
Sensor Networks. Department of Computer Science, University of Missouri – Columbia.
60 | P a g e
Camera based traffic light control system on raspberry-pi 2016
Appendix
import cv2
import time
import sys
import numpy as np
GPIO.setmode(GPIO.BCM)
red_led_A = 15
yellow_led_A = 7
green_led_A = 0
red_led_B = 24
yellow_led_B = 8
green_led_B = 1
red_led_C = 10
yellow_led_C = 23
green_led_C = 4
red_led_D = 9
yellow_led_D = 25
green_led_D = 14
# Configure the GPIO to BCM and set the pins to output mode
GPIO.setmode(GPIO.BCM)
GPIO.setup(red_led_A, GPIO.OUT)
61 | P a g e
Camera based traffic light control system on raspberry-pi 2016
GPIO.setup(yellow_led_A, GPIO.OUT)
GPIO.setup(green_led_A, GPIO.OUT)
GPIO.setup(red_led_B, GPIO.OUT)
GPIO.setup(yellow_led_B, GPIO.OUT)
GPIO.setup(green_led_B, GPIO.OUT)
GPIO.setup(red_led_C, GPIO.OUT)
GPIO.setup(yellow_led_C, GPIO.OUT)
GPIO.setup(green_led_C, GPIO.OUT)
GPIO.setup(red_led_D, GPIO.OUT)
GPIO.setup(yellow_led_D, GPIO.OUT)
GPIO.setup(green_led_D, GPIO.OUT)
GPIO.output(red_led_A, red)
GPIO.output(yellow_led_A, yellow)
GPIO.output(green_led_A, green)
GPIO.output(red_led_B, red)
GPIO.output(yellow_led_B, yellow)
GPIO.output(green_led_B, green)
62 | P a g e
Camera based traffic light control system on raspberry-pi 2016
GPIO.output(red_led_C, red)
GPIO.output(yellow_led_C, yellow)
GPIO.output(green_led_C, green)
GPIO.output(red_led_D, red)
GPIO.output(yellow_led_D, yellow)
GPIO.output(green_led_D, green)
#{
def motor():
controlpin=[17,18,11,22]
GPIO.setup(pin,GPIO.OUT)
GPIO.output(pin,0)
seq=[[1,0,1,0],
[0,1,1,0],
[0,1,0,1],
[1,0,0,1]]
GPIO.output(controlpin[pin],seq[fullstep][pin])
time.sleep(0.05)
#GPIO.cleanup()
#}
63 | P a g e
Camera based traffic light control system on raspberry-pi 2016
#{
def image_capture():
motor()
camera_port = 0
camera = cv2.VideoCapture(camera_port)
def get_image():
retval, im = camera.read()
return im
temp = get_image()
print("Taking image...")
camera_capture = get_image()
file = "/home/pi/realtime.jpg"
cv2.imwrite(file, camera_capture)
del(camera)
#}
#{
return err
m = mse(imageA, imageB)
64 | P a g e
Camera based traffic light control system on raspberry-pi 2016
print m
image_capture()
time.sleep(3)
reference = cv2.imread("reference1.jpg")
realtime = cv2.imread("realtime.jpg")
compare_images(reference1, realtime)
#}
#{
if(0<m<0.5):
time=5
else if (0.5<m<1):
time=10
else if (1<m<1.5):
time=15
else if (1.5<m<2):
time=20
else if (2<m<3):
time=25
else:
65 | P a g e
Camera based traffic light control system on raspberry-pi 2016
time=30
#}
#{
# A's Light Green for time seconds other light Lights Red
trafficState_A(0,0,1)
trafficState_B(1,0,0)
trafficState_C(1,0,0)
trafficState_D(1,0,0)
time.sleep(time)
trafficState_A(0,1,0)
trafficState_B(1,0,0)
trafficState_C(1,0,0)
trafficState_D(1,0,0)
#}
# for lane 2
image_capture()
time.sleep(3)
reference = cv2.imread("reference2.jpg")
realtime = cv2.imread("realtime.jpg")
66 | P a g e
Camera based traffic light control system on raspberry-pi 2016
compare_images(reference2, realtime)
#}
#{
if(0<m<0.5):
time=5
else if (0.5<m<1):
time=10
else if (1<m<1.5):
time=15
else if (1.5<m<2):
time=20
else if (2<m<3):
time=25
else:
time=30
#}
#{
trafficState_A(1,0,0)
trafficState_B(0,0,1)
trafficState_C(1,0,0)
trafficState_D(1,0,0)
67 | P a g e
Camera based traffic light control system on raspberry-pi 2016
time.sleep(time)
trafficState_A(1,0,0)
trafficState_B(0,1,0)
trafficState_C(1,0,0)
trafficState_D(1,0,0)
#}
# for lane 3
image_capture()
time.sleep(3)
reference = cv2.imread("reference3.jpg")
realtime = cv2.imread("realtime.jpg")
compare_images(reference3, realtime)
#}
#{
if(0<m<0.5):
time=5
else if (0.5<m<1):
time=10
else if (1<m<1.5):
time=15
68 | P a g e
Camera based traffic light control system on raspberry-pi 2016
else if (1.5<m<2):
time=20
else if (2<m<3):
time=25
else:
time=30
#}
#{
trafficState_A(1,0,0)
trafficState_B(1,0,0)
trafficState_C(0,0,1)
trafficState_D(1,0,0)
time.sleep(time)
trafficState_A(1,0,0)
trafficState_B(1,0,0)
trafficState_C(0,1,0)
trafficState_D(1,0,0)
#}
# for lane 3
image_capture()
time.sleep(3)
reference = cv2.imread("reference4.jpg")
realtime = cv2.imread("realtime.jpg")
69 | P a g e
Camera based traffic light control system on raspberry-pi 2016
compare_images(reference4, realtime)
#}
#{
if(0<m<0.5):
time=5
else if (0.5<m<1):
time=10
else if (1<m<1.5):
time=15
else if (1.5<m<2):
time=20
else if (2<m<3):
time=25
else:
time=30
#}
#{
trafficState_A(1,0,0)
trafficState_B(1,0,0)
trafficState_C(1,0,0)
70 | P a g e
Camera based traffic light control system on raspberry-pi 2016
trafficState_D(0,0,1)
time.sleep(time)
trafficState_A(1,0,0)
trafficState_B(1,0,0)
trafficState_C(1,0,0)
trafficState_D(0,1,0)
#}
GPIO.cleanup()
71 | P a g e