I'm trying to use the native functions of OpenCV HoughLines and HoughLinesP to detect the lines from an image. The Canny edge output of that image is the folllowing:

Lines to detect

The problem is that the OpenCV functions I mentioned above can't detect any of those lines. I have fiddled with the parameter values, trying to get a better result, but nothing. I think the issue may be that there are too many contiguous lines in the image, but is just a guess.

  • Can anybody help me with this?
  • And if the algorithm is not suited, can you point out an alternative?


I mainly lowered the threshold value, but, unless I lowered it to much (case in which the returned image is fully covered with miss detected lines, i.e. the output image is a red rectangle), the output image is exactly the same as the input image, without any line detected. I also tried increase the angular resolution and use subpixel distance resolution, so instead of

HoughLines( dst, lines, 1, CV_PI/180, 100 );

I tried something like

HoughLines( dst, lines, 0.5, CV_PI/360, 20 );

Without any success.


Here is the code:

void showLines(Mat src){
    Mat dst, cdst, color_dst;
    // Image only have 9 pixels vertically, so it needs to be resized
    resize(src, src, Size(), 2, 2, INTER_CUBIC);
    //Canny -> generates the image above
    Canny(src, dst, 50, 200, 5, false);

    vector<Vec2f> lines;
    // detect lines
    HoughLines( dst, lines, 0.5, CV_PI/360, 20 );

    // draw lines
    for( size_t i = 0; i < lines.size(); i++ ) {
        float rho = lines[i][0], theta = lines[i][1];
        Point pt1, pt2;
        double a = cos(theta), b = sin(theta);
        double x0 = a*rho, y0 = b*rho;
        pt1.x = cvRound(x0 + 1000*(-b));
        pt1.y = cvRound(y0 + 1000*(a));
        pt2.x = cvRound(x0 - 1000*(-b));
        pt2.y = cvRound(y0 - 1000*(a));
        line( cdst, pt1, pt2, Scalar(0,0,255), 3, CV_AA);

    imshow("source", src);
    imshow("detected lines", cdst);


The source (src) image is the following:

source image

  • $\begingroup$ Can you add some more detail eg. A couple of lines of code on which parameters you tried, or the resulting image after the failed line detection? $\endgroup$ – Atul Ingle Aug 23 '16 at 21:56
  • $\begingroup$ Adding the complete but minimal code would probably help people helping you. $\endgroup$ – anderstood Aug 24 '16 at 1:00
  • $\begingroup$ It seems like HoughLines expects a binary input image, but "dst" output from Canny will be the same type as "src" which I'm guessing is not binary? $\endgroup$ – Atul Ingle Aug 24 '16 at 15:07
  • $\begingroup$ I don't think that's the case, because in the example provided in the documentation, "src" and "dst" are also of the same type (Mat) $\endgroup$ – 0RI0N Aug 24 '16 at 15:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.