To perform object detection using YOLOv5 for detecting people only within a certain ROI (Region of Interest), we can harness the robustness of YOLOv5 which can be cloned from Ultralytics's GitHub repository and leverage multiprocessing for efficiency.
Here's a Python code snippet that demonstrates how this can be done. Please note that the multiprocessing part focuses on handling the video stream, while the inference is done without multiprocessing. Extending multiprocessing to inference would require a more complex setup, which typically involves managing shared states or inter-process communication.
First, you need to set up the YOLOv5 repository and weights if you haven't already:
git clone https://github.com/ultralytics/yolov5
cd yolov5
pip install -r requirements.txt
# Download the weights for YOLOv5 model (e.g., yolov5s.pt)
Next, use this Python script assuming you are running the script from the yolov5 repository root:
import cv2
import torch
import multiprocessing
from multiprocessing import Process, Queue
# Function to perform detection
def detect_people(q, model, device, roi):
while True:
# Get frame from the queue
frame = q.get()
# Only proceed if the queue is not empty
if frame is not None:
# Prepare frame
frame = frame[..., ::-1] # BGR to RGB
results = model(frame)
# Apply ROI filtering
detections = results.xyxy[0].cpu().numpy() # Detections
count = 0
for *xyxy, conf, cls in detections:
if cls == 0: # Class 0 corresponds to 'person' in COCO dataset
x1, y1, x2, y2 = map(int, xyxy)
if roi[0] < x1 and x2 < roi[2] and roi[1] < y1 and y2 < roi[3]:
count += 1
cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
# Display the number of people detected within the ROI
cv2.putText(frame, f'People detected: {count}', (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
# Display the frame
cv2.imshow('YOLOv5 Detection', frame[..., ::-1]) # RGB to BGR for OpenCV
if cv2.waitKey(1) == ord('q'): # Press 'q' to quit
break
# Function to handle the camera input
def camera_input(q, camera_source):
cap = cv2.VideoCapture(camera_source)
while True:
ret, frame = cap.read()
if not ret:
break
q.put(frame)
cap.release()
if __name__ == '__main__':
# Camera source
camera_source = 0 # Use 0 for webcam, or 'rtsp://...' for an RTSP stream
# Load model
model = torch.hub.load('ultralytics/yolov5', 'yolov5s')
# Define Region of Interest (ROI) as a square in the center of the frame
cap = cv2.VideoCapture(camera_source)
ret, frame = cap.read()
cap.release()
h, w, _ = frame.shape
side_length = min(w, h) // 3 # Define the side length of the ROI square
roi = [(w - side_length) // 2, (h - side_length) // 2, (w + side_length) // 2, (h + side_length) // 2]
# Create Queue
q = Queue(maxsize=2) # Set max size to avoid filling up RAM
# Create and start processes
p1 = Process(target=camera_input, args=(q, camera_source))
p2 = Process(target=detect_people, args=(q, model, torch.device('cuda' if torch.cuda.is_available() else 'cpu'), roi))
p1.start()
p2.start()
p1.join()
p2.join()
cv2.destroyAllWindows()
This code will open a video stream from the camera, do real-time object detection only for people within the specified ROI, and display the number of people detected.
This example does not split inference across multiple processes because doing so requires careful management of shared memory between processes and may not always lead to increased performance due to Python's GIL (Global Interpreter Lock) and the complexity of handling neural network model states across processes. It is usually more efficient to run inference in a single process and use multiprocessing on I/O bound operations, such as reading frames from a video stream, as demonstrated above.