2

I have a List of Points which I transform to circles. Code from here

circles = [Point(random.random(), random.random()).buffer(random.random() * 0.1) for i in range(3)]

I want to know which circles within this List intersect each other. Is there a way to achieve that with a native shapely function, or do I have to iterate over the all possible combinations?

PolyGeo
  • 65,136
  • 29
  • 109
  • 338
four-eyes
  • 3,378
  • 5
  • 33
  • 58

1 Answers1

6

The native shapely function is unary_union (Planar graph)

The circles

enter image description here

1) Using the script of How to find the intersection areas of overlapping buffer zones in single shapefile?

rings = [LineString(pol.exterior.coords) for pol in circles]
union = unary_union(rings)
result = [geom for geom in polygonize(union)]

Result: you have all the intersections

enter image description here

2) You can also use other solutions according to the position of an element in a list (look at Shapely/ Python looping through a number of polygons with itertools)

import itertools
for  i,j in itertools.combinations(enumerate(circles), 2):
    if i[1].intersects(j[1]):
        print "polygons", i[0],j[0] 
polygons 0 1
polygons 1 2

for  i,j in itertools.permutations(enumerate(circles), 2):
    if i[1].intersects(j[1]):
        print "polygons", i[0],j[0]

polygons 0 1
polygons 1 0
polygons 1 2
polygons 2 1

3) you can use a spatial index as rtree (look at Faster way of polygon intersection with shapely)

 from rtree import index
 idx = index.Index()
 # create the spatial index
 for pos, cell in enumerate(circles):
    idx.insert(pos, cell.bounds)
 # loop through each polygon
 for poly in circles:
    # Merge cells that have overlapping bounding boxes
    merged_cells = unary_union([circles[pos] for pos in idx.intersection(poly.bounds)])
    # Do actual intersection
    poly.intersection(merged_cells)

enter image description here

(the two intersections here)

gene
  • 54,868
  • 3
  • 110
  • 187