Overview
ThePersonDetector 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__()
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
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
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:
- YOLOv4:
yolov4.weights,yolov4.cfg - YOLOv3:
yolov3.weights,yolov3.cfg - HOG: Falls back to OpenCV’s built-in HOG detector if no YOLO files found
coco.names if available.- Attempts to load YOLOv4 weights and config from
model_dir/ - If YOLOv4 not found, attempts YOLOv3
- If no YOLO files found, falls back to HOG descriptor
- Checks for CUDA GPU availability (uses GPU if available, CPU otherwise)
- Loads COCO class names from
coco.namesor uses defaults - Sets up output layers for YOLO inference
person_detector.py:11-100
Public Methods
detect_persons()
cv2.typing.MatLike
required
OpenCV image matrix (BGR color format). Typically obtained from
Color space: BGR (OpenCV default)
cv2.VideoCapture.read() or cv2.imread().Format: NumPy array with shape (height, width, 3)Color space: BGR (OpenCV default)
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:
self._inference_lock) to ensure only one thread performs inference at a time, as OpenCV DNN and HOG are not thread-safe.
Usage Example:
person_detector.py:228-244
Internal Detection Methods
These methods are called internally bydetect_persons() but can be useful for understanding the detection pipeline.
detect_persons_yolo()
- Creates a 416×416 blob from the input frame
- Runs forward pass through YOLO network
- Filters detections for class_id=0 (person in COCO dataset)
- Applies confidence threshold filtering
- Applies bounding box area threshold filtering
- Applies Non-Maximum Suppression (NMS) with threshold 0.3
- Ensures bounding boxes are within frame boundaries
- Returns list of validated bounding boxes
frame: Input image (not modified - a copy is made for blob creation)
[(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()
- Resizes frame to max 640×480 for better performance
- Runs HOG detectMultiScale with window stride (8, 8)
- Scales detections back to original frame size
- Filters by confidence threshold and area threshold
- Ensures bounding boxes are within frame boundaries
- Returns list of validated bounding boxes
frame: Input image (not modified - a copy is made for processing)
[(x, y, w, h, confidence), ...]
HOG Parameters:
winStride: (8, 8) - Detection window step sizepadding: (32, 32) - Border padding around imagescale: 1.05 - Detection pyramid scale factor
[] 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 fallbackOptional[cv2.HOGDescriptor]
HOG descriptor instance, or
None if using YOLOList[str]
COCO class names loaded from
coco.names fileList[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:- OpenCV compiled with CUDA support
- NVIDIA GPU with CUDA drivers installed
- CUDA toolkit installed
person_detector.py:63-72
Model Fallback Hierarchy
- YOLOv4 (preferred): Best accuracy, requires downloaded weights
- YOLOv3 (fallback): Good accuracy, requires downloaded weights
- HOG (automatic fallback): Built-in OpenCV detector, no downloads needed
Thread Safety Guarantees
ThePersonDetector class is designed for safe concurrent use:
- Multiple threads CAN share a single
PersonDetectorinstance - 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
Complete Usage Example
Implementation Reference
ThePersonDetector class is implemented in person_detector.py (245 lines total):
- Constructor:
person_detector.py:11-100 detect_persons_yolo():person_detector.py:101-173detect_persons_hog():person_detector.py:175-226detect_persons():person_detector.py:228-244