Engine
Engine

Reputation: 5420

detecting 2 lines opencv

I have an image on which I run a dilation, and works fine, now I want to detect two dick lines on it :

DilationResult

and when run on it the part of code:

    cv::Canny(dilationResult,canny,50,200,3);
    cv::cvtColor(dilationResult,dilationResult,CV_BGR2GRAY);
    cv::HoughLines(canny,lines,30,CV_PI/180,500,0);
    cv::cvtColor(mask,mask,CV_GRAY2BGR);
        if(lines.size()!=0){
                std::cout << " line Size " << lines.size()<< std::endl;
    for( size_t i = 0; i < lines.size(); i++ )
        {
          float rho = lines[i][0], theta = lines[i][2];
          cv::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));
          angle = atan2f((pt2.y-pt1.y),(pt2.x-pt1.x))*180.0/CV_PI;
          std::cout << "angle " << angle<< std::endl;
          line( mask, pt1, pt2, cv::Scalar(0,0,255), 3, CV_AA);
        }
    }
    cv::imshow("mask " ,mask);

here's the result:

detection result

what I would like to get is something like this :

the perfect result

getting only 2 lines that have the same width, and by the way I don't want to use findcontour function

any idea how can do this !

Upvotes: 0

Views: 2509

Answers (1)

Micka
Micka

Reputation: 20130

I don't get it to work with hough transform, but with the probabilistic version cv::HoughLinesP

with lineDetection_Input.jpg being your linked image lineDetection_Input.jpg

int main() 
{
    cv::Mat color = cv::imread("../lineDetection_Input.jpg");

    cv::Mat gray;
    cv::cvtColor(color, gray, CV_RGB2GRAY);

    std::vector<cv::Vec4i> lines;
    cv::HoughLinesP( gray, lines, 1, 2*CV_PI/180, 100, 100, 50 );

    for( size_t i = 0; i < lines.size(); i++ )
    {
        cv::line( color, cv::Point(lines[i][0], lines[i][1]),
              cv::Point(lines[i][2], lines[i][3]), cv::Scalar(0,0,255), 1);
    }

    cv::imwrite("lineDetection_Output.jpg", color);
    cv::namedWindow("output"); cv::imshow("output", color); cv::waitKey(-1);

    return 0;
}

lineDetection_Output.jpg: lineDetection_Output.jpg

for rotated image:

and for some different intersection angle: there you can see some lines detected with a slightly false angle that start in the top-right and end near the intersection (close behind), but these might be easily filtered by length or something.

Upvotes: 5

Related Questions