python - 从多边形列表中减去内环

标签 python gis polygon shapely

我有一个很大的多边形列表(>10^6),其中大多数是不相交的,但其中一些多边形是另一个多边形的孔(〜10^3情况)。这里用一张图片来解释这个问题,较小的多边形是较大多边形中的一个洞,但两者都是多边形列表中的独立多边形。 A large polygon with smaller polygon on the inside.

现在我想有效地确定哪些多边形是孔并减去孔,即减去完全位于另一个多边形内部的较小多边形并返回“已清理”多边形的列表。一对孔和父多边形应该像这样进行变换(所以基本上从父多边形中减去孔): enter image description here

Stackoverflow 和 gis.stackexchange.com 上有很多类似的问题,但我还没有找到真正解决此问题的问题。以下是一些相关问题: 1.https://gis.stackexchange.com/questions/5405/using-shapely-translating-between-polygons-and-multipolygons 2.https://gis.stackexchange.com/questions/319546/converting-list-of-polygons-to-multipolygon-using-shapely

这是一个示例代码。

from shapely.geometry import Point
from shapely.geometry import MultiPolygon
from shapely.ops import unary_union
import numpy as np

#Generate a list of polygons, where some are holes in others; 
def generateRandomPolygons(polygonCount = 100, areaDimension = 1000, holeProbability = 0.5):
    pl = []
    radiusLarge = 2 #In the real dataset the size of polygons can vary
    radiusSmall = 1 #Size of holes can also vary

    for i in range(polygonCount):
        x, y = np.random.randint(0,areaDimension,(2))
        rn1 = np.random.random(1)
        pl.append(Point(x, y).buffer(radiusLarge))
        if rn1 < holeProbability: #With a holeProbability add a hole in the large polygon that was just added to the list
            pl.append(Point(x, y).buffer(radiusSmall))
    return pl

polygons = generateRandomPolygons()
print(len(pl))

输出如下所示:enter image description here

现在如何创建一个新的多边形列表并删除孔。 Shapely 提供了从一个多边形减去另一个多边形的函数( difference ),但是对于多边形列表是否有类似的函数(可能类似于 unary_union 但删除了重叠)?另一种方法是如何有效地确定哪些是孔,然后从较大的多边形中减去它们?

最佳答案

你的问题是你不知道哪些是“洞”,对吧?要“有效地确定哪些多边形是孔”,您可以使用 rtree加快交叉点检查速度:

from rtree.index import Index

# create an rtree for efficient spatial queries
rtree = Index((i, p.bounds, None) for i, p in enumerate(polygons))
donuts = []

for i, this_poly in enumerate(polygons):
    # loop over indices of approximately intersecting polygons
    for j in rtree.intersection(this_poly.bounds):
        # ignore the intersection of this polygon with itself
        if i == j:
            continue
        other_poly = polygons[j]
        # ensure the polygon fully contains our match
        if this_poly.contains(other_poly):
            donut = this_poly.difference(other_poly)
            donuts.append(donut)
            break  # quit searching

print(len(donuts))

关于python - 从多边形列表中减去内环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59106740/

相关文章:

python - 我怎样才能同时在一个可迭代的python上有多个迭代器?

gis - NoSQL 和空间数据

gis - 在 netlogo 中使用 2 张 map

django - 使用来自十进制坐标的 GeoDjango 在 PostgreSQL 数据库中添加一个点

javascript - 检测折线是否与多边形相交

python - 使用 Python Pandas 处理双 for 循环

python - RESTful API 中未处理的异常没有得到 jsonify'ed

python - 在 Python 中使用坐标和 map 图像绘制网格

用于计算任意多面体的表面积和体积的Python库

opengl-es - 使用 OpenGL 着色器绘制多边形的边缘