已知线段的两端点a、b,求线段外一点到线段的距离

公式推导过程已经不存在

仅剩下代码

贴出来,方便使用

    // 计算点p到直线a,b的距离,OpenCV
    static float distancePointToLineCV(const cv::Point2f& p, const cv::Point2f& a, const cv::Point2f& b)
    {
        float v1 = std::fabs((b.y - a.y) * p.x - (b.x - a.x) * p.y + b.x * a.y - a.x * b.y);
        float v2 = std::sqrtf((b.y - a.y) * (b.y - a.y) + (b.x - a.x) * (b.x - a.x));
        float d = v1 / v2;
        return d;
    }

    // 计算点p到直线a,b的距离,Qt
    static float distancePointToLineQ(const QPointF& p, const QPointF& a, const QPointF& b)
    {
        float v1 = std::fabs((b.y() - a.y()) * p.x() - (b.x() - a.x()) * p.y() + b.x() * a.y() - a.x() * b.y());
        float v2 = std::sqrtf((b.y() - a.y()) * (b.y() - a.y()) + (b.x() - a.x()) * (b.x() - a.x()));
        float d = v1 / v2;
        return d;
    }

提供Qt和OpenCV两种实现方式

你可能感兴趣的:(C++,C++,Qt,OpenCV,向量,数学,几何)