every blog every motto: You can do more than you think.
https://blog.csdn.net/weixin_39190382?type=blog
0. 前言
python 求直线与多边形交点并显示
1. 正文
1.1 步骤
python
import matplotlib.pyplot as plt
from shapely.geometry import LineString, Polygon
导入所需的模块和函数:
python
import matplotlib.pyplot as plt
from shapely.geometry import LineString, Polygon
创建直线对象和多边形对象:
python
line = LineString([(x1, y1), (x2, y2)])
polygon = Polygon([(x3, y3), (x4, y4), ..., (xn, yn)])
提取多边形的边界作为LineString对象:
python
boundary = polygon.boundary
计算直线与多边形边界的交点:
python
intersection = line.intersection(boundary)
将交点转换为MultiPoint对象(如果有多个交点)或Point对象(如果只有一个交点):
python
if intersection.geom_type == 'MultiPoint':
intersection_points = list(intersection)
else:
intersection_points = [intersection]
绘制多边形、直线和交点
python
fig, ax = plt.subplots()
ax.plot(*boundary.xy, label='Polygon')
ax.plot(*line.xy, label='Line')
for point in intersection_points:
ax.plot(*point.xy, 'ro', label='Intersection')
ax.legend()
plt.show()
1.2 完整代码
python
import matplotlib.pyplot as plt
from shapely.geometry import LineString, Polygon
# 创建直线对象和多边形对象
line = LineString([(0, 0), (3, 5)])
polygon = Polygon([(1, 1), (1, 4), (4, 4), (4, 1)])
# 提取直线的起点和终点坐标以及多边形的边界坐标
line_coords = line.xy
boundary_coords = polygon.boundary.xy
# 计算直线与多边形边界的交点
boundary = polygon.boundary
intersection = line.intersection(boundary)
if intersection.geom_type == 'MultiPoint':
intersection_points = list(intersection)
else:
intersection_points = [intersection]
fig, ax = plt.subplots()
ax.plot(*boundary.xy, label='Polygon')
ax.plot(*line.xy, label='Line')
for point in intersection_points:
ax.plot(*point.xy, 'ro', label='Intersection')
ax.legend()
plt.show()