OpenCV HoughLine只检测图像中的一行

时间:2017-11-20 09:51:04

标签: java opencv houghlines

我正在关注openCV的文档/ tutorial来检测图像中的线条。但是,我只从图像中的四条相似线中得到一条。 这是result

这是我的代码:

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

我尝试过使用阈值参数,但是我一直得到相同(有时甚至是最差)的结果。 有谁请指出我做错了什么?

2 个答案:

答案 0 :(得分:1)

在行矩阵结果中,行按行存储,而不是按行存储。 所以lines.rows()给你行数,你可以用lines.get(i,0)迭代来获取每一行。

答案 1 :(得分:0)

您的代码似乎是正确的,但也许您无法以正确的方式使用cv::line,例如,您可以使用以下代码来实现此目的

Mat img=imread("/home/saeed/Desktop/zracV.jpg"),img2;
cvtColor(img,img,CV_BGR2GRAY);
Canny(img,img2,50,150,3,true);
vector<Vec2f> lines;
HoughLines(img2,lines,1,CV_PI/180,200);
cvtColor(img2,img2,CV_GRAY2BGR);
vector<Vec2f>::const_iterator it = lines.begin();
while(it!=lines.end())
{
    float rho = (*it)[0];
    float theta = (*it)[1];
    if (theta < CV_PI/4.
            || theta > 3.*CV_PI/4.) { // ~vertical line
        // point of intersection of the line with first row
        cv::Point pt1(rho/cos(theta),0);
        // point of intersection of the line with last row
        cv::Point pt2((rho-img2.rows*sin(theta))/
                      cos(theta),img2.rows);
        // draw a white line
        cv::line( img2, pt1, pt2, cv::Scalar(255), 3);
    } else { // ~horizontal line
        // point of intersection of the
        // line with first column
        cv::Point pt1(0,rho/sin(theta));
        // point of intersection of the line with last column
        cv::Point pt2(img2.cols,
                      (rho-img2.cols*cos(theta))/sin(theta));
        // draw a white line
        cv::line(img2, pt1, pt2, cv::Scalar(255),3);
    }
    ++it;
}
imshow("i",img2);
waitKey(0);

以上代码的输出

enter image description here