Hough Line Transform html
霍夫變換是一種檢測任何形狀的流行技術,能夠檢測形狀,即便它被破壞或扭曲一點點.
一條線能夠表示成y = mx + c或參數形式,像ρ=xcosθ+ysinθ,其中ρ是從原點到直線的垂直距離,θ角是由這條垂線和水平軸以逆時針的方向造成的(這個方向取決於你如何表示座標系統,這種表示法在OpenCV中使用)優化
cv.HoughLines()
第一個參數,輸入圖像應該是一個二值圖像,所以在應用hough變換以前應用閾值或使用Canny邊緣檢測.
第二和第三個參數分別是ρ和θ的精度.
第四個參數是閾值,這意味着它應該被視爲一條直線.
記住,選票的數量取決於直線上的點的數量,因此它表示應該檢測到的最小長度.spa
import cv2 import numpy as np from matplotlib import pyplot as plt img = cv2.imread('img.jpg') gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) edges = cv2.Canny(gray,50,150,apertureSize = 3) lines = cv2.HoughLines(edges,1,np.pi/180,200) 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*(a)) cv2.line(img,(x1,y1),(x2,y2),(0,0,255),2) cv2.imshow('show',img) cv2.waitKey()
在hough轉換中,你能夠看到,即便對於一個有兩個參數的線,它也須要大量的計算.機率Hough變換是咱們所見的Hough變換的一個優化,它並無把全部的要點都考慮進去,相反,它只須要一個隨機子集,對行檢測來講足夠.code
cv2.HoughLinesP(image, rho, theta, threshold[, lines[, minLineLength[, maxLineGap]]])
orm
import cv2 import numpy as np from matplotlib import pyplot as plt img = cv2.imread('img.jpg') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) edges = cv2.Canny(gray, 50, 150, apertureSize=3) lines = cv2.HoughLinesP(edges, 1, np.pi/180,100, minLineLength=100, maxLineGap=10) for line in lines: x1, y1, x2, y2 = line[0] cv2.line(img, (x1, y1), (x2, y2), (0,255,0), 2) cv2.imshow('show',img) cv2.waitKey()