在线形穿过多边形的每个点处进行分割

时间:2019-02-03 00:13:20

标签: python geometry shapely shapely.geometry

我有一个跨越各种多边形的线串,存储为GeoJsons。我想将线分成每个多边形区域内的各个部分。但是,我还无法实现这一目标。这是到目前为止我可以重现的示例:

from shapely.geometry import Point, LineString, Polygon
from shapely.ops import split
from matplotlib import pyplot as plt

poly = {
    'type': "Feature",
    'geometry': {
        "type": "Polygon",
        "coordinates": ([(2,2),(2,4),(4,4),(4,2)]),
    },
    'properties': {
        'id': 'A'
    }
}

line = {
    'type': "Feature",
    'geometry': {
        "type": "Linestring",
        "coordinates": ([(3,3),(5,1)]),
    },
    'properties': {
        'id': 'A'
    }
}

poly = Polygon(poly['geometry']['coordinates'])
line = LineString(line['geometry']['coordinates'])

x,y = poly.exterior.xy
x2,y2 = line.coords

plt.plot(x, y, x2, y2)
plt.show()

此代码将生成以下带有线串的方形多边形: enter image description here

然后我尝试通过多边形分割线,如下所示:

new_lines = split(line, poly)

但是我得到以下输出,看起来似乎不正确:

GEOMETRYCOLLECTION (LINESTRING (3 3, 4 2), LINESTRING (4 2, 5 1))

我期望有3条线,其中1条存在于方形多边形内,然后2条分别存在于多边形外。

1 个答案:

答案 0 :(得分:0)

似乎split可以按预期工作,但是线的坐标以一种误导性的方式绘制-应该像多边形一样使用def farey(n): return (n*(n+3))//2 - sum(farey(n//k) for k in range(2, n+1)) 来获得线.xyxs

ys

image with original coords

image with expected coords

from shapely.geometry import Point, LineString, Polygon
from shapely.ops import split
from matplotlib import pyplot as plt

poly = Polygon([(2,2),(2,4),(4,4),(4,2)])
original_line = LineString([(3,3),(5,1)])
line = LineString([(3,1), (3,5)])
x, y = poly.exterior.xy
x2, y2 = line.xy
x3, y3 = original_line.xy

plt.plot(x, y, x2, y2)
plt.show()

plt.plot(x, y, x3, y3)
plt.show()