Python openCV detects parallel lines

I have an image and there are some shapes in it. I found lines using hough lines. How to determine which lines are parallel?

+7
source share
2 answers

The equation of the 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 the coefficient k for each detected line.

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

After finding the lines with HoughLines (C ++):

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

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

Here is an 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 } 

Having received these two points of the line, you can calculate its equation.

+13
source

HoughLines returns its results in polar coordinates. So just check the second value for the angle. No need to convert to x, y

 def findparallel(lines): lines1 = [] for i in range(len(lines)): for j in range(len(lines)): if (i == j):continue if (abs(lines[i][1] - lines[j][1]) == 0): #You've found a parallel line! lines1.append((i,j)) return lines1 
+1
source

All Articles