Certainly! To modify the code so that it only detects people within the ROI and displays the count, we'll filter by class ID for people, which is typically 0 for most pre-trained models like COCO. We'll display the count of people on the top of the frame.
Here's the updated code:
import cv2
import torch
from yolov5 import YOLOv5
def object_detection_camera_with_roi(source=0, weights='yolov5s.pt', conf_thres=0.25, person_class_id=0):
# Load the YOLOv5 model
model = YOLOv5(weights, autoshape=True)
model.conf = conf_thres
model.classes = [person_class_id] # Set to None if you want to detect all classes
model.eval()
# Open the camera source
cap = cv2.VideoCapture(source)
if not cap.isOpened():
print("Error: Could not open video source.")
return
try:
with torch.no_grad():
while True:
ret, frame = cap.read()
if not ret:
print("Error: Failed to read frame from camera source.")
break
# Define ROI size and position (centered)
h, w = frame.shape[:2]
roi_size = min(w, h) // 3
x1, y1 = w // 2 - roi_size // 2, h // 2 - roi_size // 2
x2, y2 = x1 + roi_size, y1 + roi_size
# Extract the ROI from the frame
roi = frame[y1:y2, x1:x2]
# Inference on the ROI
results = model(roi)
# Draw the ROI rectangle on the original frame
cv2.rectangle(frame, (x1, y1), (x2, y2), (255, 0, 0), 2)
# Plot detections on the original frame and count the number of people
labels, cords = results.xyxyn[0][:, -1], results.xyxyn[0][:, :-1]
people_count = 0
for row in cords:
if row[4] >= conf_thres: # Only plot detections above the threshold
people_count += 1
roi_x1, roi_y1, roi_x2, roi_y2 = (row[0:4] * torch.tensor(roi.shape)[[1, 0, 1, 0]]).int().numpy()
cv2.rectangle(frame, (roi_x1 + x1, roi_y1 + y1), (roi_x2 + x1, roi_y2 + y1), (0, 255, 0), 2)
cv2.putText(frame, f'Person {row[4]:.2f}', (roi_x1 + x1, roi_y1 + y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
# Display the number of people detected on the top of the frame
cv2.putText(frame, f'People detected: {people_count}', (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
# Display
cv2.imshow('YOLOv5 Object Detection with ROI - Camera', frame)
# Break loop with 'q'
if cv2.waitKey(1) == ord('q'):
break
finally:
cap.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
# Start object detection from default camera source (usually 0)
object_detection_camera_with_roi(source=0, weights='yolov5s.pt', conf_thres=0.25)
In this code, person_class_id is assumed to be 0, which is the class index for a person in COCO dataset that YOLO models are commonly trained on. The script will now filter detections for this class only, count the number of people detected, and display the count in the frame.
Make sure to match the weights path with the actual location of the YOLOv5 weights file on your system.
Remember to adjust the class ID if you are using a different dataset or if the index of the "person" class is different. The provided code is based on the pre-trained models on the COCO dataset.