Create new shapely polygon by subtracting the intersection with another polygon

edub picture edub · Sep 13, 2016 · Viewed 8.9k times · Source

I have two shapely MultiPolygon instances (made of lon,lat points) that intersect at various parts. I'm trying to loop through, determine if there's an intersection between two polygons, and then create a new polygon that excludes that intersection. From the attached image, I basically don't want the red circle to overlap with the yellow contour, I want the edge to be exactly where the yellow contour starts.

I've tried following the instructions here but it doesn't change my output at all, plus I don't want to merge them into one cascading union. I'm not getting any error messages, but when I add these MultiPolygons to a KML file (just raw text manipulation in python, no fancy program) they're still showing up as circles without any modifications.

# multipol1 and multipol2 are my shapely MultiPolygons
from shapely.ops import cascaded_union
from itertools import combinations
from shapely.geometry import Polygon,MultiPolygon

outmulti = []
for pol in multipoly1:
    for pol2 in multipoly2:
        if pol.intersects(pol2)==True:
            # If they intersect, create a new polygon that is
            # essentially pol minus the intersection
            intersection = pol.intersection(pol2)
            nonoverlap = pol.difference(intersection)
            outmulti.append(nonoverlap)

        else:
            # Otherwise, just keep the initial polygon as it is.
            outmulti.append(pol)

finalpol = MultiPolygon(outmulti)

Polygon Overlap

Answer

mgc picture mgc · Sep 13, 2016

I guess you can use the symmetric_difference between theses two polygons, combined by the difference with the second polygon to achieve what you want to do (the symmetric difference will brings you the non-overlapping parts from the two polygons, on which are removed parts of the polygon 2 by the difference). I haven't tested but it might look like :

# multipol1 and multipol2 are my shapely MultiPolygons
from shapely.ops import cascaded_union
from itertools import combinations
from shapely.geometry import Polygon,MultiPolygon

outmulti = []
for pol in multipoly1:
    for pol2 in multipoly2:
        if pol.intersects(pol2)==True:
            # If they intersect, create a new polygon that is
            # essentially pol minus the intersection
            nonoverlap = (pol.symmetric_difference(pol2)).difference(pol2)
            outmulti.append(nonoverlap)

        else:
            # Otherwise, just keep the initial polygon as it is.
            outmulti.append(pol)

finalpol = MultiPolygon(outmulti)