Skip to main content

Overview

The PersonDetector class provides thread-safe person detection using YOLO (YOLOv4/YOLOv3) with automatic fallback to OpenCV’s HOG descriptor. All inference operations are protected by an internal lock to ensure thread safety when processing multiple streams concurrently.

Class Definition

Constructor

__init__()

Initialize the person detector and load the detection model.
float
default:"0.5"
Minimum detection confidence score (0.0 to 1.0). Detections below this threshold are filtered out.Range: 0.0 - 1.0
Recommended: 0.5 for balanced accuracy, 0.7 for fewer false positives
int
default:"1000"
Minimum bounding box area in pixels (width × height). Smaller detections are filtered out to reduce false positives from distant or partial detections.Units: Pixels squared
Example: A 50×20 pixel box (1000 px²) passes the default threshold
str
default:"model"
Directory containing YOLO model files. The detector attempts to load files in this order:
  1. YOLOv4: yolov4.weights, yolov4.cfg
  2. YOLOv3: yolov3.weights, yolov3.cfg
  3. HOG: Falls back to OpenCV’s built-in HOG detector if no YOLO files found
Also loads class labels from coco.names if available.
Model Loading Process:
  1. Attempts to load YOLOv4 weights and config from model_dir/
  2. If YOLOv4 not found, attempts YOLOv3
  3. If no YOLO files found, falls back to HOG descriptor
  4. Checks for CUDA GPU availability (uses GPU if available, CPU otherwise)
  5. Loads COCO class names from coco.names or uses defaults
  6. Sets up output layers for YOLO inference
Console Output:
Implementation: person_detector.py:11-100

Public Methods

detect_persons()

Detect persons in the provided frame using the loaded model. This is the primary method for person detection.
cv2.typing.MatLike
required
OpenCV image matrix (BGR color format). Typically obtained from cv2.VideoCapture.read() or cv2.imread().Format: NumPy array with shape (height, width, 3)
Color space: BGR (OpenCV default)
Returns: Tuple[bool, int, List[Tuple[int, int, int, int, float]]]
bool
Whether at least one person was detected in the frame.
int
Total number of persons detected (after filtering by confidence and area thresholds).
List[Tuple[int, int, int, int, float]]
List of bounding boxes for detected persons. Each tuple contains:
Thread Safety: This method is thread-safe. It acquires an internal lock (self._inference_lock) to ensure only one thread performs inference at a time, as OpenCV DNN and HOG are not thread-safe. Usage Example:
Multi-threading Example:
Implementation: person_detector.py:228-244

Internal Detection Methods

These methods are called internally by detect_persons() but can be useful for understanding the detection pipeline.

detect_persons_yolo()

Internal method that performs YOLO-based person detection. Process:
  1. Creates a 416×416 blob from the input frame
  2. Runs forward pass through YOLO network
  3. Filters detections for class_id=0 (person in COCO dataset)
  4. Applies confidence threshold filtering
  5. Applies bounding box area threshold filtering
  6. Applies Non-Maximum Suppression (NMS) with threshold 0.3
  7. Ensures bounding boxes are within frame boundaries
  8. Returns list of validated bounding boxes
Parameters:
  • frame: Input image (not modified - a copy is made for blob creation)
Returns: List of bounding boxes [(x, y, w, h, confidence), ...] NMS Threshold: 0.3 (line 156) - More strict than typical values to reduce overlapping detections Error Handling: Returns empty list [] if any exception occurs during detection Implementation: person_detector.py:101-173

detect_persons_hog()

Internal method that performs HOG-based person detection (fallback when YOLO unavailable). Process:
  1. Resizes frame to max 640×480 for better performance
  2. Runs HOG detectMultiScale with window stride (8, 8)
  3. Scales detections back to original frame size
  4. Filters by confidence threshold and area threshold
  5. Ensures bounding boxes are within frame boundaries
  6. Returns list of validated bounding boxes
Parameters:
  • frame: Input image (not modified - a copy is made for processing)
Returns: List of bounding boxes [(x, y, w, h, confidence), ...] HOG Parameters:
  • winStride: (8, 8) - Detection window step size
  • padding: (32, 32) - Border padding around image
  • scale: 1.05 - Detection pyramid scale factor
Error Handling: Returns empty list [] if any exception occurs during detection Implementation: person_detector.py:175-226

Instance Attributes

These attributes are set during initialization and should be treated as read-only:
float
Minimum confidence score for detections (from constructor parameter)
int
Minimum bounding box area in pixels (from constructor parameter)
str
Path to model directory (from constructor parameter)
Optional[cv2.dnn.Net]
Loaded YOLO neural network, or None if using HOG fallback
Optional[cv2.HOGDescriptor]
HOG descriptor instance, or None if using YOLO
List[str]
COCO class names loaded from coco.names file
List[str]
All layer names in the YOLO network (empty if using HOG)
List[str]
YOLO output layer names for inference (empty if using HOG)
threading.Lock
Internal lock ensuring thread-safe inference. Do not access directly.

GPU Acceleration

The detector automatically uses NVIDIA GPU via CUDA if available:
Requirements for GPU acceleration:
  • OpenCV compiled with CUDA support
  • NVIDIA GPU with CUDA drivers installed
  • CUDA toolkit installed
Implementation: person_detector.py:63-72

Model Fallback Hierarchy

  1. YOLOv4 (preferred): Best accuracy, requires downloaded weights
  2. YOLOv3 (fallback): Good accuracy, requires downloaded weights
  3. HOG (automatic fallback): Built-in OpenCV detector, no downloads needed
Model Download Links: Console Output for HOG Fallback:

Thread Safety Guarantees

The PersonDetector class is designed for safe concurrent use:
  • Multiple threads CAN share a single PersonDetector instance
  • Inference is serialized via self._inference_lock (line 235)
  • OpenCV DNN and HOG are not thread-safe, so the lock is essential
  • Performance: Multiple threads will queue inference requests sequentially
Why thread-safety matters:

Complete Usage Example

Implementation Reference

The PersonDetector class is implemented in person_detector.py (245 lines total):
  • Constructor: person_detector.py:11-100
  • detect_persons_yolo(): person_detector.py:101-173
  • detect_persons_hog(): person_detector.py:175-226
  • detect_persons(): person_detector.py:228-244