pythonmergepolygonshapelyoverlapping

Removing the overlapping part between 2 polygons in Python


I have 2 polygons that have some parts overlapping like this :

enter image description here

I have the coordinates of the 2 polygons.

I would want to have the coordinates without the overlapping part.

My idea is to create 2 new polygons but without the overlapping part, so reduce the size of one of the polygons.

from shapely.geometry import Polygon

p = Polygon([(1,1),(1,2),(4,2),(4,1)])
q = Polygon([(2,1.5),(2,3),(3,3),(3,1.5)])

Here is an example of the data that I am working with.

Thanks in advance for the help


Solution

  • This is all supported by shapely. Have a look at the manual for questions like this.

    p.symmetric_difference(q)
    

    enter image description here

    p.difference(q)
    

    enter image description here

    q.difference(p)
    

    enter image description here


    To get the coordinates in the case of symmetric_difference (https://stackoverflow.com/a/40631091/10020283):

    from shapely.geometry import mapping
    
    mapping(p.symmetric_difference(q))["coordinates"]
    

    Gives multiple lists of coordinates for the different parts of the resulting shape:

    [(((1.0, 1.0),
       (1.0, 2.0),
       (2.0, 2.0),
       (2.0, 1.5),
       (3.0, 1.5),
       (3.0, 2.0),
       (4.0, 2.0),
       (4.0, 1.0),
       (1.0, 1.0)),),
     (((3.0, 2.0), (2.0, 2.0), (2.0, 3.0), (3.0, 3.0), (3.0, 2.0)),)]