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

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()
相关推荐
To_OC17 小时前
LC 207 课程表:刚学图论那会儿,我连这是拓扑排序都没看出来
javascript·算法·leetcode
To_OC17 小时前
LC 208 实现 Trie 前缀树:曾被名字劝退,写完发现是送分题
javascript·算法·leetcode
BadBadBad__AK19 小时前
线段树维护区间 k 次方和
c++·数学·算法·stl
_清歌1 天前
DSpark 深度解读:DeepSeek-V4 如何用「半自回归」把推理速度提升 85%
算法
统计实现局1 天前
SVD 的三步走:双对角化、Givens 收敛、排序
算法
躬行见万象1 天前
《VLA 系列》UniLab 强化训练 | G1 机器人 |复现
算法
统计实现局1 天前
对称不定分解(Bunch-Kaufman):为什么 Cholesky 不够用
算法
统计实现局1 天前
dqrsl 拆解:拿着 QR 结果能算出哪 5 种东西
算法
统计实现局1 天前
为什么 Cholesky 求逆比 Gauss-Jordan 快一倍——行列式溢出防护详
算法