计算IOU

给两个长方形A,B,分别用左上角和右下角的坐标表示,求这两个矩形的交并比

面试宝典 - 图1

因此,只要计算出A、B的面积和AB相交的面积即可。

image.png
矩形A: (xmin0, ymin0, xmax0, ymax0)
矩阵B:(xmin1, ymin1, xmax1, ymax1)

  • xmax比较小的 减去 xmin中比较大的,是相交区域的宽
  • ymax比较小的 减去 ymin中比较大的,是相交区域的长
  1. def iou(rect1, rect2):
  2. xmin1, ymin1, xmax1, ymax1 = rect1
  3. xmin2, ymin2, xmax2, ymax2 = rect2
  4. s1 = (xmax1 - xmin1) * (ymax1 - ymin1)
  5. s2 = (xmax2 - xmin2) * (ymax2 - ymin2)
  6. sum_area = s1 + s2
  7. left = max(xmin2, xmin1)
  8. right = min(xmax2, xmax1)
  9. top = max(ymin2, ymin1)
  10. bottom = min(ymax2, ymax1)
  11. if left >= right or top >= bottom:
  12. return 0
  13. intersection = (right - left) * (bottom - top)
  14. return intersection / (sum_area - intersection ) * 1.0