直线拟合

bool lineFit(const std::vector &points, double &a, double &b, double &c)

{

    int size = points.size();

    if(size < 2)

    {

        a = 0;

        b = 0;

        c = 0;

        return false;

    }

    double x_mean = 0;

    double y_mean = 0;

    for(int i = 0; i < size; i++)

    {

        x_mean += points[i].x;

        y_mean += points[i].y;

    }

    x_mean /= size;

    y_mean /= size; //至此,计算出了 x y 的均值    double Dxx = 0, Dxy = 0, Dyy = 0;

    for(int i = 0; i < size; i++)

    {

        Dxx += (points[i].x - x_mean) * (points[i].x - x_mean);

        Dxy += (points[i].x - x_mean) * (points[i].y - y_mean);

        Dyy += (points[i].y - y_mean) * (points[i].y - y_mean);

    }

    double lambda = ( (Dxx + Dyy) - sqrt( (Dxx - Dyy) * (Dxx - Dyy) + 4 * Dxy * Dxy) ) / 2.0;

    double den = sqrt( Dxy * Dxy + (lambda - Dxx) * (lambda - Dxx) );

    if(fabs(den) < 1e-5)

    {

        if( fabs(Dxx / Dyy - 1) < 1e-5) //这时没有一个特殊的直线方向,无法拟合        {

            return false;

        }

        else        {

            a = 1;

            b = 0;

            c = - x_mean;

        }

    }

    else    {

        a = Dxy / den;

        b = (lambda - Dxx) / den;

        c = - a * x_mean - b * y_mean;

    }

    return true;

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容