4

I'm currently using the Hough Transform to get the straight lines. But there are a lot of lines detected. Can I know how to filter and only get the longest line from the output?

      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);

}

0

1 Answer 1

2

As far as I can see, you're literally a step away:

The hypot function gives you the distance between the start and end points. Now, simply find the longest such distance, and the corresponding line is the longest.

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
9
  • 2
    "// l now has your line of maximum length" No. l is the last element of lines. You don't update max_dist, so max_dist < hyp is valid for all lines...
    – FooTheBar
    Apr 23, 2015 at 9:59
  • 1
    @FooBar : Ooopsies. Terribly sorry. My bad. Updated now, thanks! Apr 23, 2015 at 10:43
  • Hi @aspiring_sarge and FooBar, I tried but seems like the all the lines are still appearing. Is it due to the for loop? Or do I need to put it somewhere first? Still debugging
    – Maz Ahmad
    Apr 23, 2015 at 10:54
  • Of course all lines are appearing. If you only want to draw the longest line, you have to move the line(...) out of the loop.
    – FooTheBar
    Apr 23, 2015 at 11:21
  • 1
    Yes. Simply replace double max_dist = -1.0; with a very large value, and the statement if (max_dist < hyp) with if (max_dist > hyp). Actually, it might be better to simply replace the statement if (max_dist < hyp) with if (max_dist > hyp || max_dist == -1.0). A third way of this doing (which, IMO, is the neatest) would be to store the very first line length in max_dist, and the first line itself in max_l, before the start of the loop. Note that it might be better to change all variables that start with max_ to start with min_, to avoid confusion later on ;) Apr 24, 2015 at 6:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.