Overview
This function provides flexible labeling capabilities with automatic color assignment, adaptive font scaling, and template-based text generation. It supports multi-line labels and various positioning options relative to bounding boxes.Function Signature
Parameters
Input image to annotate. Must be a valid OpenCV image array in BGR format with shape (H, W, 3) or (H, W).
PixelFlow detections object containing bounding box coordinates and optional attributes (class_name, confidence, class_id, tracker_id).
Label text specification. - None: Auto-generates labels from detection attributes (class_name: confidence) - str: Template string with placeholders (, , , , ) - List[str]: Custom labels for each detection (length should match detections)
Label position relative to bounding box. Options: ‘top_left’, ‘top_center’, ‘top_right’, ‘center_left’, ‘center’, ‘center_right’, ‘bottom_left’, ‘bottom_center’, ‘bottom_right’. Default is ‘top_left’.
OpenCV font scale factor. If None, uses adaptive scaling based on image dimensions. Range: [0.1, 5.0].
Padding in pixels around text inside background rectangle. Range: [0, 50]. Default is 6.
Additional spacing in pixels between lines for multi-line text. Range: [0, 20]. Default is 2.
Background rectangle color in BGR format. If None, uses automatic color based on class_id. Can be tuple (B, G, R) or color string.
Text color in BGR format. Default is white (255, 255, 255).
Returns
Input image with labels drawn directly on it (in-place modification). Returns the same image array that was passed as input.
Examples
Error Handling
This function may raise the following exceptions:
- AssertionError: If image is not a NumPy array.
- AttributeError: If detections object lacks required bbox attribute.
- KeyError: If template string contains invalid placeholders.
- ValueError: If template formatting fails or colors are invalid.
Notes
- Labels are drawn directly on the input image (in-place modification)
- Empty detections list returns the original image unchanged
- Font scale automatically adapts to image size when not specified
- Background colors are automatically assigned based on class_id for visual consistency
- Multi-line text is supported by including newline characters in templates
- Template placeholders are safely handled with fallback values for missing attributes
- Label positioning automatically adjusts to keep labels within image boundaries
- Text baseline and height calculations ensure consistent multi-line spacing
- Optimized for real-time annotation with minimal memory allocation
- Adaptive parameter calculation cached per image size
- Direct OpenCV drawing operations for maximum performance
- Template formatting is cached per detection to avoid repeated processing