McCree Feng
McCree Feng

Reputation: 219

How to calculate the IOU of polygons in python?

I have two polygons. polygon1:[[x1,y1],[x2,y2],[x3,y3],[x4,y4]...[xn,yn]] polygon2:[[x1,y1],[x2,y2],[x3,y3],[x4,y4]...[xm,ym]] the num of n and m might be the same or not. How to calculate the IOU of two polygons? Or how to calculate the overlap area and area of polygon1 and polygon2 ? So I can compute Area of overlap / (Area P1 + Area P2)

Upvotes: 5

Views: 10560

Answers (1)

tiberius
tiberius

Reputation: 530

The shapely library has everything you need. As @pink_spikyhairman commented, there are many question examples of how to use this library to calculate IOU of polygons. So for example, you have your two polygons, a square and a triangle:

from shapely.geometry import Polygon

polygon1 = Polygon([(0, 0), (1, 1), (1, 0)])
polygon2 = Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])
intersect = polygon1.intersection(polygon2).area
union = polygon1.union(polygon2).area
iou = intersect / union
print(iou)  # iou = 0.5

Upvotes: 8

Related Questions