In this Python OpenCV lesson we are going to learn about Python OpenCV Line Detection, so line detection has it own technique that is called the Hough transform, it was invented by Richard Duda and Peter Hart, who extended the work done by Paul Hough in the early 1960s. so now we are using HoughLines and HoughLinesP for detecting lines, the difference is this that HoughLines uses the standard HoughTransForm and HoughLinesP probabilistic Hough Transform.
This is the complete code for this lesson.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
import cv2 import numpy as np image = cv2.imread("lineimage.jpg") gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) canimg = cv2.Canny(gray, 50,200) lines = cv2.HoughLines(canimg, 1,np.pi/180, 120, np.array([])) 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 * (1)) cv2.line(image, (x1,y1), (x2,y2), (0,0,255), 2) cv2.imshow("Lines Detected", image) cv2.imshow("Canny Detection", canimg) cv2.waitKey(0) cv2.destroyAllWindows() |
In here we have loaded our image and we have converted the image to gray scale.
1 2 |
image = cv2.imread("lineimage.jpg") gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) |
Also in this line of code we have created our Canny algorithm.
1 |
canimg = cv2.Canny(gray, 50,200) |
This is our HoughLine algorithm for Line Detection, in here the first parameter is the image that we want to process, another parameter is the geometrical representations of the lines, rho and theta, which are usually 1 and np.pi/180.
1 |
lines = cv2.HoughLines(canimg, 1,np.pi/180, 120, np.array([])) |
Run the complete code and this is the result.