2016-01-31 90 views
5

我在Windows 7 64位中使用Python 3.5 64位,形狀很好的版本爲1.5.13。分割自相交多邊形只能在Python中很好地返回一個多邊形

我有回到我自相交多邊形下面的代碼:

import numpy as np 
from shapely.geometry import Polygon, MultiPolygon 
import matplotlib.pyplot as plt 

x = np.array([ 0.38517325, 0.40859912, 0.43296919, 0.4583215 , 0.4583215 , 
       0.43296919, 0.40859912, 0.38517325, 0.36265506, 0.34100929]) 
y = np.array([ 62.5  , 56.17977528, 39.39698492, 0.  , 
       0.  , 17.34605377, 39.13341671, 60.4180932 , 
       76.02574417, 85.47008547]) 
polygon = Polygon(np.c_[x, y]) 
plt.plot(*polygon.exterior.xy) 

Self-intersecting polygon

這是正確的。然後我嘗試用buffer(0)獲得兩個單獨的多邊形:

split_polygon = polygon.buffer(0) 
plt.plot(*polygon.exterior.xy) 
print(type(split_polygon)) 
plt.fill(*split_polygon.exterior.xy) 

不幸的是,它只返回兩個多邊形的:

Only returned one polygon

誰能請幫助?謝謝!

回答

7

第一步是關閉LineString以製作LinearRing,這是Polygons的組成部分。

from shapely.geometry import LineString, MultiPolygon 
from shapely.ops import polygonize, unary_union 

# original data 
ls = LineString(np.c_[x, y]) 
# closed, non-simple 
lr = LineString(ls.coords[:] + ls.coords[0:1]) 
lr.is_simple # False 

但是,請注意,這是非簡單的,因爲線交叉做領結。 (根據我的經驗,廣泛使用的緩衝區(0)技巧通常不適用於固定領結)。這不適用於LinearRing,所以需要進一步的工作。使之成爲簡單MULTILINESTRING與unary_union

mls = unary_union(lr) 
mls.geom_type # MultiLineString' 

然後使用polygonize找到從線條的多邊形:

for polygon in polygonize(mls): 
    print(polygon) 

或者,如果你想要一個的MultiPolygon幾何:

mp = MultiPolygon(list(polygonize(mls))) 
+0

工程就像一個魅力。非常感謝! –