Once you have loaded both files as features collections (have a look at fiona
for that), the brute force approach is to test for intersection (or overlap, there's a slight difference between the two terms, the shapely
documentation explains it) of all against all. This can be done in a nested loop.
from shapely.geometry import shape
# List to collect pairs of intersecting features
fc_intersect = []
for featA in fc_A:
for featB in fc_B:
if shape(featA['geometry']).intersects(shape(featB['geometry'])):
fc_intersect.append([featA, featB])
If you have a lot of features on both sides, this can get very slow. Speed can be optimized by using a spatial index; that's what the rtree
package does.
from rtree import index
from shapely.geometry import shape
# List to collect pairs of intersecting features
fc_intersect = []
# Instantiate index class
idx = index.Index()
for i,featA in enumerate(fc_A):
idx.insert(i, shape(featA['geometry']).bounds)
for featB in fc_B:
# Test for potential intersection with each feature of the other feature collection
for intersect_maybe in idx.intersection(shape(featB['geometry']).bounds):
# Confirm intersection
if shape(featB['geometry']).intersects(shape(fc_B[intersect_maybe]['geometry'])):
fc_intersect.append([fc_A[intersect_maybe], featB])