find hough lines and highlight them in python

Here's the code to find hough lines and highlight them in Python using OpenCV library:

main.py
import cv2
import numpy as np

# Load the image
img = cv2.imread('image.jpg')

# Convert the image to grayscale
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

# Apply Canny edge detection
edges = cv2.Canny(gray,50,150,apertureSize = 3)

# Apply Hough line transformation
lines = cv2.HoughLines(edges,1,np.pi/180,200)

# Highlight the lines on the image
for line in lines:
    rho,theta = line[0]
    a = np.cos(theta)
    b = np.sin(theta)
    x0 = a*rho
    y0 = b*rho
    x1 = int(x0 + 1000*(-b))
    y1 = int(y0 + 1000*(a))
    x2 = int(x0 - 1000*(-b))
    y2 = int(y0 - 1000*(a))

    cv2.line(img,(x1,y1),(x2,y2),(0,0,255),2)

# Show the result
cv2.imshow('result',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
712 chars
34 lines

In this code, we first load an image using the cv2.imread function. Next, we convert the image to grayscale using the cv2.cvtColor function. We then apply the Canny edge detection algorithm to obtain the edges from the image.

After that, we use the Hough line transformation to detect lines in the image. In the cv2.HoughLines function, we specify the edges, the distance resolution of the accumulator in pixels, the angle resolution of the accumulator in radians, and the threshold that determines the minimum number of votes (intersections in the Hough grid cell) a candidate line needs to be considered.

Finally, we loop over the lines detected using Hough lines transformation and highlight them on the original image using cv2.line function.

The resulting image with highlighted lines will be displayed using cv2.imshow function.

gistlibby LogSnag