2017-02-18 38 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