我想弄清楚如何最好地做到这一点,如果我在2d平面上有一个矢量(由2个点组成的线),我如何确定它是否已通过多边形?
我知道我可以拿出构成多边形的每一条线,看看是否有任何相交但有更好的方法吗?
我已经阅读了这篇文章How can I determine whether a 2D Point is within a Polygon?,它给了我一些想法,看看这个点是否在多边形内,但我需要看看它是否已经过了/相交了它。
我对技术细节并不感兴趣,我可能会在python中实现。
干杯
大卫
答案 0 :(得分:17)
如果你想要一个用于几何操作的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
答案 1 :(得分:2)
当且仅当它穿过其中一条边时,线与多边形交叉(忽略它通过顶点时的情况)。因此,在您的情况下,您只需要测试多边形的所有边缘,并查看是否存在交叉点。
很容易测试边(a, b)
是否与一条线相交。只需按以下格式为您的生产线建立一个线方程
Ax + By + C = 0
然后为点Ax + By + C
和a
计算值b
。如果a
和b
的这些值的符号不同,则边(a, b)
与该线相交。
剩下的就是找到一种方法来处理当线穿过顶点(边缘的端点)时的情况,但这很容易做到。
答案 2 :(得分:1)
如果您对效率不太关心,可以根据多边形上的两个参考点和所有相邻点对测试线交叉。一旦检测到交叉点,就会知道您的线与多边形相交。
一如既往,一个好的起点是维基百科:http://en.wikipedia.org/wiki/Line-line_intersection
所以,让我们来看一个例子
function line-polygon_intersection:
Given points p0, p1 on plane P (your reference line)
Given points q0..qn on plane P (the polygon)
foreach ( qi, qi+1 ) pair of adjacent points:
if line( p0, p1 ) intersects line( qi, qi+1 ):
return true
return false
不要忘记用(qn,q0)循环来关闭poly!
祝你好运!答案 3 :(得分:0)
多边形算法中没有快速点吗?使用一个,您可以确定其中一个点是否在内部,这也可能意味着相交。如果他们都在外面,仍然需要其他方法之一。