多个框的IoU

IoU of multiple boxes

我有两组盒子如下图和代码所示:

from shapely.geometry import box

p1 = box(0.6,0.3,1.2,1.3)
p2 = box(0.5,0.5,1.8,1.9)
p3 = box(2,2,3,3)
p4 = box(1.4,1.4,2.6,3)
p5 = box(1,1,2.6,2.5)


plt.plot(*p1.exterior.xy, color="r")
plt.plot(*p3.exterior.xy, color="r")
plt.plot(*p5.exterior.xy, color="r")

plt.plot(*p2.exterior.xy, color="b")
plt.plot(*p4.exterior.xy, color="b")

如何获得这两个组之间的 IoU(并集交集)?

我知道这是获得两个盒子的 IoU 的方法:

p1.intersection(p2).area/ p1.union(p2).area

我不知道如何为如下两组框执行此操作:

您可以简单地使用unary_union为每个组获取并集,然后获取它们对应的交集,如下所示:

from shapely.geometry import box
from shapely.ops import unary_union

p1 = box(0.6, 0.3, 0.9, 1.3)
p2 = box(0.5, 0.5, 1.8, 1.9)
p3 = box(2, 2, 3, 3)
p4 = box(1.4, 1.4, 2.6, 3)
p5 = box(1, 1, 2.6, 2.5)

red_boxes = [p1, p3, p5]
blue_boxes = [p2, p4]

red_union = unary_union(red_boxes)
blue_union = unary_union(blue_boxes)
resulting_intersection = red_union.intersection(blue_union)

产生预期结果:

import matplotlib.pyplot as plt
from shapely.geometry import Polygon

for red in red_boxes:
    plt.plot(*red.exterior.xy, color='r')
for blue in blue_boxes:
    plt.plot(*blue.exterior.xy, color='b')
if isinstance(resulting_intersection, Polygon):
    resulting_intersection = [resulting_intersection]
for part in resulting_intersection:
    plt.fill(*part.exterior.xy, color='g')