【问题标题】:How to filter only the longest line after Hough Transform霍夫变换后如何仅过滤最长的线
【发布时间】:2015-04-23 19:30:43
【问题描述】:

我目前正在使用霍夫变换来获得直线。但是检测到很多行。我可以知道如何过滤并仅从输出中获取最长的行吗?

      HoughLinesP(dst, lines, 1, CV_PI/180, 50, 20, 10 ); //left lane

      for( size_t i = 0; i < lines.size(); i++ )
      {
        Vec4i l = lines[i];
        double theta1,theta2, hyp, result;

        theta1 = (l[3]-l[1]);
        theta2 = (l[2]-l[0]);
        hyp = hypot(theta1,theta2);

        line( cdst, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(255,0,0), 3, CV_AA);

        }

      imshow("detected lines", cdst);

}

【问题讨论】:

    标签: c++ opencv filter lines hough-transform


    【解决方案1】:

    据我所知,你真的离我们只有一步之遥:

    hypot 函数为您提供起点和终点之间的距离。现在,只要找到最长的这样的距离,对应的线就是最长的。

    Vec4i max_l;
    double max_dist = -1.0;
    
    for( size_t i = 0; i < lines.size(); i++ )
    {
        Vec4i l = lines[i];
        double theta1,theta2, hyp, result;
    
        theta1 = (l[3]-l[1]);
        theta2 = (l[2]-l[0]);
        hyp = hypot(theta1,theta2);
    
        if (max_dist < hyp) {
            max_l = l;
            max_dist = hyp;
        }           
    }
    
    // max_l now has the line of maximum length
    line( cdst, Point(max_l[0], max_l[1]), Point(max_l[2], max_l[3]), Scalar(255,0,0), 3, CV_AA);
    // do something else with max_l
    

    【讨论】:

    • "// l 现在有你的最大长度的行" No. l 是行的最后一个元素。你不更新 max_dist,所以 max_dist
    • @FooBar:哎呀。非常抱歉。我的错。已更新,谢谢!
    • 嗨@aspiring_sarge 和FooBar,我试过了,但似乎所有的行都还在出现。是因为for循环吗?还是我需要先把它放在某个地方?还在调试中
    • 当然所有的行都出现了。如果只想画最长的线,则必须将 line(...) 移出循环。
    • 是的。只需将double max_dist = -1.0; 替换为一个非常大的值,并将语句if (max_dist &lt; hyp) 替换为if (max_dist &gt; hyp)。实际上,将声明 if (max_dist &lt; hyp) 简单地替换为 if (max_dist &gt; hyp || max_dist == -1.0) 可能会更好。第三种方法(IMO 是最简洁的)是在循环开始之前将第一行长度存储在max_dist 中,并将第一行本身存储在max_l 中。请注意,最好将所有以max_ 开头的变量更改为以min_ 开头,以避免以后混淆;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多