Compute the intersection over union (IoU) of two set of boxes. Args: boxes1: bounding boxes, Nx4 or Nx6 torch tensor or ndarray. The box mode is assumed to be ``StandardMode`` boxes2: bounding boxes, Mx4 or Mx6 torch tensor or ndarray. The box mode is assumed to be ``Standa
(boxes1: NdarrayOrTensor, boxes2: NdarrayOrTensor)
| 818 | |
| 819 | |
| 820 | def box_iou(boxes1: NdarrayOrTensor, boxes2: NdarrayOrTensor) -> NdarrayOrTensor: |
| 821 | """ |
| 822 | Compute the intersection over union (IoU) of two set of boxes. |
| 823 | |
| 824 | Args: |
| 825 | boxes1: bounding boxes, Nx4 or Nx6 torch tensor or ndarray. The box mode is assumed to be ``StandardMode`` |
| 826 | boxes2: bounding boxes, Mx4 or Mx6 torch tensor or ndarray. The box mode is assumed to be ``StandardMode`` |
| 827 | |
| 828 | Returns: |
| 829 | An array/tensor matching the container type of ``boxes1`` (NumPy ndarray or Torch tensor), always |
| 830 | floating-point with size ``(N, M)``: |
| 831 | - if ``boxes1`` has a floating-point dtype, the same dtype is used. |
| 832 | - if ``boxes1`` has an integer dtype, the result is returned as ``torch.float32``. |
| 833 | |
| 834 | """ |
| 835 | |
| 836 | if not isinstance(boxes1, type(boxes2)): |
| 837 | warnings.warn(f"boxes1 is {type(boxes1)}, while boxes2 is {type(boxes2)}. The result will be {type(boxes1)}.") |
| 838 | |
| 839 | # convert numpy to tensor if needed |
| 840 | boxes1_t, *_ = convert_data_type(boxes1, torch.Tensor) |
| 841 | boxes2_t, *_ = convert_data_type(boxes2, torch.Tensor) |
| 842 | |
| 843 | # we do computation with compute_dtype to avoid overflow |
| 844 | box_dtype = boxes1_t.dtype |
| 845 | |
| 846 | inter, union = _box_inter_union(boxes1_t, boxes2_t, compute_dtype=COMPUTE_DTYPE) |
| 847 | |
| 848 | # compute IoU and convert back to original box_dtype or torch.float32 |
| 849 | iou_t = inter / (union + torch.finfo(COMPUTE_DTYPE).eps) # (N,M) |
| 850 | if not box_dtype.is_floating_point: |
| 851 | box_dtype = COMPUTE_DTYPE |
| 852 | iou_t = iou_t.to(dtype=box_dtype) |
| 853 | |
| 854 | # check if NaN or Inf |
| 855 | if torch.isnan(iou_t).any() or torch.isinf(iou_t).any(): |
| 856 | raise ValueError("Box IoU is NaN or Inf.") |
| 857 | |
| 858 | # convert tensor back to numpy if needed |
| 859 | iou, *_ = convert_to_dst_type(src=iou_t, dst=boxes1, dtype=box_dtype) |
| 860 | return iou |
| 861 | |
| 862 | |
| 863 | def box_giou(boxes1: NdarrayOrTensor, boxes2: NdarrayOrTensor) -> NdarrayOrTensor: |
searching dependent graphs…