Overview
In this tutorial, we will learn how to detect a vehicl from a video using the Haar Cascades classifier. For the well-known tasks, the classifiers / detectors already exists, for example: detecting things like faces, cars, smiles, eyes and license plates.
Installing the modules
To install the OpenCV module and some other associated dependencies, we can use the pip command:
pip install opencv-python
Download the Haar Cascades
- Follow the URL:
https://github.com/AdityaPai2398/Vehicle-And-Pedestrian-Detection-Using-Haar-Cascades/tree/master/Main%20Project/Main%20Project/Car%20Detection - Click on cars.xml
- Click on Raw and then press Ctrl + S. This will help you save the Haar Cascade file for vehicle detection.
The Code
import cv2
car_cascade = cv2.CascadeClassifier("haarcascades_car.xml")
def detect_cars(frame):
cars = car_cascade.detectMultiScale(frame, 1.15, 4)
for (x, y, w, h) in cars:
cv2.rectangle(frame, (x, y), (x+w, y+h), color=(155, 155, 0), thickness=2)
return frame
def Simulator():
car_video = cv2.VideoCapture("video.mp4")
while car_video.isOpened():
ret, frame = car_video.read()
control_key = cv2.waitKey(1)
if ret:
cars_frame = detect_cars(frame)
cv2.imshow('Frame', cars_frame)
else:
break
if control_key == ord('q'):
break
if __name__ == '__main__':
Simulator()