1 __author__ = "WSX" 2 import cv2 as cv 3 import numpy as np 4 #-----------------霍夫變換--------------------- 5 #前提條件: 邊緣檢測完成 6 def line_detection(image): 7 gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY) 8 edges = cv.Canny(gray, 50, 150, apertureSize=3) 9 lines = cv.HoughLines(edges, 1, np.pi/180, 200) 10 for line in lines: 11 print(type(lines)) 12 rho, theta = line[0] 13 a = np.cos(theta) 14 b = np.sin(theta) 15 x0 = a * rho 16 y0 = b * rho 17 x1 = int(x0+1000*(-b)) 18 y1 = int(y0+1000*(a)) 19 x2 = int(x0-1000*(-b)) 20 y2 = int(y0-1000*(a)) 21 cv.line(image, (x1, y1), (x2, y2), (0, 0, 255), 2) 22 cv.imshow("image-lines", image) 23 24 25 def line_detect_possible_demo(image): 26 gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY) 27 edges = cv.Canny(gray, 50, 150, apertureSize=3) 28 lines = cv.HoughLinesP(edges, 1, np.pi/180, 100, minLineLength=50, maxLineGap=10) 29 for line in lines: 30 print(type(line)) 31 x1, y1, x2, y2 = line[0] 32 cv.line(image, (x1, y1), (x2, y2), (0, 0, 255), 2) 33 cv.imshow("line_detect_possible_demo", image) 34 35 def main(): 36 img = cv.imread("1.JPG") 37 cv.namedWindow("Show", cv.WINDOW_AUTOSIZE) 38 cv.imshow("Show", img) 39 line_detect_possible_demo(img) 40 41 cv.waitKey(0) 42 cv.destroyAllWindows() 43 44 main()