代码之家  ›  专栏  ›  技术社区  ›  Syaiful Nizam Yahya

如何在OpenCV中更好地计算射线线段相交?得到它的交点和距离原点的距离?

  •  0
  • Syaiful Nizam Yahya  · 技术社区  · 6 年前

    我有4条线段,A、B、C和D。每条线表示为两点。线A表示为点A1和点A2。

    enter image description here

    1. 点X,即线A射线与线B相交的点

    测试相交时,不应使用线A射线

    1. 与线段C相交

    我该怎么做?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Syaiful Nizam Yahya    6 年前

    最终使之在OpenCV C++上运行。基于此, https://stackoverflow.com/a/32146853/457030 .

    // return the distance of ray origin to intersection point
    double GetRayToLineSegmentIntersection(Point2f rayOrigin, Point2f rayDirection, Point2f point1, Point2f point2)
    {
        Point2f v1 = rayOrigin - point1;
        Point2f v2 = point2 - point1;
        Point2f v3 = Point2f(-rayDirection.y, rayDirection.x);
    
        float dot = v2.dot(v3);
        if (abs(dot) < 0.000001)
            return -1.0f;
    
        float t1 = v2.cross(v1) / dot;
        float t2 = v1.dot(v3) / dot;
    
        if (t1 >= 0.0 && (t2 >= 0.0 && t2 <= 1.0))
            return t1;
    
        return -1.0f;
    }
    
    // use this to normalize rayDirection
    Point2f NormalizeVector(Point2f pt)
    {
        float length = sqrt(pt.x*pt.x + pt.y*pt.y);
        pt = pt / length;
        return pt;
    }
    
    // gets the intersection point
    Point2f GetRayIntersectionPoint(Point2f origin, Point2f vector, double distance)
    {
        Point2f pt;
    
        pt.x = origin.x + vector.x * distance;
        pt.y = origin.y + vector.y * distance;
    
        return pt;
    }