opencv image detection Hoffmann transform detection of straight line

Hough transform is a classical algorithm for line detection. It is initially used to detect lines in images, but also can be extended to detect simple structures in images.

import cv2
import numpy as np

img = cv2.imread("road.jpg", 0)

img = cv2.GaussianBlur(img,(3,3) ,0)
edges = cv2.Canny(img, 50, 150, apertureSize = 3)
lines = cv2.HoughLines(edges,1,np.pi/180,118)  # Empirical values are used for the last parameter.
# print(lines)
lines = lines.reshape((lines.shape[0],lines.shape[2]))
# print(lines.shape)
result = img.copy()
# print(lines)
# exit()
for line in lines:
    rho = line[0]  # The first element is the distance rho
    theta = line[1]  # The second element is the angle theta.

    # print(line.shape)
    # print(rho)
    # print(theta)
    if (theta < (np.pi /4)) or (theta > (3 *np.pi/4.0)):  # Vertical line
        # The intersection of the line and the first line
        pt1 = (int(rho /np.cos(theta)),0)
        # The focus of the line and the last line
        pt2 = (int((rho -result.shape[0 ] *np.sin(theta) ) /np.cos(theta)) ,result.shape[0])
        # Draw a white line
        cv2.line( result, pt1, pt2, (255))
    else:  # Horizontal straight line
        # The intersection of the line with the first row
        pt1 = (0 ,int(rho /np.sin(theta)))
        # The intersection of the line with the last column
        pt2 = (result.shape[1], int((rho -result.shape[1 ] *np.cos(theta) ) /np.sin(theta)))
        # Draw a straight line
        cv2.line(result, pt1, pt2, (255), 1)

cv2.imshow('Canny', edges )
cv2.imshow('Result', result)
cv2.waitKey(0)
cv2.destroyAllWindows()

# Probabilistic Hough Transform
Look at the resulting image from the previous example, where the Hough transform looks like finding an aligned set of boundary pixels in the image. However, this may lead to false detection in some cases, such as multiple detection caused by accidental alignment of pixels or multiple lines passing through the same aligned pixels.

To avoid this problem and detect the segments of the straight line in the image (instead of the straight line running through the whole image), an improved version of Hough transform, Probabilistic Hough transform, was born.

import cv2
import numpy as np

img = cv2.imread("road.jpg")

img = cv2.GaussianBlur(img, (3, 3), 0)
edges = cv2.Canny(img, 50, 150, apertureSize=3)
lines = cv2.HoughLines(edges, 1, np.pi / 180, 118)
result = img.copy()
lines = lines.reshape((lines.shape[0],lines.shape[2]))
# Empirical parameters
minLineLength = 200
maxLineGap = 15
lines = cv2.HoughLinesP(edges, 1, np.pi / 180, 80, minLineLength, maxLineGap)

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

cv2.imshow('Result', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Reference resources: https://blog.csdn.net/sunny2038/article/details/9253823

Posted by gateUK on Thu, 04 Apr 2019 16:00:29 -0700