当前位置:   article > 正文

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

python shapely 直线与多边形交点

every blog every motto: You can do more than you think.
https://blog.csdn.net/weixin_39190382?type=blog

0. 前言

python 求直线与多边形交点并显示

1. 正文

1.1 步骤

import matplotlib.pyplot as plt
from shapely.geometry import LineString, Polygon

  • 1
  • 2
  • 3

导入所需的模块和函数:

import matplotlib.pyplot as plt
from shapely.geometry import LineString, Polygon
  • 1
  • 2

创建直线对象和多边形对象:

line = LineString([(x1, y1), (x2, y2)])
polygon = Polygon([(x3, y3), (x4, y4), ..., (xn, yn)])
  • 1
  • 2

提取多边形的边界作为LineString对象:

boundary = polygon.boundary
  • 1

计算直线与多边形边界的交点:

intersection = line.intersection(boundary)
  • 1

将交点转换为MultiPoint对象(如果有多个交点)或Point对象(如果只有一个交点):

if intersection.geom_type == 'MultiPoint':
    intersection_points = list(intersection)
else:
    intersection_points = [intersection]
  • 1
  • 2
  • 3
  • 4

绘制多边形、直线和交点

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
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

1.2 完整代码

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()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/天景科技苑/article/detail/979275
推荐阅读
相关标签
  

闽ICP备14008679号