在Shapely

时间:2016-09-05 22:53:57

标签: python shapely

我试图用两行来分割两个部分的shapely.geometry.Polygon实例。例如,在下面的代码中,polygon是一个环,如果我们用line1line2切割它,我们应该得到两个部分环,一个w / 270度,一个90度。会有一个干净的方法吗?

from shapely.geometry import Point, LineString, Polygon

polygon = Point(0, 0).buffer(2).difference(Point(0, 0).buffer(1))
line1 = LineString([(0, 0), (3, 3)])
line2 = LineString([(0, 0), (3, -3)])

3 个答案:

答案 0 :(得分:6)

肯·沃特福德回答here关于使用bufferdifference来解决问题的方法,其缺点是失去了一点区域。下面的示例代码:

from shapely.geometry import Point, LineString, Polygon

polygon = Point(0, 0).buffer(2).difference(Point(0, 0).buffer(1))
line1 = LineString([(0, 0), (3, 3)])
line2 = LineString([(0, 0), (3, -3)])

line1_pol = line1.buffer(1e-3)
line2_pol = line2.buffer(1e-3)

new_polygon = polygon.difference(line1_pol).difference(line2_pol)

现在可以使用,我有兴趣看看是否还有另一种(可能没有丢失的区域)方法!

答案 1 :(得分:2)

从1.6.0版(2017年8月)开始,Shapely中有一个功能可以将一个几何图形拆分为另一个几何图形,因此不再需要滚动自己的几何图形。请参阅以下文档:shapely.ops.split(geom, splitter)

请注意,此线程上可接受的答案写在 之前,拆分功能在Shapely中-现在已过时了。

答案 2 :(得分:1)

from shapely.ops import linemerge, unary_union, polygonize
from shapely.geometry import LineString, Polygon

# Define the Polygon and the cutting line
line = LineString([(-5, -5), (5, 5)])
polygon = Polygon([(-1, -1), (1, -1), (1, 1), (-1, 1)])


def cut_polygon_by_line(polygon, line):
    merged = linemerge([polygon.boundary, line])
    borders = unary_union(merged)
    polygons = polygonize(borders)
    return list(polygons)

def plot(shapely_objects, figure_path='fig.png'):
    from matplotlib import pyplot as plt
    import geopandas as gpd
    boundary = gpd.GeoSeries(shapely_objects)
    boundary.plot(color=['red', 'green', 'blue', 'yellow', 'yellow'])
    plt.savefig(figure_path)

result = cut_polygon_by_line(polygon, line)
print(result)
plot(result)
print(result[0].intersection(result[1]))

结果是

[<shapely.geometry.polygon.Polygon object at 0x7f50dcf46d68>, 
 <shapely.geometry.polygon.Polygon object at 0x7f50dcf46da0>]
LINESTRING (-1 -1, 1 1)

enter image description here