Reputation: 278
I have two groups of boxes as shown in the picture and code below:
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")
How do I get the IoU (intersection over union) between these two groups?
I know this is the way to get the IoU for two boxes:
p1.intersection(p2).area/ p1.union(p2).area
I have no clue how to do this for two groups of boxes like the following:
Upvotes: 0
Views: 2696
Reputation: 13717
You can simply get a union for each group using unary_union
and then get their corresponding intersection as follows:
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)
which produces the expected result:
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')
Upvotes: 2