python - 多边形相交与匀称的更快方法

标签 python numpy shapely

我有大量多边形 (~100000),并尝试找到一种聪明的方法来计算它们与规则网格单元的相交面积。

目前,我正在使用 shapely(基于它们的角坐标)创建多边形和网格单元。然后,我使用一个简单的 for 循环遍历每个多边形并将其与附近的网格单元格进行比较。

只是一个小例子来说明多边形/网格单元。

from shapely.geometry import box, Polygon
# Example polygon 
xy = [[130.21001, 27.200001], [129.52, 27.34], [129.45, 27.1], [130.13, 26.950001]]
polygon_shape = Polygon(xy)
# Example grid cell
gridcell_shape = box(129.5, -27.0, 129.75, 27.25)
# The intersection
polygon_shape.intersection(gridcell_shape).area

(顺便说一句:网格单元的尺寸为 0.25x0.25,多边形最大为 1x1)

实际上,这对于大约 0.003 秒的单个多边形/网格单元组合来说是相当快的。但是,在我的机器上运行大量多边形(每个多边形可能与数十个网格单元相交)大约需要 15 分钟以上(最多 30 分钟以上,具体取决于相交网格单元的数量),这是 Not Acceptable 。不幸的是,我不知道如何为多边形相交编写代码以获得重叠区域。你有什么建议吗?有没有身材匀称的替代品?

最佳答案

考虑使用 Rtree帮助识别多边形可能与哪些网格单元相交。这样,您可以删除与 lat/lons 数组一起使用的 for 循环,这可能是缓慢的部分。

像这样构造你的代码:

from shapely.ops import cascaded_union
from rtree import index
idx = index.Index()

# Populate R-tree index with bounds of grid cells
for pos, cell in enumerate(grid_cells):
    # assuming cell is a shapely object
    idx.insert(pos, cell.bounds)

# Loop through each Shapely polygon
for poly in polygons:
    # Merge cells that have overlapping bounding boxes
    merged_cells = cascaded_union([grid_cells[pos] for pos in idx.intersection(poly.bounds)])
    # Now do actual intersection
    print(poly.intersection(merged_cells).area)

关于python - 多边形相交与匀称的更快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14697442/

相关文章:

python - 如何添加一条最适合散点图的线

python - Shapely:沿边缘在任意点拆分 LineString

python - 值错误 : No Shapely geometry can be created from null value

python - Python Print Function 中的函数打印

python - 为什么我的 python 程序在 eclipse/pydev 中调试这么慢?

python - python中的色差估计

python元素明智地与其他列表一起添加到列表列表中

python - 将 PostGIS 几何类型作为几何类型从 Shapely 导入 Python?

python - 如何为 py.test 中的所有测试跨模块共享变量

javascript - reactjs 客户端和 flask-socketio 服务器之间的 WebSocket 连接未打开