2017-02-18 69 views
1

我试图创建区域的多边形,他们触摸的条件。在我的示例中,我有一个包含382个多边形的示例数据集,需要将它们组合在一起(但完整数据集包含6355个多边形)。 (我会展示一张图片,但是我没有足够的声望去做这件事..)蟒蛇区域与多边形的性能增长

我虽然做了这种蛮力,但当然这需要很长时间,并不是非常优化。

def groupBuildings(blds): 
    # blds is a list with shapely polygons 
    groups = [] 
    for bld in blds: 
     group = [] 
     group.append(bld) 
     for other in blds: 
      for any in group: 
       if any != other and any.intersects(other): 
        group.append(other) 
     groups.append(group) 
    return groups 

我了解了地区的发展并认为这将是一个可能的解决方案,但仍然表现糟糕。我在下面的方式来实现这一点:

def groupBuildings(blds): 
    # blds is a list with shapely polygons 
    others = blds 
    groups = [] 
    while blds != []: 
     done = [] 
     group = [] 
     first = blds.pop(0) 
     done.append(first) 
     group.append(first) 
     for other in others: 
      if (other in blds) and first.touches(other): 
       group.append(other) 
       blds.remove(other) 

return groups 

但我觉得这里的问题是,我没有任何最近的邻居,所以我还是要每一个建筑遍历两次。

所以我的问题是:最近的邻居对区域增长至关重要?还是有另一种有效的方法呢?

回答

1

最好用shapely.ops.cascaded_union()docs here)。

from shapely.geometry import Point, Polygon, MultiPolygon 
from shapely.ops import cascaded_union 
import numpy as np 
polygons = [Point(200*x,200*y).buffer(b) for x,y,b in np.random.random((6000,3))] 
multi = MultiPolygon(polygons) 
unioned = cascaded_union(multi) 

%%timeit 
unioned = cascaded_union(multi) 
# 2.8 seconds for me