Python Shapely – How to Remove Overlapping Polygons in One Dataset

iterationoverlapping-featurespolygonpythonshapely

I am looking for a method using python to remove a large amount of overlapping polygons from one collection. These polygons are grouped together based on imagery collection and have been stored as WKB in a database. I am able to pull the WKBs out per collection. My current approach is to create a list of geometries and iterate using shapely.intersects per polygon to an empty list. If polygon in listA does not intersect with polygon in listB the polygon in listA is appended to listB and removed from listA. My thinking is as this iterates I will be able to move polygons with no overlaps to one list and keep the overlapping polygons in another. When I run this code I get the error: "AttributeError 'list' object has no attribute '_geom'".

polygon_list_A = [<shapely.geometry.polygon.Polygon object at 0x000005B3A>, <shapely.geometry.polygon.Polygon object at 0x000006E7A>, ...]

polygon_list_B = []

for polygon_A in polygon_list_A:
    if polygon_A.intersects(polygon_list_B) == True:
        polygon_list_B.append(polygon_A)
        polygon_list_A.remove(polygon_A)
    else:
        pass

Best Answer

AttributeError 'list' object has no attribute '_geom'

Why ? Because polygon_list_B is an empty list and not a Shapely geometry in if polygon_A.intersects(polygon_list_B): (you don't need == True, it is implicit)

A possible solution is to iterate through all pairs of geometries in polygon_list_A to find the intersections (as in Finding the common borders between polygons in the same shapefile)

enter image description here

import itertools
polygon_list_B = []
for geom1,geom2 in  itertools.combinations(polygon_list_A, 2):
     if geom1.intersects(geom2):
        polygon_list_B.append(geom1)
        polygon_list_A.remove(geom1)

polygon_list_A -> dark green colour, polygon_list_B -> light green colour

enter image description here

If you only want the polygons without intersection

polygon_list_B = []          
for geom1,geom2 in  itertools.combinations(polygon_list_A, 2):
    if geom1.intersects(geom2):
         polygon_list_B.append(geom1)
         polygon_list_B.append(geom2)
 result = [geom for geom in polygon_list_A if geom not in polygon_list_B]

result -> dark green colour, polygon_list_B -> light green colour

enter image description here