问题
We are using a shapely library to check that some random point is not in some prohibited areas stored in a shape file.
with fiona.open(path) as source:
geometry = get_exclusive_item(source[0])
geom = shapely.geometry.shape(geometry['geometry'])
def check(lat, lng):
point = shapely.geometry.Point(lng, lat)
return not geom.contains(point)
But the latest call geom.contains(point)
takes about a second to complete. Is there any other faster libraries for python, or could we optimize a shape files somehow to get better speed?
回答1:
Thank for the @iant point to use a spatial indexes.
My shapefile was a single MultiPoligon with a lot of points, makes .contains()
are really slow.
I solved the issue by splitting it into smaller shapes and use Rtree index.
To split shapefile I used QGIS, as it descrived here - https://gis.stackexchange.com/a/23694/65569
The core idea how to use RTree in python is here - https://gis.stackexchange.com/a/144764/65569
In total this gaves me 1000x speed-up for .contains() lookups!
来源:https://stackoverflow.com/questions/36282306/is-there-way-to-optimize-speed-of-shapely-geometry-shape-containsa-point-call