为了进行比较,请查看不使用QGIS,ArcGIS,PostGIS等的Python中的“ 更高效的空间连接”。提出的解决方案使用Python模块Fiona,Shapely和 rtree(空间索引)。
与PyQGIS和相同的示例两层,point
以及polygon
:
1)没有空间索引:
polygons = [feature for feature in polygon.getFeatures()]
points = [feature for feature in point.getFeatures()]
for pt in points:
point = pt.geometry()
for pl in polygons:
poly = pl.geometry()
if poly.contains(point):
print point.asPoint(), poly.asPolygon()
(184127,122472) [[(183372,123361), (184078,123130), (184516,122631), (184516,122265), (183676,122144), (183067,122570), (183128,123105), (183372,123361)]]
(183457,122850) [[(183372,123361), (184078,123130), (184516,122631), (184516,122265), (183676,122144), (183067,122570), (183128,123105), (183372,123361)]]
(184723,124043) [[(184200,124737), (185368,124372), (185466,124055), (185515,123714), (184955,123580), (184675,123471), (184139,123787), (184200,124737)]]
(182179,124067) [[(182520,125175), (183348,124286), (182605,123714), (182252,123544), (181753,123799), (181740,124627), (182520,125175)]]
2)使用R-Tree PyQGIS空间索引:
# build the spatial index with all the polygons and not only a bounding box
index = QgsSpatialIndex()
for poly in polygons:
index.insertFeature(poly)
# intersections with the index
# indices of the index for the intersections
for pt in points:
point = pt.geometry()
for id in index.intersects(point.boundingBox()):
print id
0
0
1
2
这些指数是什么意思?
for i, pt in enumerate(points):
point = pt.geometry()
for id in index.intersects(point.boundingBox()):
print "Point ", i, points[i].geometry().asPoint(), "is in Polygon ", id, polygons[id].geometry().asPolygon()
Point 1 (184127,122472) is in Polygon 0 [[(182520,125175), (183348,124286), (182605,123714), (182252,123544), (181753,123799), (181740,124627), (182520,125175)]]
Point 2 (183457,122850) is in Polygon 0 [[(182520,125175), (183348,124286), (182605,123714), (182252,123544), (181753,123799), (181740,124627), (182520,125175)]]
Point 4 (184723,124043) is in Polygon 1 [[(182520,125175), (183348,124286), (182605,123714), (182252,123544), (181753,123799), (181740,124627), (182520,125175)]]
Point 6 (182179,124067) is in Polygon 2 [[(182520,125175), (183348,124286), (182605,123714), (182252,123544), (181753,123799), (181740,124627), (182520,125175)]]
与没有QGIS,ArcGIS,PostGIS等的Python中的“ 更高效的空间连接”中的结论相同:
- 如果没有和索引,则必须遍历所有几何(多边形和点)。
- 使用边界空间索引(QgsSpatialIndex()),您仅循环访问有可能与当前几何图形相交的几何图形(“过滤器”可以节省大量计算和时间...)。
- 您还可以将其他空间索引Python模块(rtree,Pyrtree或Quadtree)与PyQGIS一起使用,如使用QGIS空间索引来加快代码(通过QgsSpatialIndex()和rtree)
- 但是空间索引不是魔杖。当必须检索数据集的很大一部分时,空间索引无法带来任何速度优势。
GIS se中的另一个示例:如何在QGIS中找到最接近点的线?[重复]