# boundingbox

Python API: `luxonis_train.utils.boundingbox`

用于检测头、损失和指标的边界框辅助函数。

该模块包含：

 * 框角和锚点距离之间的转换；
 * IoU 及其变体，以及 IoU 损失；
 * 非极大值抑制；
 * 特征金字塔特征图的锚点；
 * 移除框外掩码像素，以及将关键点转换为框。

[BBoxFormatType](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/utils/boundingbox.md)
命名了框格式：

 * `"xyxy"`: 左上角和右下角，`(x1, y1, x2, y2)`。
 * `"xywh"`: 左上角、宽度和高度，`(x, y, w, h)`。
 * `"cxcywh"`: 中心、宽度和高度，`(cx, cy, w, h)`。

[IoUType](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/utils/boundingbox.md)
命名了
[bbox_iou](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/utils/boundingbox.md)
的 IoU 变体：`"none"`、`"giou"`、`"diou"`、`"ciou"` 和 `"siou"`。

## 函数

### anchors_for_fpn_features

```python
def anchors_for_fpn_features(features: list[Tensor], strides: Tensor, grid_cell_size: float = 5.0, grid_cell_offset: float = 0.5, multiply_with_stride: bool = False) -> tuple[Tensor, Tensor, list[int], Tensor]:
```

生成特征金字塔特征图的锚点。

该函数在每个特征图的每个单元格中放置一个锚点。行 `i` 和列 `j` 中单元格的锚点是 `(j + grid_cell_offset, i + grid_cell_offset)`，以单元格为单位。锚框是一个边长为 `grid_cell_size *
stride` 的正方形，围绕锚点。边长不随 `multiply_with_stride` 改变。特征图的锚点遵循 `features` 的顺序，并在每个图中逐行排列。

该函数按顺序将 `features` 与 `strides` 配对，并忽略较长的一个的额外项。返回的张量具有特征图的数据类型，并位于 `features[0]` 的设备上。

> **示例**
> ```pycon
>>> import torch
>>> features = [torch.zeros(1, 8, 2, 2), torch.zeros(1, 8, 1, 1)]
>>> anchors, points, n_anchors, strides = anchors_for_fpn_features(
...     features, torch.tensor([8, 16]), multiply_with_stride=True
... )
>>> n_anchors
[4, 1]
>>> points.tolist()
[[4.0, 4.0], [12.0, 4.0], [4.0, 12.0], [12.0, 12.0], [8.0, 8.0]]
>>> anchors[0].tolist()
[-16.0, -16.0, 24.0, 24.0]
>>> strides.flatten().tolist()
[8.0, 8.0, 8.0, 8.0, 16.0]
```

参数

 * `features` (`list[Tensor]`): 特征图，每个形状为 `[B, C, H, W]`。该函数只读取它们的形状和数据类型，以及第一个图的设备。
 * `strides` (`Tensor`): 每个特征图的一个步幅，作为一维张量。
 * `grid_cell_size` (`float`): 锚框的边长，以步幅为单位。
 * `grid_cell_offset` (`float`): 锚点相对于其单元格左上角的偏移量，以单元格为单位。
 * `multiply_with_stride` (`bool`): 是否将锚点乘以步幅。点将以输入图像像素为单位。

返回

 * `tuple[Tensor, Tensor, list[int], Tensor]`: 四个值，其中 `A` 是锚点的总数。 * `xyxy` 格式的锚框，形状为 `[A, 4]`；
    * 锚点 `(x, y)`，形状为 `[A, 2]`；
    * 每个特征图的锚点数量 `H * W`；
    * 每个锚点的步幅，形状为 `[A, 1]`。

### apply_bounding_box_to_masks

```python
def apply_bounding_box_to_masks(masks: Tensor, bounding_boxes: Tensor) -> Tensor:
```

返回框外像素为零的掩码。

当 x1 ≤ x < x2 且 y1 ≤ y < y2 时，掩码 `i` 保留列 x 和行 y 中的像素，其中 (x1, y1, x2, y2) 是框 `i`。比较使用像素的整数索引。该函数不改变 `masks`。

> **示例**
> ```pycon
>>> import torch
>>> masks = torch.ones(1, 4, 4)
>>> boxes = torch.tensor([[1.0, 0.0, 3.0, 2.0]])
>>> apply_bounding_box_to_masks(masks, boxes)[0].int().tolist()
[[0, 1, 1, 0], [0, 1, 1, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
```

参数

 * `masks` (`Tensor`): 掩码，形状为 `[N, H, W]`。
 * `bounding_boxes` (`Tensor`): 每个掩码的一个 `xyxy` 框，以掩码像素为单位，形状为 `[N, 4]`。

返回

 * `Tensor`: 乘以框区域的掩码，形状为 `[N, H, W]`。

### bbox2dist

```python
def bbox2dist(bbox: Tensor, anchor_points: Tensor, reg_max: float) -> Tensor:
```

将 `xyxy` 框转换为与锚点的距离。

该函数计算从每个锚点到其框的左、上、右和下侧的距离 `(l, t, r, b)`。它将距离裁剪到 `[0, reg_max - 0.01]`。当锚点在该侧的框外时，距离为
`0`。[dist2bbox](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/utils/boundingbox.md)
执行相反的转换。

> **示例**
> ```pycon
>>> import torch
>>> bbox = torch.tensor([[9.0, 8.0, 13.0, 14.0]])
>>> anchor_points = torch.tensor([[10.0, 10.0]])
>>> bbox2dist(bbox, anchor_points, reg_max=16).tolist()
[[1.0, 2.0, 3.0, 4.0]]
>>> distances = bbox2dist(bbox, anchor_points, reg_max=3)
>>> [round(value, 2) for value in distances[0].tolist()]
[1.0, 2.0, 2.99, 2.99]
```

参数

 * `bbox` (`Tensor`): `xyxy` 格式的框，形状为 `[..., 4]`。
 * `anchor_points` (`Tensor`): 锚点 `(x, y)`，形状为 `[..., 2]`。形状必须与框角的形状广播。
 * `reg_max` (`float`): 距离的限制。返回的最大距离是 `reg_max - 0.01`。

返回

 * `Tensor`: 距离 `(l, t, r, b)`，形状为 `[..., 4]`。

### bbox_iou

```python
def bbox_iou(bbox1: Tensor, bbox2: Tensor, bbox_format: BBoxFormatType = 'xyxy', iou_type: IoUType = 'none', element_wise: bool =
False) -> Tensor:
```

计算两组边界框之间的 IoU。

该函数将两组框转换为 `xyxy` 格式，并计算 `bbox1` 中每个框与 `bbox2` 中每个框的 IoU。A 和 B 是两个框，C 是包含两者的最小框。`iou_type` 选择变体：

 * `"none"`: 普通 IoU，IoU = (|A∩B|)/(|A∪B|)。
 * `"giou"`: 广义 IoU，IoU − (|C⧵(A∪B)|)/(|C|)。
 * `"diou"`: 距离 IoU，IoU − (ρ2)/(c2)。ρ 是框中心之间的距离，c 是 C 的对角线。
 * `"ciou"`: 来自 [Enhancing Geometric Factors in Model Learning and Inference for Object Detection and Instance Segmentation](https://arxiv.org/pdf/2005.03572.pdf) 的完整 IoU，DIoU − α**v。
 * `"siou"`: 来自 [SIoU Loss: More Powerful Learning for Bounding Box Regression](https://arxiv.org/pdf/2205.12740.pdf) 的 SIoU，IoU − (Δ + Ω)/(2)。Δ 是距离成本，包括角度成本，Ω 是形状成本。

对于 `"ciou"`，w 和 h 是框的宽度和高度。该函数将 10 − 7 添加到高度，并且没有梯度流过 α：

v = (4)/(π2)⎛⎝arctan(wA)/(hA) − arctan(wB)/(hB)⎞⎠2

α = (v)/(1 − IoU + v + 10 − 7)

该函数将 `NaN` 结果替换为 `0`。

警告： `"siou"` 在其某些项中将 `bbox1[i]` 与 `bbox2[i]` 配对。它需要 `N` 等于 `M`，并且只有其结果的对角线是正确的。请与 `element_wise=True` 一起使用。

> **示例**
> ```pycon
>>> import torch
>>> boxes = torch.tensor([[0.0, 0.0, 2.0, 2.0], [0.0, 0.0, 2.0, 1.0]])
>>> target = torch.tensor([[0.0, 0.0, 2.0, 2.0]])
>>> bbox_iou(boxes, target).tolist()
[[1.0], [0.5]]
>>> bbox_iou(boxes, boxes, element_wise=True).tolist()
[1.0, 1.0]
```

两个独立框的广义 IoU 小于 `0`：

```pycon
>>> left = torch.tensor([[0.0, 0.0, 1.0, 1.0]])
>>> right = torch.tensor([[2.0, 0.0, 3.0, 1.0]])
>>> round(bbox_iou(left, right, iou_type="giou").item(), 4)
-0.3333
```

参数

 * `bbox1` (`Tensor`): 第一组框，形状为 `[N, 4]`。
 * `bbox2` (`Tensor`): 第二组框，形状为 `[M, 4]`。
 * `bbox_format` (`BBoxFormatType`): 两组框的格式。
 * `iou_type` (`IoUType`): IoU 变体。
 * `element_wise` (`bool`): 是否只返回 IoU 矩阵的对角线，即 `bbox1[i]` 和 `bbox2[i]` 的 IoU。该函数在两种情况下都计算完整矩阵。

返回

 * `Tensor`: 形状为 `[N, M]` 的 IoU 矩阵。如果 `element_wise` 为 `True`，则返回其对角线，形状为 `[min(N, M)]`。

引发

 * `ValueError`: 当 `iou_type` 不是受支持的变体时。

### compute_iou_loss

```python
def compute_iou_loss(pred_bboxes: Tensor, target_bboxes: Tensor, target_scores: Tensor | None = None, mask_positive: Tensor | None = None, *, iou_type: IoUType = 'giou', bbox_format: BBoxFormatType = 'xyxy', reduction: Literal['sum', 'mean'] = 'mean') -> tuple[Tensor, Tensor]:
```

计算预测框和目标框之间的 IoU 损失。

该函数将 `pred_bboxes` 的每个框与 `target_bboxes` 中相同位置的框配对。当设置 `mask_positive` 时，它只使用正对。一对的损失是 w(1 − IoU)。权重 w 是该对目标分数的总和，或者在没有
`target_scores` 时为 `1`。`reduction` 选择结果：

 * `"mean"`: 对的平均损失。
 * `"sum"`: 损失的总和。当 `target_scores` 中所有值的总和大于 `1` 时，该函数将结果除以该总和。此总和包括 `mask_positive` 之外的对。

当 `mask_positive` 没有正对时，该函数立即返回零损失。然后它既不检查 `reduction` 也不检查 `iou_type`。

> **示例**
> ```pycon
>>> import torch
>>> pred = torch.tensor([[0.0, 0.0, 2.0, 2.0], [0.0, 0.0, 2.0, 1.0]])
>>> target = torch.tensor([[0.0, 0.0, 2.0, 2.0]]).repeat(2, 1)
>>> loss, iou = compute_iou_loss(pred, target)
>>> loss.item(), iou.tolist()
(0.25, [[1.0], [0.5]])
```

如果没有正对，损失为零：

```pycon
>>> mask = torch.zeros(1, 2, dtype=torch.bool)
>>> loss, iou = compute_iou_loss(
...     pred[None], target[None], mask_positive=mask
... )
>>> loss.item(), iou.tolist()
(0.0, [0.0])
```

参数

 * `pred_bboxes` (`Tensor`): 预测框，形状为 `[B, N, 4]`。如果没有 `mask_positive`，任何形状 `[..., 4]` 都有效。
 * `target_bboxes` (`Tensor`): 目标框，与 `pred_bboxes` 形状相同。该函数将它们移动到 `pred_bboxes` 的设备。
 * `target_scores` (`Tensor | None`): 目标类别分数，形状为 `[B, N, n_classes]`。`None` 为每对赋予权重 `1`。
 * `mask_positive` (`Tensor | None`): 正对的布尔掩码，形状为 `[B, N]`。`None` 使用所有对。
 * `iou_type` (`IoUType`): IoU 变体。请参阅 [bbox_iou](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/utils/boundingbox.md)。
 * `bbox_format` (`BBoxFormatType`): 两组框的格式。
 * `reduction` (`Literal['sum', 'mean']`): 对损失的归约。

返回

 * `tuple[Tensor, Tensor]`: 标量损失，以及每个使用的对的脱离 IoU，钳制到至少 `0`，形状为 `[K, 1]`。`K` 是使用的对的数量。如果没有正对，IoU 值为形状为 `[B]` 的零。

引发

 * `ValueError`: 当 `reduction` 不是 `"sum"` 或 `"mean"`，或者当 `iou_type` 不是受支持的变体时。
 * `NotImplementedError`: 当 `reduction` 是 `"sum"` 且 `target_scores` 是 `None` 时。

### dist2bbox

```python
def dist2bbox(distance: Tensor, anchor_points: Tensor, out_format: BBoxFormatType = 'xyxy', dim: int = -1) -> Tensor:
```

将锚点距离转换为框。

距离 `(l, t, r, b)` 从锚点 (x, y) 到框的左、上、右和下侧。该函数计算角点 (x − l, y − t) 和 (x + r, y + b)，并将框转换为 `out_format`。[bbox2dist](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/utils/boundingbox.md) 执行相反的转换。

> **示例**
> ```pycon
>>> import torch
>>> distance = torch.tensor([[1.0, 2.0, 3.0, 4.0]])
>>> anchor_points = torch.tensor([[10.0, 10.0]])
>>> dist2bbox(distance, anchor_points).tolist()
[[9.0, 8.0, 13.0, 14.0]]
>>> dist2bbox(distance, anchor_points, out_format="cxcywh").tolist()
[[11.0, 11.0, 4.0, 6.0]]
```

参数

 * `distance` (`Tensor`): 距离 `(l, t, r, b)`，维度 `dim` 上大小为 `4`。
 * `anchor_points` (`Tensor`): 锚点 `(x, y)`。形状必须与 `distance` 的一半广播，后者在维度 `dim` 上大小为 `2`。
 * `out_format` (`BBoxFormatType`): 返回框的格式。
 * `dim` (`int`): 包含坐标的维度。只有 `"xyxy"` 格式支持除最后一个维度之外的维度，因为格式转换读取最后一个维度。

返回

 * `Tensor`: `out_format` 中的框，维度 `dim` 上大小为 `4`。

引发

 * `ValueError`: 当 `out_format` 不是 `"xyxy"`、`"xywh"` 或 `"cxcywh"` 时。

### keypoints_to_bboxes

```python
def keypoints_to_bboxes(keypoints: list[Tensor], img_height: int, img_width: int, box_width: int = 5, visibility_threshold: float = 0.5) -> list[Tensor]:
```

将关键点转换为 `xyxy` 格式的正方形框。

该函数丢弃可见性低于 `visibility_threshold` 的关键点。它在每个保留的关键点周围放置一个边长为 `box_width` 的正方形。它将正方形的左上角裁剪到 `0`，右下角裁剪到 `img_width` 和 `img_height`。

> **示例**
> 该函数将第二个关键点的框裁剪到图像边界。它丢弃第三个关键点，因为其可见性低于 `0.5`：

```pycon
>>> import torch
>>> keypoints = torch.tensor(
...     [
...         [[10.0, 10.0, 0.75, 2.0]],
...         [[1.0, 30.0, 0.5, 0.0]],
...         [[20.0, 20.0, 0.25, 1.0]],
...     ]
... )
>>> boxes = keypoints_to_bboxes(
...     [keypoints], img_height=32, img_width=32
... )
>>> boxes[0].tolist()
[[7.5, 7.5, 12.5, 12.5, 0.75, 2.0],
 [0.0, 27.5, 3.5, 32.0, 0.5, 0.0]]
```

参数

 * `keypoints` (`list[Tensor]`): 每张图像的关键点，每个形状为 `[N, 1, 4]`。关键点的值为 `(x, y, visibility, class_id)`。
 * `img_height` (`int`): 图像高度，以像素为单位。
 * `img_width` (`int`): 图像宽度，以像素为单位。
 * `box_width` (`int`): 框的边长，以像素为单位。
 * `visibility_threshold` (`float`): 保留关键点的最小可见性。

返回

 * `list[Tensor]`: 每张图像的框，每个形状为 `[K, 6]`，其中 `K` 是图像保留关键点的数量。框的值为 `(x_min, y_min, x_max, y_max, visibility,
   class_id)`。没有保留关键点的图像将获得形状为 `[0, 6]` 的张量。

### non_max_suppression

```python
def non_max_suppression(preds: Tensor, n_classes: int, conf_thres: float = 0.25, iou_thres: float = 0.45, keep_classes: list[int] | None = None, agnostic: bool = False, multi_label: bool = False, bbox_format: BBoxFormatType = 'xyxy', max_det: int = 300, predicts_objectness: bool = True) -> list[Tensor]:
```

对批次的框预测执行非极大值抑制。

`preds` 的一行包含一个框、一个置信度、类别分数和可选的额外值，例如关键点或掩码系数。对于每张图像，该函数执行以下步骤：

 * 它保留置信度高于 `conf_thres` 的行。当 `predicts_objectness` 为 `False` 时，最高类别分数也必须高于 `conf_thres`。
 * 它将类别分数乘以置信度。当 `predicts_objectness` 为 `True` 且 `n_classes` 为 `1` 时，它用置信度替换类别分数。
 * 它为每行赋予分数最高的类别，并保留分数高于 `conf_thres` 的行。对于 `multi_label`，每行对于分数高于 `conf_thres` 的每个类别都会获得一个副本。
 * 它丢弃类别不在 `keep_classes` 中的行。
 * 它为每个类别运行 NMS，或者当 `agnostic` 为 `True` 时跨所有类别运行。它最多保留 `max_det` 行，即分数最高的行。

> **示例**
> 前两个框的 IoU 为 `0.81`，因此 NMS 丢弃分数较低的框：

```pycon
>>> import torch
>>> preds = torch.tensor(
...     [
...         [
...             [0.0, 0.0, 10.0, 10.0, 0.75, 1.0],
...             [1.0, 1.0, 10.0, 10.0, 0.625, 1.0],
...             [20.0, 20.0, 30.0, 30.0, 0.5, 1.0],
...         ]
...     ]
... )
>>> non_max_suppression(preds, n_classes=1)[0].tolist()
[[0.0, 0.0, 10.0, 10.0, 0.75, 0.0],
 [20.0, 20.0, 30.0, 30.0, 0.5, 0.0]]
```

参数

 * `preds` (`Tensor`): 预测，形状为 `[B, N, M]`。一行的列是 `bbox_format` 中的框、置信度、`n_classes` 个类别分数和 `E = M - 5 - n_classes` 个额外值。
 * `n_classes` (`int`): `preds` 中类别分数列的数量。
 * `conf_thres` (`float`): 分数阈值，范围为 `[0, 1]`。保留的分数必须严格高于它。
 * `iou_thres` (`float`): NMS 的 IoU 阈值，范围为 `[0, 1]`。当一个框与分数更高的框的 IoU 高于此值时，NMS 会丢弃该框。
 * `keep_classes` (`list[int] | None`): 要保留的类别的索引。`None` 保留所有类别。
 * `agnostic` (`bool`): NMS 是否比较不同类别的框。
 * `multi_label` (`bool`): 一个框是否可以获得多个类别。当 `n_classes` 为 `1` 时，该函数会忽略它。
 * `bbox_format` (`BBoxFormatType`): `preds` 中框的格式。
 * `max_det` (`int`): 每张图像的最大检测数量。
 * `predicts_objectness` (`bool`): 置信度列是否包含预测的对象性。

返回

 * `list[Tensor]`: 每张图像一个张量，形状为 `[K, 6 + E]`，其中 `K` 是保留检测的数量。一行包含 `xyxy` 框、分数、作为浮点数的类别索引和额外值。行从最高分数到最低分数排列。没有检测的图像将获得形状为 `[0, M]`
   的张量。

引发

 * `ValueError`: 当 `conf_thres` 或 `iou_thres` 超出 `[0, 1]` 范围时。

## 属性

### BBoxFormatType

### IoUType
