Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

I think the example was intended for something smaller than your image. Try this.

Mat dst = imread("lines.jpg");
Mat cdst = dst.clone();
cvtColor(dst, dst, COLOR_BGR2GRAY);
threshold(dst, dst, 1, 255, THRESH_BINARY);
vector<Vec2f> lines;
HoughLines(dst, lines, 1, CV_PI / 180, dst.cols*0.5, 0, 0, 89 * CV_PI / 180, 91 * CV_PI / 180);

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 + 5000 * (-b));
    pt1.y = cvRound(y0 + 5000 * (a));
    pt2.x = cvRound(x0 - 5000 * (-b));
    pt2.y = cvRound(y0 - 5000 * (a));
    line(cdst, pt1, pt2, Scalar(0, 0, 255), 3, CV_AA);
}
imshow("source", dst);
imshow("detected lines", cdst);
waitKey();

I think the example was intended for something smaller than your image. Try this.

EXPLANATION EDIT: I extended the size of the lines it draws to 5000 pixels, cause it's a big image. The most important changes are to the HoughLines call.

  • The (1) is rho is the distance of the accumulator in pixels, and I just used the value from the tutorial.
  • The (CV_PI/180) is the angular resolution of the accumulator in radians, and this is a value of 1 degree.
  • The (dst.cols*0.5) is the number of pixels that must be accumulated to count as a line, which I have set to half the width of the image. This is your main control over what qualifies as a line.
  • The (0, 0) are telling it to use the classical Hough transform, not the multi-scale one.
  • The (89 * CV_PI / 180, 91 * CV_PI / 180) are the min and max theta. Since 0 is a vertical line, and you just want horizontal lines, we restrict it to a small distance +/- 1 degree around 90. You can possibly make this even smaller. Probably, just 90/90. That might get rid of the duplicates.

.

Mat dst = imread("lines.jpg");
Mat cdst = dst.clone();
cvtColor(dst, dst, COLOR_BGR2GRAY);
threshold(dst, dst, 1, 255, THRESH_BINARY);
vector<Vec2f> lines;
HoughLines(dst, lines, 1, CV_PI / 180, dst.cols*0.5, 0, 0, 89 * CV_PI / 180, 91 * CV_PI / 180);

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 + 5000 * (-b));
    pt1.y = cvRound(y0 + 5000 * (a));
    pt2.x = cvRound(x0 - 5000 * (-b));
    pt2.y = cvRound(y0 - 5000 * (a));
    line(cdst, pt1, pt2, Scalar(0, 0, 255), 3, CV_AA);
}
imshow("source", dst);
imshow("detected lines", cdst);
waitKey();