web-dev-qa-db-ja.com

線分上の2つの他の点の間にある点をどのように判断できますか?

各ポイントのx整数とy整数で表される2つのポイント(aおよびbと呼ばれる)を持つ2次元の平面があるとします。

別の点cがaとbで定義された線分上にあるかどうかをどのように判断できますか

私はpythonほとんどを使用しますが、どの言語の例も役立ちます。

84
Paul D. Eden

ダリウス・ベーコンが言うように、外積 of(b-a)と(c-a)が0であるかどうかを確認します。

ただし、cがaとbの間にあるかどうかを知りたいので、(ba)と(ca)のdot productpositiveであることも確認する必要がありますおよびlessは、aとbの間の距離の2乗よりも小さい。

最適化されていない擬似コードの場合:

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
113
Cyrille Ka

これが私がそれをする方法です:

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)
43
Jules

b-ac-a is0の外積:すべてのポイントが同一線上にあることを確認します。ある場合、cの座標がabの間にあるかどうかを確認します。 abがその軸上で分離されている(または両方で同じである)限り、x座標またはy座標のいずれかを使用します。

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

この答えは、以前は3つの更新の混乱でした。それらからの価値のある情報:Brian Hayesの chapter inBeautiful Codeは共線性テスト関数の設計空間をカバーしています-有用ですバックグラウンド。 Vincentの答え これを改善するのに役立ちました。そして、x座標またはy座標のいずれかのみをテストすることを提案したのはHayesでした。元々、コードにはif a.x != b.x elseの代わりにandがありました。

31
Darius Bacon

別のアプローチを次に示します。

  • 2つのポイントを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の間にあります(簡単なチェック)
7
Sridhar Iyer

セグメントの長さは重要ではないため、平方根を使用する必要はありません。精度を失う可能性があるため、避ける必要があります。

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)
6
vincent

C++でコードを指定して、別の方法でこれを実行します。 2つのポイント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成分をこれらの2つの式に代入して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;
}
4
Matthew Henry

線形代数(ベクトルの外積)についての多くの言及があり、これは実(すなわち連続または浮動小数点)空間で機能しますが、2つの点はintegers したがって、近似積は得られますが、外積は正しい解ではありません。

正しい解決策は、2つのポイントの間に Bresenham's Line Algorithm を使用し、3番目のポイントがライン上のポイントの1つであるかどうかを確認することです。アルゴリズムの計算がパフォーマンスに欠けるほどポイントが十分に離れている場合(そして、そのためには本当に大きくなければならないでしょう)掘り下げて最適化を見つけることができると確信しています。

3
cletus

より幾何学的なアプローチを使用して、次の距離を計算します。

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 + bcabと等しいかどうかをテストします。

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

3つの可能性があるためです。

  • 3点は三角形を形成します=> ac + bc> ab
  • それらは同一直線上にあり、cabセグメントの外側にあります=> ac + bc> ab
  • それらは同一直線上にあり、cabセグメントの内側にあります=> ac + bc = ab
3
efotinis

(c-a)と(b-a)の間のスカラー積は、それらの長さの積に等しくなければなりません(これは、ベクトル(c-a)と(b-a)が同じ方向に整列していることを意味します)。さらに、(c-a)の長さは(b-a)の長さ以下でなければなりません。擬似コード:

# 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
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
2
bfcoder

線分上の任意の点(ab)(ここでaおよびbはベクトル) 2つのベクトルの線形結合としてaおよびb

つまり、cが線分上にある場合(ab):

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)
1
Shankster

これが学校でのやり方です。なぜそれが良いアイデアではないのか忘れました。

編集:

@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 __== '__main__':
    import  doctest
    doctest.testmod()
1
jfs

ここにいくつかの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);
    if (dotProduct < 0) return true;
    return false;
}
1
mihahh

c#From http://www.faqs.org/faqs/graphics/algorithms-faq/ -> Subject 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;
        }
1
edid

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;
}
0
kaleidos

勾配が同じであり、ポイントが他のポイントの間にあることを確認するだけではどうですか?

与えられた点(x1、y1)および(x2、y2)(x2> x1)および候補点(a、b)

if(b-y1)/(a-x1)=(y2-y2)/(x2-x1)And x1 <a <x2

(a、b)は(x1、y1)と(x2、y2)の間の行になければなりません

0
Charles Bretana

Vector2Dクラスを使用したC#での回答

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#での演算子のオーバーロードを介したセグメントベクトルの内積です。

重要な点は、無限線への点の投影を利用し、投影のスカラー量が投影がセグメント上にあるかどうかを簡単に示していることを観察することです。スカラー量の境界を調整して、ファジー許容値を使用できます。

投影が境界内にある場合、ポイントから投影までの距離が境界内にあるかどうかをテストします。

クロス積アプローチに勝る利点は、許容値に有意義な値があることです。

0
bradgonesurfing

ジュールの答えの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;
}
0
Tone Škoda

ウェッジとドット積を使用できます:

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
0
Jules