| |
| |
|
|
| import torch |
|
|
| def pairwise_iou_max_scores(boxes1: torch.Tensor, boxes2: torch.Tensor) -> torch.Tensor: |
| """ |
| Given two lists of boxes of size N and M, compute the IoU |
| (intersection over union) between **all** N x M pairs of boxes. |
| The box order must be (xmin, ymin, xmax, ymax). |
| |
| Args: |
| boxes1,boxes2 (Boxes): two `Boxes`. Contains N & M boxes, respectively. |
| |
| Returns: |
| Tensor: IoU, sized [N,M]. |
| """ |
| area1 = (boxes1[:, 2] - boxes1[:, 0]) * (boxes1[:, 3] - boxes1[:, 1]) |
| area2 = (boxes2[:, 2] - boxes2[:, 0]) * (boxes2[:, 3] - boxes2[:, 1]) |
|
|
| width_height = torch.min(boxes1[:, None, 2:], boxes2[:, 2:]) - torch.max( |
| boxes1[:, None, :2], boxes2[:, :2] |
| ) |
|
|
| width_height.clamp_(min=0) |
| inter = width_height.prod(dim=2) |
|
|
| |
| iou = torch.where( |
| inter > 0, |
| inter / (area1[:, None] + area2 - inter), |
| torch.zeros(1, dtype=inter.dtype, device=inter.device), |
| ) |
| iou_max, _ = torch.max(iou, dim=1) |
| return iou_max |