【交点】直线与多边形相交显示

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()
相关推荐
_Itachi__7 分钟前
LeetCode 热题 100 73. 矩阵置零
算法·leetcode·矩阵
夏末秋也凉29 分钟前
力扣-贪心-376 摆动序列
算法·leetcode
Orange--Lin1 小时前
【用deepseek和chatgpt做算法竞赛】——还得DeepSeek来 -Minimum Cost Trees_5
人工智能·算法·chatgpt
01_1 小时前
力扣hot100 ——搜索二维矩阵 || m+n复杂度优化解法
算法·leetcode·矩阵
SylviaW081 小时前
python-leetcode 35.二叉树的中序遍历
算法·leetcode·职场和发展
篮l球场1 小时前
LeetCodehot 力扣热题100
算法·leetcode·职场和发展
pzx_0011 小时前
【机器学习】K折交叉验证(K-Fold Cross-Validation)
人工智能·深度学习·算法·机器学习
BanLul1 小时前
进程与线程 (三)——线程间通信
c语言·开发语言·算法
qy发大财2 小时前
分发糖果(力扣135)
数据结构·算法·leetcode