我有两组盒子,如下图和代码所示:
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
我不知道如何针对两组类似的框执行此操作:
答案 0 :(得分:0)
您可以简单地使用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')