I'm using Shapely's polygons for human-generated data. Multiple humans were asked to draw polygons around certain features in images. For each image, we thus have n MultiPolygon's, where n equals the number of participants per image.
I can plot each of these Multipolygon's.
fig, ax = plt.subplots()
for ii, multi_poly in enumerate(multi_polys):
for poly in multi_poly.geoms:
x,y = poly.exterior.xy
plt.plot(x,y, c=colors[ii])
We can see that at some locations, the Multipolygon's overlap, while at others there is no overlap.
I wish to get the overlap, or intersections, of these polygons. This should be trivial, as I can do something like:
intersection = multi_a.intersection(multi_b) \
.intersection(multi_c) \
.intersection(multi_d) \
.inters...
I can plot this intersection on the previous plot and we see:
This looks pretty good. However, this method only returns the regions where all Multipoloygon's overlap. Is there a way to get the intersection where 75% of the polygons overlap? Or where 50% overlap?
A code example: The following dummy data gives this figure:
P1 = Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])
P2 = Polygon([(2.5, 2), (3, 2), (3, 3), (2.5, 3)])
multi_a = MultiPolygon([P1, P2])
P1 = Polygon([(-1, -1), (-1, 2),(2, 2), (2, -1)])
P2 = Polygon([(3, 3), (4, 2), (4, 4), (3, 4)])
multi_b = MultiPolygon([P1,P2])
P1 = Polygon([(-2, 4), (2.2, 4),(2.2, -2), (-2, -2)])
P2 = Polygon([(-1.5, 3), (-1.1, 3), (-1.5, -1), (-1.1, -1)])
multi_c = MultiPolygon([P1,P2])
P1 = Polygon([(2.5, -1), (3.2, -1),(3.2, -2), (-2, -2)])
P2 = Polygon([(3, 0), (4, 0), (3, 1), (4, 1)])
multi_d = MultiPolygon([P1,P2])
On these four multipolygons, the intersection method would returns no intersection as there is not a single spot that all four multipolygons occupy. However, the blue square, accentuated with yellow marker, is occupied by the blue, orange and green polygon. Thus 75% of the multipolygons overlap at this location.
Is there a way (preferably using Shapely) to get the locations where 75% of polygons overlap?
The accepted answer appeared to break down in certain conditions.
I found the problem: the boundaries of the contain shape sometimes overlap the inter polygons. I can replace if geom.contains(polygon): with if geom.contains(polygon.buffer(-1)): and it works exactly as intended.







