Hough Line Transform
由于直角坐标系下存在,当直线垂直于x轴时,参数空间将无法表示该直线的情况。因此在opencv中选择用极坐标系来检测直线。
每条直线都可以准确的由
和
来表示。那么用grid的方式划分参数空间。横轴为
,取值为0到180。若取精度为1度,那么就将参数空间划分为180列;纵轴为
,取值为0到图像对角线长度。若取精度为1,就将参数空间划分为
行。
通过投票机制,在参数空间中进行投票,找到直线位置。
import cv2 as cv
import numpy as np
img = cv.imread(cv.samples.findFile('sudoku.png'))
gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)#RGB 转灰度图
edges = cv.Canny(gray,50,150,apertureSize = 3)#边缘检测
lines = cv.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))
cv.line(img,(x1,y1),(x2,y2),(0,0,255),2)
cv.imwrite('houghlines3.jpg',img)
Hough Circle Transform
寻找圆的方式与上面同理。圆的公式如下,
式中
是圆的中心,r是半径,由这三个参数组成了三维参数空间。用与上面相同的方式可以找到图中圆的位置。
import numpy as np
import cv2 as cv
img = cv.imread('opencv-logo-white.png',0)
img = cv.medianBlur(img,5)#中值滤波
cimg = cv.cvtColor(img,cv.COLOR_GRAY2BGR)#转灰度
circles = cv.HoughCircles(img,cv.HOUGH_GRADIENT,1,20,
param1=50,param2=30,minRadius=0,maxRadius=0)#霍夫曼圆形检测
circles = np.uint16(np.around(circles))#取整
for i in circles[0,:]:
# draw the outer circle
cv.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2)
# draw the center of the circle
cv.circle(cimg,(i[0],i[1]),2,(0,0,255),3)
cv.imshow('detected circles',cimg)
cv.waitKey(0)
cv.destroyAllWindows()