opencv學習(二十):直線檢測
阿新 • • 發佈:2018-12-08
霍夫直線檢測原理:
1、對於直角座標系中的任意一點A(x0,y0),經過點A的直線滿足Y0=k*X0+b.(k是斜率,b是截距)
2、那麼在X-Y平面過點A(x0,y0)的直線簇可以用Y0=k*X0+b表示,但對於垂直於X軸的直線斜率是無窮大的則無法表示。因此將直角座標系轉換到極座標系就能解決該特殊情況。
3、在極座標系中表示直線的方程為ρ=xCosθ+ySinθ(ρ為原點到直線的距離),如圖所示:
參考連結:https://blog.csdn.net/ycj9090900/article/details/52944708
https://www.cnblogs.com/ssyfj/p/9275368.html
霍夫直線檢測的兩種方法
參考連結:https://www.cnblogs.com/ssyfj/p/9275368.html
1.獲取灰度影象
2.canny邊緣檢測
3.獲取霍夫直線資訊
4.算出直線位置,畫出每條直線
程式碼如下:
# 匯入cv模組 import cv2 as cv import numpy as np # 直線檢測 HoughLines霍夫變換 def line_detection(image): gray = cv.cvtColor(image,cv.COLOR_BGR2GRAY) edges = cv.Canny(gray,50,150,apertureSize=3) #apertureSize是sobel運算元大小,只能為1,3,5,7 lines = cv.HoughLines(edges,1,np.pi/180,200) #函式將通過步長為1的半徑和步長為π/180的角來搜尋所有可能的直線 for line in lines: rho,theta = line[0]#獲取極值ρ長度和θ角度 a = np.cos(theta)#獲取角度cos值 b = np.sin(theta)#獲取角度sin值 x0 = a * rho#獲取x軸值 y0 = b * rho#獲取y軸值x0和y0是直線的中點 x1 = int(x0 + 1000*(-b))#獲取這條直線最大值點x1 y1 = int(y0 + 1000*(a)) #獲取這條直線最大值點y1 x2 = int(x0 - 1000 * (-b)) #獲取這條直線最小值點x2 y2 = int(y0 - 1000 * (a)) #獲取這條直線最小值點y2 其中*1000是內部規則 cv.line(image,(x1,y1),(x2,y2),(0,0,255),2)#開始劃線 cv.imshow("image line",image) #直線檢測 HoughLinesP概率霍夫變換 def line_detect_possible_demo(image): gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY) edges = cv.Canny(gray, 50, 150, apertureSize=3) # apertureSize是sobel運算元大小,只能為1,3,5,7 lines = cv.HoughLinesP(edges, 1, np.pi / 180, 100, minLineLength=50,maxLineGap=10) #函式將通過步長為1的半徑和步長為π/180的角來搜尋所有可能的直線 for line in lines: print(type(line)) #多維陣列 x1,y1,x2,y2 = line[0] cv.line(image,(x1,y1),(x2,y2),(0,0,255),2) cv.imshow("line_detect_possible_demo",image) print("------------Python Opencv Tutorial!-------------") # 讀取影象,支援 bmp、jpg、png、tiff 等常用格式 src = cv.imread("F:/Projects/images/sudoku.png") # 建立視窗並顯示影象 cv.namedWindow("input image", cv.WINDOW_AUTOSIZE) cv.imshow("input image", src) # 顯示原圖 line_detection(src) line_detect_possible_demo(src) cv.waitKey(0) # 釋放視窗 cv.destroyAllWindows()
執行效果: