Search code examples
pythonopencvhough-transform

Python openCV detect parallel lines


I have an image and it has some shapes in it. I detected lines with using hough lines. How can I detect which lines are parallel?


Solution

  • Equation of a line in Cartesian coordinates:

    y = k * x + b

    Two lines y = k1 * x + b1, y = k2 * x + b2 are parallel, if k1 = k2.

    So you need to calculate coefficient k for each detected line.

    In order to uniquely identify the equation of a line you need to know the coordinates of two points that belong to line.

    After having found lines with HoughLines (С++):

    vector<Vec2f> lines;
    HoughLines(dst, lines, 1, CV_PI/180, 100, 0, 0 );
    

    you have the vector lines, which stores the parameters (r,theta) of the detected lines in polar coordinates. You need to transfer them in Cartesian coordinates:

    Here example in C++:

    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)); //the first point
      pt1.y = cvRound(y0 + 1000*(a)); //the first point
      pt2.x = cvRound(x0 - 1000*(-b)); //the second point
      pt2.y = cvRound(y0 - 1000*(a)); //the second point
    }
    

    After having got these two points of a line you can calculate its equation.