find longest 3 lines in edge image and highlight them in the original image in python

Here's one way to find the longest 3 lines in an edge-detected image and highlight them in the original image using Python, OpenCV library:

  1. Read the original image and convert it to grayscale:
main.py
import cv2
import numpy as np
 
img = cv2.imread('original_image.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
116 chars
6 lines
  1. Apply edge detection to the grayscale image:
main.py
edges = cv2.Canny(gray, 50, 150, apertureSize=3)
49 chars
2 lines
  1. Find the lines in the edge-detected image using Hough Line Transform:
main.py
lines = cv2.HoughLines(edges, 1, np.pi/180, 200)
49 chars
2 lines
  1. Sort the lines by length and select the 3 longest ones:
main.py
lines = sorted(lines, key=lambda line: np.abs(line[0][0] - line[0][2]), reverse=True)[:3]
90 chars
2 lines
  1. Draw the 3 longest lines on the original image:
main.py
for line in lines:
    rho, theta = line[0]
    a = np.cos(theta)
    b = np.sin(theta)
    x0, y0 = a*rho, b*rho
    x1, y1 = int(x0 + 1000*(-b)), int(y0 + 1000*(a))
    x2, y2 = int(x0 - 1000*(-b)), int(y0 - 1000*(a))
    cv2.line(img, (x1, y1), (x2, y2), (0, 0, 255), 2)
274 chars
9 lines
  1. Display the original image with the 3 highlighted lines:
main.py
cv2.imshow("Original Image with 3 Longest Lines Highlighted", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
106 chars
4 lines

Note that the line length threshold value in step 3 (200 in this example) might need to be adjusted depending on the specific edge image being analyzed.

gistlibby LogSnag