Open In App

Vehicle detection using OpenCV Python

Last Updated : 21 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Object Detection means identifying the objects in a video or image. In this article, we will learn how to detect vehicles using the Haar Cascade classifier and OpenCV. We will implement the vehicle detection on an image and as a result, we will get a video in which vehicles will be detected and it will be represented by a rectangular frame around it.

Why Vehicle Detection?

  • The startling losses both in human lives and finance caused by vehicle accidents.
  • Detecting vehicles in images acquired from a moving platform is a challenging problem.

Installing the requirements:

  • Install Python 3.x version, numpy, and OpenCV 2.4.x version. Check if your Windows either 32-bit or 64-bit is compatible and install accordingly.
  • Make sure to install numpy first and then install opencv.
  • Put the haar cascade file in the same folder. Download it from here.

Importing the Required Libraries

We are going to use OpenCV, so let’s import it.

Python3




# import libraries of python OpenCV 
import cv2


Now, to capture a video, we need to create a VideoCapture() object. So let’s create it. Also let’s load our trained XML classifier, i.e. Haar Cascade classifier that contains the features to identify the objects.

Python3




haar_cascade = 'cars.xml'
video = 'video.avi'
      
cap = cv2.VideoCapture(video)
car_cascade = cv2.CascadeClassifier(haar_cascade)


Now, as we are working with the video, and a video has many frames, hence we will run a while loop. In the loop, we will first read the frames from the video, and convert those frames to a grayscale. Then we will use the haar cascade classifier to detect the vehicle.

Python3




# reads frames from a video
ret, frames = cap.read()
        
# convert frames to gray scale 
gray = cv2.cvtColor(frames, cv2.COLOR_BGR2GRAY)
        
# Detects cars of different sizes in the input image
cars = car_cascade.detectMultiScale(gray, 1.1, 1)


After this step, we will use the OpenCV to draw rectangles around the vehicles. For this, we will use the coordinates that we got while using the haar cascade. And in the end, we will display the frames using cv2.imshow().

Python3




# To draw a rectangle in each cars
for (x,y,w,h) in cars:
  cv2.rectangle(frames,(x,y),(x+w,y+h),(0,0,255),2)
    
# Display frames in a window 
cv2.imshow('video', frames)


Let’s combine all the above steps:

Python3




# loop runs if capturing has been initialized.
while True:
    # reads frames from a video
    ret, frames = cap.read()
        
    # convert to gray scale of each frames
    gray = cv2.cvtColor(frames, cv2.COLOR_BGR2GRAY)
        
    
    # Detects cars of different sizes in the input image
    cars = car_cascade.detectMultiScale(gray, 1.1, 1)
        
    # To draw a rectangle in each cars
    for (x,y,w,h) in cars:
        cv2.rectangle(frames,(x,y),(x+w,y+h),(0,0,255),2)
    
    # Display frames in a window 
    cv2.imshow('video', frames)
        
    # Wait for Esc key to stop
    if cv2.waitKey(33) == 27:
        break
    
# De-allocate any associated memory usage
cv2.destroyAllWindows()


This is how the output will look

car-detection

Vehicle Detection

More articles on detections using Haar Cascade – Face Detection Basics



Previous Article
Next Article

Similar Reads

Real-Time Edge Detection using OpenCV in Python | Canny edge detection method
Edge detection is one of the fundamental image-processing tasks used in various Computer Vision tasks to identify the boundary or sharp changes in the pixel intensity. It plays a crucial role in object detection, image segmentation and feature extraction from the image. In Real-time edge detection, the image frame coming from a live webcam or video
5 min read
Python | Corner detection with Harris Corner Detection method using OpenCV
Harris Corner detection algorithm was developed to identify the internal corners of an image. The corners of an image are basically identified as the regions in which there are variations in large intensity of the gradient in all possible dimensions and directions. Corners extracted can be a part of the image features, which can be matched with fea
2 min read
Python | Corner Detection with Shi-Tomasi Corner Detection Method using OpenCV
What is a Corner? A corner can be interpreted as the junction of two edges (where an edge is a sudden change in image brightness). Shi-Tomasi Corner Detection - Shi-Tomasi Corner Detection was published by J.Shi and C.Tomasi in their paper 'Good Features to Track'. Here the basic intuition is that corners can be detected by looking for significant
3 min read
Face detection using Cascade Classifier using OpenCV-Python
In this article, we are going to see how to detect faces using a cascade classifier in OpenCV Python. Face detection has much significance in different fields of today's world. It is a significant step in several applications, face recognition (also used as biometrics), photography (for auto-focus on the face), face analysis (age, gender, emotion r
4 min read
Face Detection using Python and OpenCV with webcam
OpenCV is a Library which is used to carry out image processing using programming languages like python. This project utilizes OpenCV Library to make a Real-Time Face Detection using your webcam as a primary camera.Following are the requirements for it:- Python 2.7OpenCVNumpyHaar Cascade Frontal face classifiers Approach/Algorithms used: This proje
4 min read
Python | Smile detection using OpenCV
Emotion detectors are used in many industries, one being the media industry where it is important for the companies to determine the public reaction to their products. In this article, we are going to build a smile detector using OpenCV which takes in live feed from webcam. The smile/happiness detector that we are going to implement would be a raw
3 min read
Circle Detection using OpenCV | Python
Circle detection finds a variety of uses in biomedical applications, ranging from iris detection to white blood cell segmentation. The technique followed is similar to the one used to detect lines, as discussed in this article. Basics of Circle Detection A circle can be described by the following equation: To detect circles, we may fix a point (x,
3 min read
White and black dot detection using OpenCV | Python
Image processing using Python is one of the hottest topics in today's world. But image processing is a bit complex and beginners get bored in their first approach. So in this article, we have a very basic image processing python program to count black dots in white surface and white dots in the black surface using OpenCV functions (cv2.imread, cv2.
4 min read
Pedestrian Detection using OpenCV-Python
OpenCV is an open-source library, which is aimed at real-time computer vision. This library is developed by Intel and is cross-platform - it can support Python, C++, Java, etc. Computer Vision is a cutting edge field of Computer Science that aims to enable computers to understand what is being seen in an image. OpenCV is one of the most widely used
3 min read
Multiple Color Detection in Real-Time using Python-OpenCV
For a robot to visualize the environment, along with the object detection, detection of its color in real-time is also very important. Why this is important? : Some Real-world Applications In self-driving car, to detect the traffic signals. Multiple color detection is used in some industrial robots, to performing pick-and-place task in separating d
4 min read
Article Tags :