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

label(
    image: np.ndarray,
    detections: Detections,
    texts: Optional[Union[str, List[str]]] = None,
    position: str = 'top_left',
    font_scale: Optional[float] = None,
    padding: int = 6,
    line_spacing: int = 2,
    bg_color: Optional[Union[tuple, str]] = None,
    text_color: tuple = default
) -> np.ndarray

Parameters

image
np.ndarray
required
Input image to annotate. Must be a valid OpenCV image array in BGR format with shape (H, W, 3) or (H, W).
detections
Detections
required
PixelFlow detections object containing bounding box coordinates and optional attributes (class_name, confidence, class_id, tracker_id).
texts
Optional[Union[str, List[str]]]
default:"None"
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)
position
str
default:"'top_left'"
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’.
font_scale
Optional[float]
default:"None"
OpenCV font scale factor. If None, uses adaptive scaling based on image dimensions. Range: [0.1, 5.0].
padding
int
default:"6"
Padding in pixels around text inside background rectangle. Range: [0, 50]. Default is 6.
line_spacing
int
default:"2"
Additional spacing in pixels between lines for multi-line text. Range: [0, 20]. Default is 2.
bg_color
Optional[Union[tuple, str]]
default:"None"
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
tuple
default:"default"
Text color in BGR format. Default is white (255, 255, 255).

Returns

result
np.ndarray
Input image with labels drawn directly on it (in-place modification). Returns the same image array that was passed as input.

Examples

import cv2
import pixelflow as pf
from ultralytics import YOLO

# Load image and run detection
image = cv2.imread("people.jpg")
model = YOLO("yolo11n.pt")
outputs = model.predict(image)
detections = pf.results.from_ultralytics(outputs)

# Basic auto-generated labels
labeled_image = pf.annotators.label(image, detections)

# Custom template with confidence percentage
template = "{class_name}: {confidence:.1%}"
labeled_image = pf.annotators.label(image, detections, template, position='top_center')

# Multi-line labels with tracking info
multi_template = """{class_name}

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