【问题标题】:How do I find the intersection of two line segments?如何找到两条线段的交点?
【发布时间】:2014-03-15 00:01:58
【问题描述】:

假设我们有两个有限线段,每个线段由两个点(在两个空间中)定义。我想找到一种方法来获得这两条线的交点。最终,我想将其扩展到连接线段集。

我在这里找到了一个很好的解决方案:Python - matplotlib: find intersection of lineplots。但是,这依赖于 scipy,我认为这需要 BLAS,出于不同的原因,我想避免这种情况。

matplotlib 有一个名为 Path 的模块,它有一个 intersects_path() 函数 (http://matplotlib.org/api/path_api.html#matplotlib.path.Path.intersects_path),它返回 true 或 false 是否存在交叉点,但不是我需要的特定位置。

有没有人知道一个干净的方法?

我想出的任何解决方案都很冗长,如果已经存在解决方案,我真的不想重新发明轮子。

谢谢!

【问题讨论】:

  • 这应该是微不足道的,不是吗? 1) 使用端点,求解每条线段的slopey-intercept。 2)一旦你知道每条线的方程,求解交点 3)检查该交点是否位于两条线(而不是线段之外)
  • 正如 Cyber​​ 所说,这应该是微不足道的。看看这里,看你懂不懂stackoverflow.com/questions/4543506/…
  • shapely 可以很快做到这一点,pypi.python.org/pypi/Shapely
  • Shapely 正是我不想重新发明的轮子。很棒的包裹。谢谢!

标签: python matplotlib


【解决方案1】:

为了完成,我想我会发布我使用的最终解决方案。

使用 Shapely (https://pypi.python.org/pypi/Shapely) 代码看起来很简单:

from shapely.geometry import LineString

line1 = LineString([(0,0), (1,0), (1,1)])
line2 = LineString([(0,1), (1,1)])

print(line1.intersection(line2))

返回:

POINT (1 1)

这样做的好处是它可以无缝处理单点相交和线段相交,并且可以将相同的技术应用于更复杂的对象。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-26
  • 2021-10-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多