OpenCV Tutorial
Image Processing
Feature Detection and Description
Drawing Functions
Video Processing
Applications and Projects
Detecting vehicles in a video frame is a common application in computer vision, especially for surveillance, traffic monitoring, and autonomous vehicles. Here, we'll use OpenCV's pre-trained Haar cascades to detect vehicles in a video frame. Although this method is not as robust as deep learning techniques, it's simpler and faster.
pip install opencv-python
import cv2
car_cascade = cv2.CascadeClassifier('path_to_vehicle_cascade.xml')
# Open video video = cv2.VideoCapture('path_to_video.mp4') while True: ret, frame = video.read() if not ret: break # Convert frame to grayscale gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Detect cars cars = car_cascade.detectMultiScale(gray, 1.1, 3) # Draw bounding box around cars for (x, y, w, h) in cars: cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2) # Display frame cv2.imshow('Car Detection', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break video.release() cv2.destroyAllWindows()
Robustness: Haar cascades are not the most robust technique for car detection, especially in complex scenarios. It might have trouble detecting cars from different angles or in various lighting conditions.
False Positives/Negatives: Depending on the cascade quality and the detection parameters, you might experience false positives (detecting non-car objects as cars) or false negatives (missing some cars).
Deep Learning: For robust vehicle detection in complex scenarios, consider using deep learning techniques. Popular architectures like Single Shot MultiBox Detector (SSD), You Only Look Once (YOLO), and Faster R-CNN have been used effectively for vehicle detection tasks.
Training: If you're unable to find a satisfactory pre-trained cascade for car detection, you can consider training one using positive and negative samples. OpenCV provides tools for training Haar cascades, though this can be a time-consuming process.
Remember, the approach presented here is basic and might not work perfectly in all scenarios. However, it serves as an introduction to the concept of object detection using OpenCV.
Vehicle detection in video using OpenCV Python:
import cv2 # Load pre-trained vehicle detection model cascade_path = 'haarcascade_car.xml' car_cascade = cv2.CascadeClassifier(cascade_path) # Read video stream cap = cv2.VideoCapture('traffic_video.mp4') while True: ret, frame = cap.read() # Convert to grayscale for Haarcascade gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Detect vehicles cars = car_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5) # Draw bounding boxes around detected vehicles for (x, y, w, h) in cars: cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) # Display the resulting frame cv2.imshow('Vehicle Detection', frame) if cv2.waitKey(25) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()