First of all, let’s detect some lines, which is done with the HoughLines and HoughLinesP functions. The only difference between the two functions is that one uses the standard Hough transform, and the second uses the probabilistic Hough transform (hence P in the name).
The probabilistic version is so-called because it only analyzes a subset of points and estimates the probability of these points all belonging to the same line. This implementation is an optimized version of the standard Hough transform, and in this case, it’s less computationally intensive and executes faster.
Let’s take a look at a very simple example:
# Import Necessary library
import cv2
# Read Input image
img = cv2.imread('chess.jpg')
# convert to grayscale
gray = cv2.cvtColor( img, cv2.COLOR_BGR2GRAY)
# Edge Detection using canny
edges = cv2.Canny( gray, 50, 120)
# Define threshold Line Length and Line gap
minLineLength = 20
maxLineGap = 5
# Obtain Hough Lines
lines = cv2.HoughLinesP( edges, 1, np.pi/180, 100, minLineLength, maxLineGap)
# Loop though the lines and draw them
for i in range(len(lines)):
for x1,y1,x2,y2 in lines[i]:
cv2.line( img, (x1,y1), (x2,y2), (0,255,0),2)
# Display Output Image
cv2.imwrite("Houghedges.jpg", edges)
cv2.imwrite("Houghlines.jpg", img)
Input Image is:
Output Image for Edges and Lines will be: