Search code examples
javaopencvhoughlines

OpenCV HoughLine only detect one line in image


I am following the docs/tutorial of openCV to detect lines in image. However, I only got one out of the four similar lines in the image. Here is the result

And here is my code:

Mat im = Imgcodecs.imread("C:/Users/valer/eclipse-workspace/thesis-application/StartHere/resource/4 lines.JPG");
    
    Mat gray = new Mat(im.rows(), im.cols(), CvType.CV_8SC1);
    
    Imgproc.cvtColor(im, gray, Imgproc.COLOR_RGB2GRAY);

    Imgproc.Canny(gray, gray, 50, 150);
    
    Mat lines = new Mat();

    Imgproc.HoughLines(gray, lines, 1, Math.PI/180, 200);

    for (int i = 0; i < lines.cols(); i++){
        double data[] = lines.get(0, i);
        double rho = data[0];
        double theta = data[1];
        double cosTheta = Math.cos(theta);
        double sinTheta = Math.sin(theta);
        double x0 = cosTheta * rho;
        double y0 = sinTheta * rho;
        Point pt1 = new Point(x0 + 10000 * (-sinTheta), y0 + 10000 * cosTheta);
        Point pt2 = new Point(x0 - 10000 * (-sinTheta), y0 - 10000 * cosTheta);
        Imgproc.line(im, pt1, pt2, new Scalar(0, 0, 200), 3);
    }
    Imgcodecs.imwrite("C:/Users/valer/eclipse-workspace/thesis-application/StartHere/resource/process/line_output.jpg", im);

I have tried playing around with the parameters for threshold, but I kept getting same (and sometimes worst) results. Would anyone please point out where am I doing wrong?


Solution

  • In the lines matrix result, lines are stored by row, not by column. So lines.rows() gives you line count and you can iterate with lines.get(i, 0) to fetch each line.