Lecture 03 学习讲义
正文
工具
按问题查找
Lecture 031 · 坐标先说清:连续 xyxy,不加一 · 实现代码

1 · 坐标先说清:连续 xyxy,不加一 · 实现代码

独立阅读

并入相关学习路径

固定框匹配、PR/AP、NMS误删相邻对象反例

展开完整实现代码
def boxes_xyxy(values):
    """Validate an (N,4) array of continuous-coordinate boxes."""
    boxes = np.asarray(values, dtype=float).reshape(-1, 4)
    if not np.isfinite(boxes).all():
        raise ValueError("Box coordinates must be finite")
    if np.any(boxes[:, 2:] < boxes[:, :2]):
        raise ValueError("Require x2 >= x1 and y2 >= y1")
    return boxes


def box_iou(boxes_a, boxes_b):
    """Return (N,M) IoUs. A zero-area union is defined to have IoU 0."""
    a, b = boxes_xyxy(boxes_a), boxes_xyxy(boxes_b)
    intersection_size = np.maximum(
        0.0, np.minimum(a[:, None, 2:], b[None, :, 2:])
        - np.maximum(a[:, None, :2], b[None, :, :2])
    )
    intersection = intersection_size.prod(axis=2)
    area_a = (a[:, 2:] - a[:, :2]).prod(axis=1)
    area_b = (b[:, 2:] - b[:, :2]).prod(axis=1)
    union = area_a[:, None] + area_b[None, :] - intersection
    return np.divide(intersection, union, out=np.zeros_like(union), where=union > 0)

print("IoU shape:", box_iou(PRED, GT).shape)
print(box_iou(PRED, GT))