Detecting Lines
Line detection finds straight lines in an image. It is used in lane detection for autonomous vehicles, document alignment, and architectural analysis.
8 min•By Priygop Team•Updated 2026
Hough Line Detection
Hough Line Detection
import cv2
import numpy as np
image = cv2.imread("photo.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 50, 150)
# METHOD 1: Standard Hough Lines
lines = cv2.HoughLines(
edges,
rho=1, # Distance resolution (pixels)
theta=np.pi/180, # Angle resolution (radians)
threshold=150 # Minimum votes (higher = fewer, stronger lines)
)
result = image.copy()
if lines is not None:
for line in lines:
rho, theta = line[0]
a, b = np.cos(theta), np.sin(theta)
x0, y0 = a * rho, b * rho
x1 = int(x0 + 1000 * (-b))
y1 = int(y0 + 1000 * (a))
x2 = int(x0 - 1000 * (-b))
y2 = int(y0 - 1000 * (a))
cv2.line(result, (x1, y1), (x2, y2), (0, 255, 0), 1)
print(f"Found {len(lines)} lines (standard Hough)")
# METHOD 2: Probabilistic Hough Lines (returns line segments, faster)
lines_p = cv2.HoughLinesP(
edges, rho=1, theta=np.pi/180,
threshold=100, minLineLength=50, maxLineGap=10
)
result2 = image.copy()
if lines_p is not None:
for line in lines_p:
x1, y1, x2, y2 = line[0]
cv2.line(result2, (x1, y1), (x2, y2), (0, 255, 0), 2)
print(f"Found {len(lines_p)} line segments (probabilistic)")
cv2.imwrite("lines_hough.jpg", result2)Diagram
Loading diagram…
Machine Learning follows a structured pipeline from data to deployment