我有大量的多边形列表(> 10 ^ 6),其中大多数是不相交的,但是其中一些多边形是另一个多边形的孔(〜10 ^ 3种情况)。这里是一个解释问题的图像,较小的多边形是较大的多边形中的孔,但在多边形列表中都是独立的多边形。
现在,我想有效地确定哪些多边形是孔并减去孔,即减去完全位于另一个多边形内部的较小多边形,并返回“已清理”多边形的列表。一对孔和父多边形应按以下方式进行转换(因此基本上是从父级减去孔):
在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))
现在如何在删除孔的情况下创建多边形的新列表。 Shapely提供了从一个多边形中减去另一个多边形(difference)的功能,但是多边形列表是否有类似的功能(也许像unary_union之类的东西,但是重叠部分被删除了)?或者,如何有效地确定哪些是孔,然后从较大的多边形中减去它们?
答案 0 :(得分:6)
您的问题是您不知道哪些是“漏洞”,对吗?要“有效地确定哪些多边形是孔”,可以使用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))