Lea*_*ner 1 python geometry polygon
我试图找出由两个或多个点组成的给定线段是否在多边形内,这是一张图来帮助捕捉这个想法: 图片帮助可视化问题
我在互联网上找到的所有内容都是接受穿过多边形的线(可能仅在多边形内部或仅穿过多边形)的代码,而不仅仅是在多边形内部,这里是提到的代码:
import numpy as np
import matplotlib.pyplot as plt
import shapely.geometry
import descartes
circle = shapely.geometry.Point(5.0, 0.0).buffer(10.0)
clip_poly = shapely.geometry.Polygon([[-9.5, -2], [2, 2], [3, 4], [-1, 3]])
clipped_shape = circle.difference(clip_poly)
line = shapely.geometry.LineString([[-10, -5], [15, 5]])
line2 = shapely.geometry.LineString([[-10, -5], [-5, 0], [2, 3]])
print 'Blue line intersects clipped shape:', line.intersects(clipped_shape)
print 'Green line intersects clipped shape:', line2.intersects(clipped_shape)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(*np.array(line).T, color='blue', linewidth=3, solid_capstyle='round')
ax.plot(*np.array(line2).T, color='green', linewidth=3, solid_capstyle='round')
ax.add_patch(descartes.PolygonPatch(clipped_shape, fc='blue', alpha=0.5))
ax.axis('equal')
plt.show()
Run Code Online (Sandbox Code Playgroud)
要检查线段是否完全位于多边形内,您可以按照以下两步过程操作:
from shapely.geometry import LineString, Point, Polygon
point_a = Point(7, 2)
point_b = Point(10, 6)
segment = LineString([point_a, point_b])
polygon = Polygon([(1, 0), (4, 1), (5, 4), (3, 5), (3, 2)])
polygon_ext = LineString(list(polygon.exterior.coords))
intersections = polygon_ext.intersection(segment)
Run Code Online (Sandbox Code Playgroud)
if intersections.is_empty:
if polygon.contains(point_a):
print("The segment completely lies within the polygon.")
else:
print("The segment does not lies within the polygon.")
else:
print("Segment-polygon intersections are found.")
Run Code Online (Sandbox Code Playgroud)
对于这种情况,没有找到交点,但线位于多边形之外,如下图所示:

如果我们修改该行,例如:
point_a = Point(2, 3)
point_b = Point(10, 6)
Run Code Online (Sandbox Code Playgroud)
如果:
point_a = Point(2, 0.5)
point_b = Point(3.3, 4)
Run Code Online (Sandbox Code Playgroud)
再次发现交叉点:
最后针对案例:
point_a = Point(2, 3)
point_b = Point(10, 6)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2051 次 |
| 最近记录: |