Advertisement
In this article, we will learn about Line Detection in OpenCV Python. We will learn Line Detection in OpenCV using Hough Lines and Probabilistic Hough Lines.
Let’s Code Line Detection in OpenCV!
Line Detection Theory OpenCV
The Hough Transform is a popular technique to detect any shape if you can represent that shape in a mathematical form, It can detect the shape even if it is broken or distorted a little bit.
A line can be represented by two formulas.
In Cartesian Coordinate System
1. y = mx + c
where m is the slope and c is the intercept. (Basic Mathematics formulas)
In the polar coordinate system
2. p = x cos Ѳ + y sin Ѳ
p is the perpendicular distance from the origin. Ѳ is the angle formed by the normal of this line to the origin (radians).
Hough Transformation OpenCV Python
1. Edge detection, e.g Using the Canny Edge Detector.
2. Mapping of the edge points to the Hough space and storage in an accumulator
3. Interpretation of the accumulator to yield lines of infinite length. The interpretation is done by thresholding and possibly other constraints.
4. Conversion of infinite lines to finite lines.
Types of Hough line Transforms OpenCV Python
- The Standard Hough Transform (HoughLines method)
- The Probabilistic Hough Line Transform (HoughLinesP)
Hough Lines OpenCV Python
cv.HoughLines( binarized image, rho accuracy, Ѳ accuracy, threshold)
The threshold here is the minimum vote for it to be considered a line.
Probabilistic Hough Lines OpenCV Python
cv.HoughLinesP(binarized image, rho accuracy, Ѳ accuracy, threshold, minimum line length, max line gap)
Line Detection OpenCV Python Steps
1. Input the image in which you want to detect lines.
image = cv.imread(“source”)
2. Convert the image to grayscale using cvtColor function
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
3. Canny Edge Detection OpenCV Python
edge = cv.Canny(gray, 100,170, apertureSize = 3)
4. Hough Lines OpenCV Python
Run Hough lines of a rho accuracy of 1 pixel.
Ѳ (theta) accuracy of np.pi/180 which is one degree.
Our line threshold is set to 240 (number of points on Line).
lines = cv.HoughLines(edge, 1, np.pi/180, 240)
5. Iterate through each line
Now, we will iterate through each line and convert it to the format required by cv.lines (i.e Requiring endpoints).
for line in lines:
rho, theta = line[0]
a = np.cos(theta)
b = np.sin(theta)
x0 = a * rho
y0 = b * rho
# x1 stores the rounded off value of (r* cosΘ - 1000 * sinΘ)
x1 = int(x0 + 1000 * (-b))
# y1 stores the rounded off value of (r * sinΘ + 1000 * cosΘ)
y1 = int(y0 + 1000 * (a))
# x2 stores the rounded off value of (r * cosΘ + 1000 * sinΘ)
x2 = int(x0 - 1000 * (-b))
# y2 stores the rounded off value of (r * sinΘ - 1000 * cosΘ)
y2 = int(y0 - 1000 * (a))
cv.line(img, (x1, y1), (x2, y2), (0, 0, 255), 2)
Line Detection Documentation
Visit the official OpenCV web page for documentation.