The Wayback Machine - https://web.archive.org/web/20240930233936/https://www.geeksforgeeks.org/opencv-python-program-vehicle-detection-video-frame/
Open In App

Vehicle detection using OpenCV Python

Last Updated : 26 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

Python
# 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.

Python
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.

Python
# 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().

Python
# 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:

Python
# 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
OpenCV - Facial Landmarks and Face Detection using dlib and OpenCV
Content has been removed on Author's request.
1 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
Gun Detection using Python-OpenCV
Gun Detection using Object Detection is a helpful tool to have in your repository. It forms the backbone of many fantastic industrial applications. We can use this project for real threat detection in companies or organizations. Prerequisites: Python OpenCV OpenCV(Open Source Computer Vision Library) is a highly optimized library with a focus on Re
4 min read
Contour Detection with Custom Seeds using Python - OpenCV
This article discusses how we can dynamically detect contours by clicking on the Image and assign different colors to different parts of the image. Contours are a very useful tool for shape analysis and object detection and recognition. This program uses OpenCV, Numpy, and Matplotlib libraries. It also uses a built-in OpenCV Watershed algorithm to
3 min read
Automating Scrolling using Python-Opencv by Color Detection
Prerequisites: OpencvPyAutoGUI It is possible to perform actions without actually giving any input through touchpad or mouse. This article discusses how this can be done using opencv module. Here we will use color detection to scroll screen. When a certain color is detected by the program during execution the screen starts to scroll on its own. App
2 min read
Face and Hand Landmarks Detection using Python - Mediapipe, OpenCV
In this article, we will use mediapipe python library to detect face and hand landmarks. We will be using a Holistic model from mediapipe solutions to detect all the face and hand landmarks. We will be also seeing how we can access different landmarks of the face and hands which can be used for different computer vision applications such as sign la
4 min read
Detection of a specific color(blue here) using OpenCV with Python
The following code in python uses OpenCV library which is employed for image processing techniques. The program allows the detection of a specific color in a live stream video content. A video is composed of infinite frames at different time instants. We will detect the colour of every frame one by one. The code will only compile in linux environme
4 min read
Project Idea | Real Time Vehicle Tracking
Project Title: Real Time Vehicle Tracking Introduction: This project aims to solve the problem of tracking and accountability of vehicles by providing a software platform. This project would serve as an important step to help in Vehicle tracking, component monitoring, vehicle analysis and fleet management. An efficient vehicle tracking system is im
6 min read
Real time object color detection using OpenCV
In this article, we will discuss how to detect a monochromatic colour object using python and OpenCV. Monochromatic color means light of a single wavelength. We will use the video, captured using a webcam as input and try to detect objects of a single color, especially Blue. But you can detect any color if you set the range properly, we'll discuss
4 min read
Blob Detection Using OpenCV
Blob detection is a basic method in computer vision used to locate areas of interest in a picture. These "blobs" frequently depict elements or items that have similar characteristics, like color, texture, or intensity. In this post, we explore the realm of blob identification with OpenCV, an effective computer vision toolkit. In this article, we lo
5 min read
Text Detection and Extraction using OpenCV and OCR
OpenCV (Open source computer vision) is a library of programming functions mainly aimed at real-time computer vision. OpenCV in python helps to process an image and apply various functions like resizing image, pixel manipulations, object detection, etc. In this article, we will learn how to use contours to detect the text in an image and save it to
5 min read
Age Detection using Deep Learning in OpenCV
In this tutorial, we are going to see the entire process of creating an Age predictor and Gender classifier project using OpenCV. Age Detection Our goal here is to create a program that will predict the gender and age of the person using an image.  But predicting age might not be as simple as you think, why? You might be thinking that age predictio
5 min read
Feature detection and matching with OpenCV-Python
In this article, we are going to see about feature detection in computer vision with OpenCV in Python. Feature detection is the process of checking the important features of the image in this case features of the image can be edges, corners, ridges, and blobs in the images. In OpenCV, there are a number of methods to detect the features of the imag
5 min read
Python OpenCV - Roberts Edge Detection
Edge detection refers to a set of mathematical techniques for recognizing points in a digital image where the image brightness abruptly changes or, more formally, where there are discontinuities. The sharp fluctuations in image brightness are usually grouped into a collection of curved line segments called edges. Roberts Edge DetectionThe Roberts o
3 min read
Eye blink detection with OpenCV, Python, and dlib
In this article, we are going to see how to detect eye blink using OpenCV, Python, and dlib. This is a fairly simple task and it requires you to have a basic understanding of OpenCV and how to implement face landmark detection programs using OpenCV and dlib, since we'll be using that as the base for today's project. Stepwise ImplementationStep 1: I
6 min read
Python OpenCV - Drowsiness Detection
The number of fatalities on the road due to drowsiness is very high. Thus python allows the model of deep learning algorithm via including the use of OpenCV. Drowsiness Detection is the detection of a person to check whether the person is feeling sleepy while performing a significant task. This detection has many applications in medical and safety
9 min read
Opencv Python program for Face Detection
The objective of the program given is to detect object of interest(face) in real time and to keep tracking of the same object.This is a simple example of how to detect face in Python. You can try to use training samples of any other object of your choice to be detected by training the classifier on required objects. Here is the steps to download th
2 min read
Automatic Document Scanner using OpenCV (OpenCV Document Scanner)
An automatic document scanner using OpenCV is a computer vision application that automatically detects and extracts documents from images. This type of scanner can be useful in various scenarios, such as digitizing paper documents, processing scanned documents, or automating document recognition tasks. In this article, we will see how we can build
6 min read
OpenCV C++ Program for coin detection
The following is the explanation to the C++ code for coin detection in C++ using the tool OpenCV. Things to know: The code will only compile in Linux environment. To run in windows, please use the file: 'coin.o' and run it in cmd. However if it does not run(problem in system architecture) then compile it in windows by making suitable and obvious ch
4 min read
Region Proposal Object Detection with OpenCV, Keras, and TensorFlow
In this article, we'll learn how to implement Region proposal object detection with OpenCV, Keras and TensorFlow. Install all the dependencies Use the pip command for installing all the dependencies pip install tensorflow keras imutils pip install opencv-contrib-python Note: Make sure about installing the above OpenCV package otherwise you might fa
9 min read
OpenCV Selective Search For Object Detection
OpenCV is a Python library that is used to study images and video streams. It basically extracts the pixels from the images and videos (stream of image) so as to study the objects and thus obtain what they contain. It contains low-level image processing and high-level algorithms for object detection, feature matching etc. In this article, we will d
14 min read
Article Tags :