How to calculate ray-line segment intersection preferably in OpenCV? And get its intersection points and distance from origin?

。_饼干妹妹 提交于 2019-12-23 04:45:24

问题


I have 4 lines segment, A, B, C and D. Each line is represented as two points. Eg. line A is represented as point A1 and point A2.

What I want is

  1. point X, which is the point where line A ray intersect with line B
  2. distance between X and A1(origin)

When testing for intersection, line A ray should not

  1. intersect with line segment D
  2. intersect with line segment C

How do I do this?


回答1:


Finally got it working on OpenCV C++. Based on this 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;
}

Should be self explanatory.



来源:https://stackoverflow.com/questions/53893292/how-to-calculate-ray-line-segment-intersection-preferably-in-opencv-and-get-its

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!