106

假设您有一个二维平面,上面有 2 个点(称为 a 和 b),每个点用 x 整数和 ay 整数表示。

如何确定另一个点 c 是否在由 a 和 b 定义的线段上?

我最常使用 python,但任何语言的示例都会有所帮助。

4

20 回答 20

144

检查 (ba) 和 (ca) 的叉积是否为 0,正如 Darius Bacon 所说,告诉您点 a、b 和 c 是否对齐。

但是,当您想知道 c 是否在 a 和 b 之间时,您还必须检查(ba) 和 (ca)的点积是否为并且小于a 和 b 之间距离的平方。

在非优化伪代码中:

def isBetween(a, b, c):
    crossproduct = (c.y - a.y) * (b.x - a.x) - (c.x - a.x) * (b.y - a.y)

    # compare versus epsilon for floating point values, or != 0 if using integers
    if abs(crossproduct) > epsilon:
        return False

    dotproduct = (c.x - a.x) * (b.x - a.x) + (c.y - a.y)*(b.y - a.y)
    if dotproduct < 0:
        return False

    squaredlengthba = (b.x - a.x)*(b.x - a.x) + (b.y - a.y)*(b.y - a.y)
    if dotproduct > squaredlengthba:
        return False

    return True
于 2008-11-29T22:46:45.333 回答
61

这是我的做法:

def distance(a,b):
    return sqrt((a.x - b.x)**2 + (a.y - b.y)**2)

def is_between(a,c,b):
    return distance(a,c) + distance(c,b) == distance(a,b)
于 2008-11-29T23:39:34.713 回答
37

b-a检查和的叉积是否c-a0:这意味着所有点都共线。如果是,请检查c's 坐标是否在a's 和b's 之间。使用 x 或 y 坐标,只要ab在该轴上是分开的(或者它们在两者上相同)。

def is_on(a, b, c):
    "Return true iff point c intersects the line segment from a to b."
    # (or the degenerate case that all 3 points are coincident)
    return (collinear(a, b, c)
            and (within(a.x, c.x, b.x) if a.x != b.x else 
                 within(a.y, c.y, b.y)))

def collinear(a, b, c):
    "Return true iff a, b, and c all lie on the same line."
    return (b.x - a.x) * (c.y - a.y) == (c.x - a.x) * (b.y - a.y)

def within(p, q, r):
    "Return true iff q is between p and r (inclusive)."
    return p <= q <= r or r <= q <= p

这个答案曾经是三个更新的混乱。他们提供的有价值的信息:Brian Hayes在Beautiful Code中的章节涵盖了共线性测试函数的设计空间——有用的背景。文森特的回答有助于改进这一点。海耶斯建议只测试 x 或 y 坐标中的一个。最初该代码已代替.andif a.x != b.x else

于 2008-11-29T22:40:05.567 回答
9

这是另一种方法:

  • 让我们假设两点是 A (x1,y1) 和 B (x2,y2)
  • 通过这些点的线的方程是 (x-x1)/(y-y1)=(x2-x1)/(y2-y1) .. (只是使斜率相等)

如果满足以下条件,点 C (x3,y3) 将位于 A 和 B 之间:

  • x3,y3 满足上述等式。
  • x3 位于 x1 和 x2 之间,y3 位于 y1 和 y2 之间(简单检查)
于 2008-11-29T23:05:55.093 回答
7

段的长度并不重要,因此不需要使用平方根,应该避免使用,因为我们可能会损失一些精度。

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

class Segment:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def is_between(self, c):
        # Check if slope of a to c is the same as a to b ;
        # that is, when moving from a.x to c.x, c.y must be proportionally
        # increased than it takes to get from a.x to b.x .

        # Then, c.x must be between a.x and b.x, and c.y must be between a.y and b.y.
        # => c is after a and before b, or the opposite
        # that is, the absolute value of cmp(a, b) + cmp(b, c) is either 0 ( 1 + -1 )
        #    or 1 ( c == a or c == b)

        a, b = self.a, self.b             

        return ((b.x - a.x) * (c.y - a.y) == (c.x - a.x) * (b.y - a.y) and 
                abs(cmp(a.x, c.x) + cmp(b.x, c.x)) <= 1 and
                abs(cmp(a.y, c.y) + cmp(b.y, c.y)) <= 1)

一些随机的用法示例:

a = Point(0,0)
b = Point(50,100)
c = Point(25,50)
d = Point(0,8)

print Segment(a,b).is_between(c)
print Segment(a,b).is_between(d)
于 2008-11-30T01:58:59.113 回答
4

使用更几何的方法,计算以下距离:

ab = sqrt((a.x-b.x)**2 + (a.y-b.y)**2)
ac = sqrt((a.x-c.x)**2 + (a.y-c.y)**2)
bc = sqrt((b.x-c.x)**2 + (b.y-c.y)**2)

并测试ac+bc是否等于ab

is_on_segment = abs(ac + bc - ab) < EPSILON

那是因为有三种可能:

  • 三个点形成一个三角形 => ac+bc > ab
  • 它们是共线的并且cab段之外 => ac+bc > ab
  • 它们是共线的,cab段内 => ac+bc = ab
于 2008-11-29T23:14:32.220 回答
4

这是一种不同的方法,使用 C++ 给出的代码。给定两个点 l1 和 l2 将它们之间的线段表示为是微不足道的

l1 + A(l2 - l1)

其中 0 <= A <= 1。如果您对线的向量表示感兴趣,而不仅仅是将其用于此问题。我们可以把它的 x 和 y 分量分开,给出:

x = l1.x + A(l2.x - l1.x)
y = l1.y + A(l2.y - l1.y)

取一个点 (x, y) 并将其 x 和 y 分量代入这两个表达式以求解 A。如果两个表达式中 A 的解相等且 0 <= A <= 1,则该点在线。因为求解 A 需要除法,当线段是水平或垂直时,有些特殊情况需要处理以停止除以零。最终解决方案如下:

// Vec2 is a simple x/y struct - it could very well be named Point for this use

bool isBetween(double a, double b, double c) {
    // return if c is between a and b
    double larger = (a >= b) ? a : b;
    double smaller = (a != larger) ? a : b;

    return c <= larger && c >= smaller;
}

bool pointOnLine(Vec2<double> p, Vec2<double> l1, Vec2<double> l2) {
    if(l2.x - l1.x == 0) return isBetween(l1.y, l2.y, p.y); // vertical line
    if(l2.y - l1.y == 0) return isBetween(l1.x, l2.x, p.x); // horizontal line

    double Ax = (p.x - l1.x) / (l2.x - l1.x);
    double Ay = (p.y - l1.y) / (l2.y - l1.y);

    // We want Ax == Ay, so check if the difference is very small (floating
    // point comparison is fun!)

    return fabs(Ax - Ay) < 0.000001 && Ax >= 0.0 && Ax <= 1.0;
}
于 2012-11-10T16:48:59.220 回答
4

您可以使用楔形和点积:

def dot(v,w): return v.x*w.x + v.y*w.y
def wedge(v,w): return v.x*w.y - v.y*w.x

def is_between(a,b,c):
   v = a - b
   w = b - c
   return wedge(v,w) == 0 and dot(v,w) > 0
于 2015-03-27T13:34:06.500 回答
3

好的,很多提到线性代数(向量的叉积),这在真实(即连续或浮点)空间中有效,但问题特别指出这两个点表示为整数,因此叉积不正确解决方案虽然它可以给出一个近似的解决方案。

正确的解决方案是在两点之间使用Bresenham 的直线算法,并查看第三个点是否是直线上的点之一。如果这些点距离足够远以至于计算算法是无效的(并且它必须非常大才能成为这种情况),我相信你可以四处挖掘并找到优化。

于 2008-11-30T08:56:44.260 回答
2

(ca) 和 (ba) 之间的标量积必须等于它们长度的乘积(这意味着向量 (ca) 和 (ba) 对齐且方向相同)。此外,(ca)的长度必须小于或等于(ba)的长度。伪代码:

# epsilon = small constant

def isBetween(a, b, c):
    lengthca2  = (c.x - a.x)*(c.x - a.x) + (c.y - a.y)*(c.y - a.y)
    lengthba2  = (b.x - a.x)*(b.x - a.x) + (b.y - a.y)*(b.y - a.y)
    if lengthca2 > lengthba2: return False
    dotproduct = (c.x - a.x)*(b.x - a.x) + (c.y - a.y)*(b.y - a.y)
    if dotproduct < 0.0: return False
    if abs(dotproduct*dotproduct - lengthca2*lengthba2) > epsilon: return False 
    return True
于 2008-11-29T22:51:43.063 回答
2

我需要在 html5 画布中使用 javascript 来检测用户光标是否在某行上方或附近。于是我将 Darius Bacon 给出的答案修改为coffeescript:

is_on = (a,b,c) ->
    # "Return true if point c intersects the line segment from a to b."
    # (or the degenerate case that all 3 points are coincident)
    return (collinear(a,b,c) and withincheck(a,b,c))

withincheck = (a,b,c) ->
    if a[0] != b[0]
        within(a[0],c[0],b[0]) 
    else 
        within(a[1],c[1],b[1])

collinear = (a,b,c) ->
    # "Return true if a, b, and c all lie on the same line."
    ((b[0]-a[0])*(c[1]-a[1]) < (c[0]-a[0])*(b[1]-a[1]) + 1000) and ((b[0]-a[0])*(c[1]-a[1]) > (c[0]-a[0])*(b[1]-a[1]) - 1000)

within = (p,q,r) ->
    # "Return true if q is between p and r (inclusive)."
    p <= q <= r or r <= q <= p
于 2012-07-20T23:08:11.937 回答
1

以下是我在学校的做法。我忘了为什么这不是一个好主意。

编辑:

@Darius Bacon:引用了一本“美丽的代码”一书,其中解释了为什么下面的代码不是一个好主意。

#!/usr/bin/env python
from __future__ import division

epsilon = 1e-6

class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

class LineSegment:
    """
    >>> ls = LineSegment(Point(0,0), Point(2,4))
    >>> Point(1, 2) in ls
    True
    >>> Point(.5, 1) in ls
    True
    >>> Point(.5, 1.1) in ls
    False
    >>> Point(-1, -2) in ls
    False
    >>> Point(.1, 0.20000001) in ls
    True
    >>> Point(.1, 0.2001) in ls
    False
    >>> ls = LineSegment(Point(1, 1), Point(3, 5))
    >>> Point(2, 3) in ls
    True
    >>> Point(1.5, 2) in ls
    True
    >>> Point(0, -1) in ls
    False
    >>> ls = LineSegment(Point(1, 2), Point(1, 10))
    >>> Point(1, 6) in ls
    True
    >>> Point(1, 1) in ls
    False
    >>> Point(2, 6) in ls 
    False
    >>> ls = LineSegment(Point(-1, 10), Point(5, 10))
    >>> Point(3, 10) in ls
    True
    >>> Point(6, 10) in ls
    False
    >>> Point(5, 10) in ls
    True
    >>> Point(3, 11) in ls
    False
    """
    def __init__(self, a, b):
        if a.x > b.x:
            a, b = b, a
        (self.x0, self.y0, self.x1, self.y1) = (a.x, a.y, b.x, b.y)
        self.slope = (self.y1 - self.y0) / (self.x1 - self.x0) if self.x1 != self.x0 else None

    def __contains__(self, c):
        return (self.x0 <= c.x <= self.x1 and
                min(self.y0, self.y1) <= c.y <= max(self.y0, self.y1) and
                (not self.slope or -epsilon < (c.y - self.y(c.x)) < epsilon))

    def y(self, x):        
        return self.slope * (x - self.x0) + self.y0

if __name__ == '__main__':
    import  doctest
    doctest.testmod()
于 2008-11-30T00:45:56.000 回答
1

线段 ( a , b ) 上的任何点(其中ab是向量)都可以表示为两个向量ab的线性组合

换句话说,如果c位于线段 ( a , b ) 上:

c = ma + (1 - m)b, where 0 <= m <= 1

求解m,我们得到:

m = (c.x - b.x)/(a.x - b.x) = (c.y - b.y)/(a.y - b.y)

所以,我们的测试变成了(在 Python 中):

def is_on(a, b, c):
    """Is c on the line segment ab?"""

    def _is_zero( val ):
        return -epsilon < val < epsilon

    x1 = a.x - b.x
    x2 = c.x - b.x
    y1 = a.y - b.y
    y2 = c.y - b.y

    if _is_zero(x1) and _is_zero(y1):
        # a and b are the same point:
        # so check that c is the same as a and b
        return _is_zero(x2) and _is_zero(y2)

    if _is_zero(x1):
        # a and b are on same vertical line
        m2 = y2 * 1.0 / y1
        return _is_zero(x2) and 0 <= m2 <= 1
    elif _is_zero(y1):
        # a and b are on same horizontal line
        m1 = x2 * 1.0 / x1
        return _is_zero(y2) and 0 <= m1 <= 1
    else:
        m1 = x2 * 1.0 / x1
        if m1 < 0 or m1 > 1:
            return False
        m2 = y2 * 1.0 / y1
        return _is_zero(m2 - m1)
于 2011-10-27T08:42:26.343 回答
1

c# 来自http://www.faqs.org/faqs/graphics/algorithms-faq/ -> 主题 1.02:如何找到点到线的距离?

Boolean Contains(PointF from, PointF to, PointF pt, double epsilon)
        {

            double segmentLengthSqr = (to.X - from.X) * (to.X - from.X) + (to.Y - from.Y) * (to.Y - from.Y);
            double r = ((pt.X - from.X) * (to.X - from.X) + (pt.Y - from.Y) * (to.Y - from.Y)) / segmentLengthSqr;
            if(r<0 || r>1) return false;
            double sl = ((from.Y - pt.Y) * (to.X - from.X) - (from.X - pt.X) * (to.Y - from.Y)) / System.Math.Sqrt(segmentLengthSqr);
            return -epsilon <= sl && sl <= epsilon;
        }
于 2012-02-10T08:16:16.110 回答
1

这是一些对我有用的Java代码:

boolean liesOnSegment(Coordinate a, Coordinate b, Coordinate c) {
        
    double dotProduct = (c.x - a.x) * (c.x - b.x) + (c.y - a.y) * (c.y - b.y);
    return (dotProduct < 0);
}
于 2013-10-28T11:15:30.643 回答
1

C# 中使用 Vector2D 类的答案

public static bool IsOnSegment(this Segment2D @this, Point2D c, double tolerance)
{
     var distanceSquared = tolerance*tolerance;
     // Start of segment to test point vector
     var v = new Vector2D( @this.P0, c ).To3D();
     // Segment vector
     var s = new Vector2D( @this.P0, @this.P1 ).To3D();
     // Dot product of s
     var ss = s*s;
     // k is the scalar we multiply s by to get the projection of c onto s
     // where we assume s is an infinte line
     var k = v*s/ss;
     // Convert our tolerance to the units of the scalar quanity k
     var kd = tolerance / Math.Sqrt( ss );
     // Check that the projection is within the bounds
     if (k <= -kd || k >= (1+kd))
     {
        return false;
     }
     // Find the projection point
     var p = k*s;
     // Find the vector between test point and it's projection
     var vp = (v - p);
     // Check the distance is within tolerance.
     return vp * vp < distanceSquared;
}

注意

s * s

是通过 C# 中的运算符重载得到的段向量的点积

关键是利用点在无限线上的投影,并观察投影的标量告诉我们投影是否在线段上。我们可以调整标量的范围以使用模糊容差。

如果投影在范围内,我们只需测试从点到投影的距离是否在范围内。

与叉积方法相比的好处是容差具有有意义的值。

于 2014-01-30T10:34:14.683 回答
1

Jules 回答的 C# 版本:

public static double CalcDistanceBetween2Points(double x1, double y1, double x2, double y2)
{
    return Math.Sqrt(Math.Pow (x1-x2, 2) + Math.Pow (y1-y2, 2));
}

public static bool PointLinesOnLine (double x, double y, double x1, double y1, double x2, double y2, double allowedDistanceDifference)
{
    double dist1 = CalcDistanceBetween2Points(x, y, x1, y1);
    double dist2 = CalcDistanceBetween2Points(x, y, x2, y2);
    double dist3 = CalcDistanceBetween2Points(x1, y1, x2, y2);
    return Math.Abs(dist3 - (dist1 + dist2)) <= allowedDistanceDifference;
}
于 2019-07-02T10:09:14.970 回答
0

如何确保斜率相同并且点在其他点之间?

给定点 (x1, y1) 和 (x2, y2) ( x2 > x1) 和候选点 (a,b)

如果 (b-y1) / (a-x1) = (y2-y2) / (x2-x1) 且 x1 < a < x2

那么 (a,b) 必须在 (x1,y1) 和 (x2, y2) 之间

于 2008-11-30T20:52:30.557 回答
0

这是我在 Unity 中使用 C# 的解决方案。

private bool _isPointOnLine( Vector2 ptLineStart, Vector2 ptLineEnd, Vector2 ptPoint )
{
    bool bRes = false;
    if((Mathf.Approximately(ptPoint.x, ptLineStart.x) || Mathf.Approximately(ptPoint.x, ptLineEnd.x)))
    {
        if(ptPoint.y > ptLineStart.y && ptPoint.y < ptLineEnd.y)
        {
            bRes = true;
        }
    }
    else if((Mathf.Approximately(ptPoint.y, ptLineStart.y) || Mathf.Approximately(ptPoint.y, ptLineEnd.y)))
    {
        if(ptPoint.x > ptLineStart.x && ptPoint.x < ptLineEnd.x)
        {
            bRes = true;
        }
    }
    return bRes;
}
于 2017-10-19T02:50:58.153 回答
0

您可以通过使用点坐标求解该线段的线方程来做到这一点,您将知道该点是否在线上,然后检查线段的边界以了解它是在其内部还是外部。您可以应用一些阈值,因为它位于空间中的某个位置,很可能由浮点值定义,并且您不能达到确切的阈值。php中的示例

function getLineDefinition($p1=array(0,0), $p2=array(0,0)){
    
    $k = ($p1[1]-$p2[1])/($p1[0]-$p2[0]);
    $q = $p1[1]-$k*$p1[0];
    
    return array($k, $q);
    
}

function isPointOnLineSegment($line=array(array(0,0),array(0,0)), $pt=array(0,0)){
    
    // GET THE LINE DEFINITION y = k.x + q AS array(k, q) 
    $def = getLineDefinition($line[0], $line[1]);
    
    // use the line definition to find y for the x of your point
    $y = $def[0]*$pt[0]+$def[1];

    $yMin = min($line[0][1], $line[1][1]);
    $yMax = max($line[0][1], $line[1][1]);

    // exclude y values that are outside this segments bounds
    if($y>$yMax || $y<$yMin) return false;
    
    // calculate the difference of your points y value from the reference value calculated from lines definition 
    // in ideal cases this would equal 0 but we are dealing with floating point values so we need some threshold value not to lose results
    // this is up to you to fine tune
    $diff = abs($pt[1]-$y);
    
    $thr = 0.000001;
    
    return $diff<=$thr;
    
}
于 2020-08-10T15:27:56.773 回答