Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is a Vehicle Detection System ?
3.
How does a Vehicle Detection System work ?
3.1.
Frame Differencing
3.2.
Image Thresholding
3.3.
Finding Contours
4.
Project Code - Vehicle Detection
5.
Frequently Asked Questions
5.1.
What is OpenCV?
5.2.
What are the applications of vehicle detection in real world projects?
5.3.
What is an image frame ?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Vehicle Detection using OpenCV

Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Significant damage to finance and infrastructure is caused due to road accidents, not to mention the loss of human lives. Bosch's study highlights a setback of approximately $15 billion to $38 billion in the year of 2019 due to road accidents. However, this issue can be handled by tracking the movements of vehicles with the advanced implementations of object detection systems. Vehicle detection systems can keep track of individual vehicles and overcome the challenges of the inability to locate them in images collected from a moving platform.

What is a Vehicle Detection System ?

A vehicle detection system is an application of an object detection system in which the primary focus is on tracking the vehicle using its coordinates in the images or videos. This system can be implemented using various tools, and in the following section, we will implement a project using the OpenCV library.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

How does a Vehicle Detection System work ?

The objective of such a system is to detect the vehicle's coordinates and focus on that particular vehicle in the video. For example, consider the following image frame in which a bounding box is created which surrounds the vehicle and detects the coordinates of the car.

Source: link

Various methods can be used to assess the changes in the movement of a vehicle, so let us look at the following methods.

Frame Differencing

We know that a video is essentially a collection of image frames put together and played in a continuous stream. Therefore, it is noticeable that the vehicle changes coordinates in each successive frame and, hence, its location. Also, it can be noted that only the pixels representing the vehicle will undergo changes in these consecutive frames. Thus, the frame differencing method aims to notice the changes in the pixel and location of the moving vehicle.

Image Thresholding

This method works by assigning one of the two values based on a threshold to the pixels in a grayscale image. If the value of a pixel exceeds a threshold value, then it is assigned a particular value; else, it is given another value. The objective is to remove unwanted highlighted areas by obtaining a resultant binary image.

Finding Contours

In this method, the shape of the vehicle is identified by setting boundaries around regions of interest (the vehicle) in the image frames. In the next steps, we can get the coordinates of these contours in the image frame and locate the vehicle.

Utilizing these methods selectively, we can easily locate the movements of vehicles in the video or image frame and detect them.

Project Code - Vehicle Detection

Let us implement a project to detect vehicles in a video. 

import cv2
import time
import numpy as np

 

# Create the body classifier
car_classifier = cv2.CascadeClassifier('haarcascade_car.xml')

 

# Initiate video capture for video file
video_cap = cv2.VideoCapture('C:/Users/vidhu/Desktop/Project/cars.avi')

 

# Loop once video is successfully loaded
while video_cap.isOpened():
    
    time.sleep(.05)
    # Read first frame
    ret, frame = video_cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
  
    # Pass frame to our car classifier
    cars = car_classifier.detectMultiScale(gray, 1.4, 2)
    
    # Extract bounding boxes for any bodies identified
    for (x,y,w,h) in cars:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 255), 2)
        cv2.imshow('Cars', frame)

    if cv2.waitKey(1) ==13: #13 is the Enter Key
        break
        
video_cap.release()
cv2.destroyAllWindows()

 

XML file used here can be accessed via: Link

The result of the code detecting the vehicles is :

Source: link

Also read, Sampling and Quantization

Frequently Asked Questions

What is OpenCV?

Open Source Computer Vision (OpenCV) Library is a library of Python consisting of programming functions to implement real-time computer vision and its applications.

What are the applications of vehicle detection in real world projects?

Some real-world projects implementing vehicle detection in the Intelligent Transportation System (ITS) are Vehicle speed measurement, traffic flow prediction, and identification of traffic accidents.

What is an image frame ?

An image frame represents elements in an image with respect to the placement of the subject (here, vehicle) to other objects (here, surrounding environment).

Conclusion

In this blog, we discussed the significance of the Vehicle Detection System along with its applications in the real world. We have understood how the vehicles are detected using Computer Vision and what methods are used to locate a particular vehicle's movements in a frame. Additionally, we have implemented the code for a project on vehicle detection using OpenCV.

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem DesignMachine learning and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But if you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc; you must look at the problems, interview experiences, and interview bundle for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!!

Previous article
Invisible Cloak using OpenCV
Next article
Face Detection
Live masterclass