# medipipe

Python API: `depthai_nodes.node.parsers.utils.medipipe`

mediapipe.py.

Description: This script contains utility functions for decoding the output of the MediaPipe hand tracking model.

This script contains code that is based on or directly taken from a public GitHub repository:
[https://github.com/geaxgx/depthai_hand_tracker](https://github.com/geaxgx/depthai_hand_tracker)

Original code author(s): geaxgx

License: MIT License

Copyright (c) [2021] [geax]

## Classes

| Name | Description |
| --- | --- |
| [`HandRegion`](https://docs.luxonis.com/software-v3/ai-inference/inference/depthai-nodes/depthai-nodes-api-reference/node/parsers/utils/medipipe.md#medipipe-Classes-HandRegion) | Store a detected palm and its derived rotated region. |

### class `HandRegion`

```python
class HandRegion
```

Store a detected palm and its derived rotated region.

Attributes

| Name | Description |
| --- | --- |
| `pd_box` | Normalized `[x, y, width, height]` box in the square image. |
| `pd_kps` | Normalized `[x, y]` palm keypoints in the square image. |
| `pd_score` | Palm detection confidence. |
| `rect_h` | Normalized rectangle height, which may exceed 1. |
| `rect_h_a` | Rectangle height in square-image pixels. |
| `rect_points` | Four rectangle corners in pixels. Coordinates refer to the square image during processing and the source image on return. |
| `rect_w` | Normalized rectangle width, which may exceed 1. |
| `rect_w_a` | Rectangle width in square-image pixels. |
| `rect_x_center` | Normalized rotated-rectangle center X coordinate. |
| `rect_x_center_a` | Rectangle center X coordinate in square-image pixels. |
| `rect_y_center` | Normalized rotated-rectangle center Y coordinate. |
| `rect_y_center_a` | Rectangle center Y coordinate in square-image pixels. |
| `rotation` | Rectangle rotation relative to the Y axis, in radians. |

Methods

| Name | Description |
| --- | --- |
| [`__init__`](https://docs.luxonis.com/software-v3/ai-inference/inference/depthai-nodes/depthai-nodes-api-reference/node/parsers/utils/medipipe.md#medipipe-Classes-HandRegion-__init__) | Store palm detection values before deriving a rotated region. |

#### method `__init__`

```python
def __init__(pd_score=None, pd_box=None, pd_kps=None)
```

Store palm detection values before deriving a rotated region.

Args

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `pd_score` |  | Optional detection confidence. | `None` |
| `pd_box` |  | Optional normalized `[x, y, width, height]` box. | `None` |
| `pd_kps` |  | Optional normalized palm keypoints. | `None` |

## Functions

| Name | Description |
| --- | --- |
| [`calculate_scale`](https://docs.luxonis.com/software-v3/ai-inference/inference/depthai-nodes/depthai-nodes-api-reference/node/parsers/utils/medipipe.md#medipipe-Functions-calculate_scale) | Interpolate an anchor scale across feature strides. |
| [`compute_mediapipe_palm_detections`](https://docs.luxonis.com/software-v3/ai-inference/inference/depthai-nodes/depthai-nodes-api-reference/node/parsers/utils/medipipe.md#medipipe-Functions-compute_mediapipe_palm_detections) | Decode MediaPipe palms into rotated detections and apply suppression. |
| [`decode`](https://docs.luxonis.com/software-v3/ai-inference/inference/depthai-nodes/depthai-nodes-api-reference/node/parsers/utils/medipipe.md#medipipe-Functions-decode) | Decode palm predictions and attach rotated pixel rectangles. |
| [`decode_bboxes`](https://docs.luxonis.com/software-v3/ai-inference/inference/depthai-nodes/depthai-nodes-api-reference/node/parsers/utils/medipipe.md#medipipe-Functions-decode_bboxes) | Decode palm boxes and seven landmarks using SSD anchors. |
| [`detections_to_rect`](https://docs.luxonis.com/software-v3/ai-inference/inference/depthai-nodes/depthai-nodes-api-reference/node/parsers/utils/medipipe.md#medipipe-Functions-detections_to_rect) | Add normalized rotated-rectangle geometry to each palm in place. |
| [`generate_anchors`](https://docs.luxonis.com/software-v3/ai-inference/inference/depthai-nodes/depthai-nodes-api-reference/node/parsers/utils/medipipe.md#medipipe-Functions-generate_anchors) | Generate SSD anchors using MediaPipe's anchor layout. |
| [`generate_handtracker_anchors`](https://docs.luxonis.com/software-v3/ai-inference/inference/depthai-nodes/depthai-nodes-api-reference/node/parsers/utils/medipipe.md#medipipe-Functions-generate_handtracker_anchors) | Generate anchors for the MediaPipe palm-detection layout. |
| [`normalize_radians`](https://docs.luxonis.com/software-v3/ai-inference/inference/depthai-nodes/depthai-nodes-api-reference/node/parsers/utils/medipipe.md#medipipe-Functions-normalize_radians) | Wrap an angle to the interval [-pi, pi). |
| [`rect_transformation`](https://docs.luxonis.com/software-v3/ai-inference/inference/depthai-nodes/depthai-nodes-api-reference/node/parsers/utils/medipipe.md#medipipe-Functions-rect_transformation) | Convert rotated regions to pixel rectangles in place. |
| [`rotated_rect_to_points`](https://docs.luxonis.com/software-v3/ai-inference/inference/depthai-nodes/depthai-nodes-api-reference/node/parsers/utils/medipipe.md#medipipe-Functions-rotated_rect_to_points) | Convert a rotated rectangle into integer pixel corners. |

### function `calculate_scale`

```python
def calculate_scale(min_scale, max_scale, stride_index, num_strides)
```

Interpolate an anchor scale across feature strides.

Args

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `min_scale` |  | Scale at the first stride. | required |
| `max_scale` |  | Scale at the last stride. | required |
| `stride_index` |  | Zero-based stride index. | required |
| `num_strides` |  | Number of strides; when one, use the midpoint scale. | required |

Returns

| Type | Description |
| --- | --- |
|  | Interpolated anchor scale. |

### function `compute_mediapipe_palm_detections`

```python
def compute_mediapipe_palm_detections(
    bboxes: np.ndarray,
    scores: np.ndarray,
    *,
    anchors: np.ndarray,
    conf_threshold: float,
    iou_threshold: float,
    max_det: int,
    scale: int,
    label_names: list[str] | None = None,
) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, list[str] | None]
```

Decode MediaPipe palms into rotated detections and apply suppression.

Args

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `bboxes` | `np.ndarray` | Per-anchor palm box and landmark predictions. | required |
| `scores` | `np.ndarray` | Per-anchor palm score logits. | required |
| `anchors` | `np.ndarray` | Precomputed anchor coordinates used to decode model predictions. | required |
| `conf_threshold` | `float` | Minimum detection confidence used to filter candidates. | required |
| `iou_threshold` | `float` | Intersection-over-union threshold for non-maximum suppression. | required |
| `max_det` | `int` | Maximum number of detection candidates to retain or consider during suppression. | required |
| `scale` | `int` | Side length of the square model input in pixels. | required |
| `label_names` | `list[str] | None` | Optional class-name lookup indexed by predicted class ID. | `None` |

Returns

| Type | Description |
| --- | --- |
| `tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, list[str] | None]` | Normalized center-XY/width/height boxes, confidence scores, angles in degrees, zero-valued class IDs, and optional class names. |

### function `decode`

```python
def decode(bboxes, scores, anchors, threshold=0.5, scale=192)
```

Decode palm predictions and attach rotated pixel rectangles.

Args

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `bboxes` |  | Per-anchor box and landmark offsets of shape `(N, 18)`. | required |
| `scores` |  | One score logit per anchor. | required |
| `anchors` |  | Precomputed anchors matching the model input dimensions. | required |
| `threshold` |  | Minimum sigmoid score for keeping a detection. | `0.5` |
| `scale` |  | Side length of the square model input in pixels. | `192` |

Returns

| Type | Description |
| --- | --- |
|  | List of `HandRegion` objects containing normalized palm geometry and pixel-space rotated rectangles. |

### function `decode_bboxes`

```python
def decode_bboxes(score_thresh, scores, bboxes, anchors, scale=128, best_only=False)
```

Decode palm boxes and seven landmarks using SSD anchors.

Args

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `score_thresh` |  | Minimum sigmoid confidence for retaining a palm. | required |
| `scores` |  | One score logit per anchor. | required |
| `bboxes` |  | Per-anchor box and landmark offsets of shape `(N, 18)`. | required |
| `anchors` |  | Normalized center-XY/width/height anchors matching the prediction count. | required |
| `scale` |  | Model input side length used to normalize the predicted offsets. | `128` |
| `best_only` |  | Compatibility flag for highest-score selection; the standard decoding path uses false. | `False` |

Returns

| Type | Description |
| --- | --- |
|  | List of `HandRegion` objects with normalized palm boxes and keypoints. Negative-width or negative-height boxes are discarded. |

Raises

| Type | Description |
| --- | --- |
| `IndexError` | If predictions and anchors cannot be selected together. The current highest-score path also raises when a candidate meets the threshold. |

### function `detections_to_rect`

```python
def detections_to_rect(regions)
```

Add normalized rotated-rectangle geometry to each palm in place.

Args

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `regions` |  | Hand regions with palm boxes and landmarks. The wrist-to-middle-finger direction determines rotation. | required |

### function `generate_anchors`

```python
def generate_anchors(options)
```

Generate SSD anchors using MediaPipe's anchor layout.

Based on the MediaPipe `ssd_anchors_calculator.cc` implementation.

Args

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `options` | `SSDAnchorOptions` | Layer sizes, strides, scales, and aspect ratios. | required |

Returns

| Type | Description |
| --- | --- |
|  | Array of anchors in `[x_center, y_center, width, height]` format. |

### function `generate_handtracker_anchors`

```python
def generate_handtracker_anchors(input_size_width, input_size_height)
```

Generate anchors for the MediaPipe palm-detection layout.

Args

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `input_size_width` |  | Model input width in pixels. | required |
| `input_size_height` |  | Model input height in pixels. | required |

Returns

| Type | Description |
| --- | --- |
|  | Array of normalized center-XY/width/height anchors for strides 8, 16, 16, and 16. |

### function `normalize_radians`

```python
def normalize_radians(angle)
```

Wrap an angle to the interval [-pi, pi).

Args

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `angle` |  | Input angle in radians. | required |

Returns

| Type | Description |
| --- | --- |
|  | Equivalent angle between -pi inclusive and pi exclusive. |

### function `rect_transformation`

```python
def rect_transformation(regions, w, h, no_shift=False)
```

Convert rotated regions to pixel rectangles in place.

Args

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `regions` |  | Regions already populated by `detections_to_rect()`. | required |
| `w` |  | Source image width in pixels. | required |
| `h` |  | Source image height in pixels. | required |
| `no_shift` |  | If false, shift toward the fingers and expand the square by 2.9; if true, keep the center and use the original longer side. | `False` |

### function `rotated_rect_to_points`

```python
def rotated_rect_to_points(cx, cy, w, h, rotation)
```

Convert a rotated rectangle into integer pixel corners.

Args

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `cx` |  | Rectangle center X coordinate. | required |
| `cy` |  | Rectangle center Y coordinate. | required |
| `w` |  | Rectangle width in pixels. | required |
| `h` |  | Rectangle height in pixels. | required |
| `rotation` |  | Rotation angle in radians. | required |

Returns

| Type | Description |
| --- | --- |
|  | Four integer XY coordinate lists in perimeter order. |

## Module Attributes

| Name | Description |
| --- | --- |
| [`SSDAnchorOptions`](https://docs.luxonis.com/software-v3/ai-inference/inference/depthai-nodes/depthai-nodes-api-reference/node/parsers/utils/medipipe.md#medipipe-Module-Attributes-SSDAnchorOptions) |  |

### variable `SSDAnchorOptions`

```python
SSDAnchorOptions = namedtuple(
    'SSDAnchorOptions',
    ['num_layers', 'min_scale', 'max_scale', 'input_size_height', 'input_size_width', 'anchor_offset_x', 'anchor_offset_y', 'strides', 'aspect_ratios', 'reduce_boxes_in_lowest_layer', 'interpolated_scale_aspect_ratio', 'fixed_anchor_size'],
)
```
