OpenCV:直线拟合——cv::fitLine()详解

Posted on 2018-02-28 15:14  supercxm  阅读(17571)  评论(0编辑  收藏  举报

实现目的:有一系列的点,需要拟合出一条直线。

cv::fitLine()的具体调用形式如下:

void cv::fitLine(  
    cv::InputArray points, // 二维点的数组或vector  
    cv::OutputArray line, // 输出直线,Vec4f (2d)或Vec6f (3d)的vector  
    int distType, // 距离类型  
    double param, // 距离参数  
    double reps, // 径向的精度参数  表示直线到原点距离的精度,建议取 0.01。设为0,则自动选用最优值
    double aeps // 角度精度参数  表示直线角度的精度,建议取 0.01
); 

计算出的直线信息存放在 line 中,为 cv::Vec4f 类型。line[0]、line[1] 存放的是直线的方向向量,double cos_theta = line[0]; double sin_theta = line[1];。line[2]、line[3] 存放的是直线上一个点的坐标。

还不太理解输出的直线,为什么要用这种类型。可以避免得到竖直直线,斜率无法显示么?

如果在图中画出直线,会用到cv::line(image, point1, point2, cv::Scalar(0, 255, 0), 2, 8, 0);因此,需要输入直线上的两个点,才能画出直线。

    double cos_theta = line[0];
    double sin_theta = line[1];
    double x0 = line[2], y0 = line[3];

    double k = sin_theta / cos_theta;
    double b = y0 - k * x0;

    double x = 0;
    double y = k * x + b;

    cv::line(image, Point(x0,y0), Point(x,y), cv::Scalar(255), 1);

 

Copyright © 2024 supercxm
Powered by .NET 8.0 on Kubernetes