git:https://github.com/linyi0604/Computer-Vision
1 # coding:utf8
2
3 import cv2 4 import numpy as np 5
6
7 # 讀入圖像
8 img = cv2.imread("../data/line1.png") 9 # 轉為灰度圖像
10 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 11 # Canny邊緣檢測
12 edges = cv2.Canny(gray, 50, 100) 13 """
14 canny邊緣檢測: 15 有五個步驟: 16 1 高斯濾波器降噪 17 2 計算梯度 18 3 邊緣上使用非最大抑制 nms 19 4 邊緣上使用雙閾值去除假陽性 20 5 分析所有邊緣連接 消除不明顯的邊緣 21 """
22
23 minLineLength = 20
24 maxLineGap = 5
25 lines = cv2.HoughLinesP(edges, 1, np.pi/180, 100, minLineLength, maxLineGap) 26 """
27 cv2.HoughLinesP 28 作用:標准霍夫線變換, 找到圖像中的所有直線 29 參數: 30 1 二值圖 31 2 半徑精度 32 3 角度精度 33 4 最短檢測長度 34 5 允許的最大缺口 35 返回: 36 一個列表,每一項是一個四元組,分別是直線兩個端點的坐標 37 """
38 for line in lines: 39 for x1, y1, x2, y2 in line: 40 # 在圖片上畫直線
41 cv2.line(img, (x1, y1), (x2, y2), (0, 255, 0), 2) 42
43 cv2.imshow("edges", edges) 44 cv2.imshow("lines", img) 45 cv2.waitKey() 46 cv2.destroyAllWindows()