如何检查点是否在线下?
我有以下数据:
Line [ {x1,y1}, {x2,y2} ]
Points {xA,yA}, {xB,yB} ...
我需要在python中编写一个小算法来检测线的一侧和另一侧的点。
谢谢
您可以尝试使用交叉产品 - http://en.wikipedia.org/wiki/Cross_product。
v1 = {x2-x1, y2-y1} # Vector 1
v2 = {x2-xA, y2-yA} # Vector 1
xp = v1.x*v2.y - v1.y*v2.x # Cross product
if xp > 0:
print 'on one side'
elif xp < 0:
print 'on the other'
else:
print 'on the same line!'
您需要校准每个方面的内容。如果您希望它在“下方”或“上方”,则需要确保线上的点水平排序。
我没有测试过这个。
编辑我最初放入点积公式。 :○
您可以尝试使用交叉产品,但诀窍是如何选择形成矢量的点,在这里我选择距离点最近的点,假设我得到了pointA(你可以公平地循环点来计算从循环点到Line的距离) ):
v1 = {x2-x1, y2-y1} # Vector 1
v2 = {xA-x1, yA-y1} # Vector 2
cross_product = v1.x*v2.y - v1.y*v2.x
if cross_product > 0:
print 'pointA is on the counter-clockwise side of line'
elif xp < 0:
print 'pointA is on the clockwise side of line'
else:
print 'pointA is exactly on the line'