> ## Documentation Index
> Fetch the complete documentation index at: https://docs.datamarkin.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Label

> Draw text labels on detected objects with positioning, templates, and multi-line support.

## 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

```python theme={null}
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 ({class_name}, {confidence}, {class_id}, {tracker_id}, {bbox}) - 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

```python Example theme={null}
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}
```

```python Example theme={null}
labeled_image = pf.annotators.label(image, detections, multi_template,
```

```python Example theme={null}

# Custom label list with specific positioning
custom_labels = ["Primary Target", "Secondary", "Background"]
labeled_image = pf.annotators.label(image, detections[:3], custom_labels,
```

## Error Handling

> [!WARNING]
>
> 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

> [!NOTE]
>
> * 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


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.