To create a Python script for real-time vehicle detection and counting, we are going to use the OpenCV library which is a high-performance image processing library. We will also be using the yolov3 model for the detection stage. It's a model trained on the COCO dataset and can detect up to 80 classes of objects.
Installation
Before we begin, ensure that you have OpenCV, Numpy, Imutils, and Dlib installed. You can install these packages using pip.
pip install opencv-python-headless numpy imutils dlib
Also, download the YOLO weight and configuration file.
- yolov3.cfg (https://github.com/pjreddie/darknet/blob/master/cfg/yolov3.cfg)
- yolov3.weights (https://pjreddie.com/media/files/yolov3.weights)
Ask your specific question in Mate AI
In Mate you can connect your project, ask questions about your repository, and use AI Agent to solve programming tasks
Here is a step-by-step guide.
Step 1: Import Required Libraries
import cv2
import numpy as np
import imutils
Step 2: Load YOLO
We will load the yolov3 model.
net = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg")
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
Step 3: Capture Video from Webcam
cap = cv2.VideoCapture(0)
font = cv2.FONT_HERSHEY_PLAIN
starting_time = time.time()
frame_id = 0
Step 4: Inside a Loop, Read Images from the Webcam
while True:
_, frame = cap.read()
frame_id += 1
height, width, channels = frame.shape
# Detecting objects
blob = cv2.dnn.blobFromImage(frame, 0.00392, (320, 320), (0, 0, 0), True, crop=False)
net.setInput(blob)
outs = net.forward(output_layers)
Step 5: Show Information on the Screen
class_ids = []
confidences = []
boxes = []
for out in outs:
for detection in out:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > 0.2:
# Object detected
center_x = int(detection[0] * width)
center_y = int(detection[1] * height)
w = int(detection[2] * width)
h = int(detection[3] * height)
# Rectangle coordinates
x = int(center_x - w / 2)
y = int(center_y - h / 2)
boxes.append([x, y, w, h])
confidences.append(float(confidence))
class_ids.append(class_id)
Step 6: Perform the Object Detection Inside the While Loop
indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.8, 0.3)
# The NMSBoxes function removes all the predicted bounding boxes that have a detection probability less than the threshold.
Step 7: Show the Output in a Window
for i in range(len(boxes)):
if i in indexes:
x, y, w, h = boxes[i]
label = str(classes[class_ids[i]])
confidence = confidences[i]
color = colors[class_ids[i]]
cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)
cv2.putText(frame, label + " " + str(round(confidence, 2)), (x, y + 30), font, 1, color, 3)
cv2.imshow("Image", frame)
Step 8: Break the Loop
key = cv2.waitKey(1)
if key & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
After running this script, a window should open accessing your webcam where the script will detect the vehicles in your area in real time. It will count the number of vehicles as well with vehicle classes taken from the coco datasets.
This is a simplified vehicle detection script. You can further enhance it by filtering by cars and trucks only and also storing the number of vehicles detected. For real world scenarios, you need a more advanced way of counting vehicles over a period.
AI agent for developers
Boost your productivity with Mate:
easily connect your project, generate code, and debug smarter - all powered by AI.
Do you want to solve problems like this faster? Download now for free.