python - 确定线段是否与多边形相交

标签 python geometry polygon

如果我在 2D 平面上有一个矢量(一条由 2 个点组成的线),我如何确定它是否穿过多边形?

我知道我可以获取构成多边形的每条线,看看是否有任何相交,但有没有更好的方法?

我读过这篇文章 How can I determine whether a 2D Point is within a Polygon?这给了我一些想法来查看该点是否在多边形内,但我需要查看它是否已经通过/与它相交。

最佳答案

如果你想要一个用于几何操作的 python 库,请查看 shapely .它使这变得像 someline.intersects(somepolygon) 一样简单。

这是一个关于交集、缓冲区和裁剪的简单示例(有一个漂亮的图......我正在使用 descartes 轻松地将形状优美的多边形转换为 matplotlib 补丁。)。

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()

这会产生:

Blue line intersects clipped shape: True
Green line intersects clipped shape: False

enter image description here

关于python - 确定线段是否与多边形相交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6050392/

相关文章:

python - Apache Storm Python Bolt 中的 "No module named"错误

javascript - d3.js 在 Jupyter Notebook 中加载版本 3 与版本 4

python - 如何找到给定值将被另一个系列达到/交叉的索引?

Java 递归三角形站在尖端

algorithm - 无孔多边形并集

python - 为 Python 函数参数提供额外装饰/元数据的好方法是什么?

c++ - 给定纬度/经度对 vector ,我如何创建一个 vector ,使点之间的距离小于或等于某个常数?

在一个区域中拟合二维多边形的算法?

算法或生成器或示例道路车道/和网络

geometry - 找到点组中最大可能的多边形