boundingbox
最后更新
luxonis_train.utils.boundingbox用于检测头、损失和指标的边界框辅助函数。该模块包含:- 框角和锚点距离之间的转换;
- IoU 及其变体,以及 IoU 损失;
- 非极大值抑制;
- 特征金字塔特征图的锚点;
- 移除框外掩码像素,以及将关键点转换为框。
"xyxy": 左上角和右下角,(x1, y1, x2, y2)。"xywh": 左上角、宽度和高度,(x, y, w, h)。"cxcywh": 中心、宽度和高度,(cx, cy, w, h)。
"none"、"giou"、"diou"、"ciou" 和 "siou"。函数
anchors_for_fpn_features
Python
1def 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
1>>> import torch
2>>> features = [torch.zeros(1, 8, 2, 2), torch.zeros(1, 8, 1, 1)]
3>>> anchors, points, n_anchors, strides = anchors_for_fpn_features(
4... features, torch.tensor([8, 16]), multiply_with_stride=True
5... )
6>>> n_anchors
7[4, 1]
8>>> points.tolist()
9[[4.0, 4.0], [12.0, 4.0], [4.0, 12.0], [12.0, 12.0], [8.0, 8.0]]
10>>> anchors[0].tolist()
11[-16.0, -16.0, 24.0, 24.0]
12>>> strides.flatten().tolist()
13[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
1def apply_bounding_box_to_masks(masks: Tensor, bounding_boxes: Tensor) -> Tensor:i 保留列 x 和行 y 中的像素,其中 (x1, y1, x2, y2) 是框 i。比较使用像素的整数索引。该函数不改变 masks。示例
Pycon
1>>> import torch
2>>> masks = torch.ones(1, 4, 4)
3>>> boxes = torch.tensor([[1.0, 0.0, 3.0, 2.0]])
4>>> apply_bounding_box_to_masks(masks, boxes)[0].int().tolist()
5[[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
1def bbox2dist(bbox: Tensor, anchor_points: Tensor, reg_max: float) -> Tensor:xyxy 框转换为与锚点的距离。该函数计算从每个锚点到其框的左、上、右和下侧的距离 (l, t, r, b)。它将距离裁剪到 [0, reg_max - 0.01]。当锚点在该侧的框外时,距离为 0。dist2bbox 执行相反的转换。示例
Pycon
1>>> import torch
2>>> bbox = torch.tensor([[9.0, 8.0, 13.0, 14.0]])
3>>> anchor_points = torch.tensor([[10.0, 10.0]])
4>>> bbox2dist(bbox, anchor_points, reg_max=16).tolist()
5[[1.0, 2.0, 3.0, 4.0]]
6>>> distances = bbox2dist(bbox, anchor_points, reg_max=3)
7>>> [round(value, 2) for value in distances[0].tolist()]
8[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
1def bbox_iou(bbox1: Tensor, bbox2: Tensor, bbox_format: BBoxFormatType = 'xyxy', iou_type: IoUType = 'none', element_wise: bool = False) -> Tensor: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 的完整 IoU,DIoU − α**v。"siou": 来自 SIoU Loss: More Powerful Learning for Bounding Box Regression 的 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
1>>> import torch
2>>> boxes = torch.tensor([[0.0, 0.0, 2.0, 2.0], [0.0, 0.0, 2.0, 1.0]])
3>>> target = torch.tensor([[0.0, 0.0, 2.0, 2.0]])
4>>> bbox_iou(boxes, target).tolist()
5[[1.0], [0.5]]
6>>> bbox_iou(boxes, boxes, element_wise=True).tolist()
7[1.0, 1.0]0:Pycon
1>>> left = torch.tensor([[0.0, 0.0, 1.0, 1.0]])
2>>> right = torch.tensor([[2.0, 0.0, 3.0, 1.0]])
3>>> round(bbox_iou(left, right, iou_type="giou").item(), 4)
4-0.3333bbox1(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
1def 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]: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
1>>> import torch
2>>> pred = torch.tensor([[0.0, 0.0, 2.0, 2.0], [0.0, 0.0, 2.0, 1.0]])
3>>> target = torch.tensor([[0.0, 0.0, 2.0, 2.0]]).repeat(2, 1)
4>>> loss, iou = compute_iou_loss(pred, target)
5>>> loss.item(), iou.tolist()
6(0.25, [[1.0], [0.5]])Pycon
1>>> mask = torch.zeros(1, 2, dtype=torch.bool)
2>>> loss, iou = compute_iou_loss(
3... pred[None], target[None], mask_positive=mask
4... )
5>>> loss.item(), iou.tolist()
6(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。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
1def 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 执行相反的转换。示例
Pycon
1>>> import torch
2>>> distance = torch.tensor([[1.0, 2.0, 3.0, 4.0]])
3>>> anchor_points = torch.tensor([[10.0, 10.0]])
4>>> dist2bbox(distance, anchor_points).tolist()
5[[9.0, 8.0, 13.0, 14.0]]
6>>> dist2bbox(distance, anchor_points, out_format="cxcywh").tolist()
7[[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
1def 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
1>>> import torch
2>>> keypoints = torch.tensor(
3... [
4... [[10.0, 10.0, 0.75, 2.0]],
5... [[1.0, 30.0, 0.5, 0.0]],
6... [[20.0, 20.0, 0.25, 1.0]],
7... ]
8... )
9>>> boxes = keypoints_to_bboxes(
10... [keypoints], img_height=32, img_width=32
11... )
12>>> boxes[0].tolist()
13[[7.5, 7.5, 12.5, 12.5, 0.75, 2.0],
14 [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
1def 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
1>>> import torch
2>>> preds = torch.tensor(
3... [
4... [
5... [0.0, 0.0, 10.0, 10.0, 0.75, 1.0],
6... [1.0, 1.0, 10.0, 10.0, 0.625, 1.0],
7... [20.0, 20.0, 30.0, 30.0, 0.5, 1.0],
8... ]
9... ]
10... )
11>>> non_max_suppression(preds, n_classes=1)[0].tolist()
12[[0.0, 0.0, 10.0, 10.0, 0.75, 0.0],
13 [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]范围时。