How do you detect the largest set of parallel lines in an image?

Question:

I have images with multiple line in them and I’m looking to detect the largest set of lines which are (approximately) parallel using Python and OpenCV. For example give:

enter image description here

The green lines are the best set:

enter image description here

Asked By: nickponline

||

Answers:

you can follow the following steps

  • Apply the Hough Line Transform to detect all line segments in the image.
  • Group the line segments based on their orientation using a clustering
  • Identify the largest cluster of lines. These will be the set of lines
    that are approximately parallel.
import cv2
import numpy as np
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt


img = cv2.imread('UI5Mr.png')


gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)


edges = cv2.Canny(gray, 50, 150, apertureSize=3)


lines = cv2.HoughLinesP(edges, rho=1, theta=np.pi/180, threshold=100, minLineLength=100, maxLineGap=10)


X = np.array([[x1, y1, x2, y2] for [[x1, y1, x2, y2]] in lines])
kmeans = KMeans(n_clusters=2)
kmeans.fit(X[:, [2, 3]] - X[:, [0, 1]])
labels = kmeans.labels_
centers = kmeans.cluster_centers_


counts = np.bincount(labels)
largest_cluster_idx = np.argmax(counts)
largest_cluster_mask = (labels == largest_cluster_idx)
largest_cluster_lines = X[largest_cluster_mask]


for [x1, y1, x2, y2] in largest_cluster_lines:
    cv2.line(img, (x1, y1), (x2, y2), (0, 255, 0), 2)


plt.imshow(img)
Answered By: Basir Mahmood
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.