第二章:霍夫变换
霍夫变换:霍夫变换是一种在图像中寻找直线、圆形以及其他简单形状的方法。霍夫变换采用类似于投票的方式来获取当前图像内的形状集合,该变换由 Paul Hough(霍夫)于 1962 年首次提出。最初的霍夫变换只能用于检测直线,经过发展后,霍夫变换不仅能够识别直线,还能识别其他简单的图形结构,常见的有圆、椭圆等
代码如下(示例):
import cv2
import numpy as np
代码如下:
HoughLines |
import cv2
import numpy as np
img = cv2.imread("shape.png")#读取原图
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
edge = cv2.Canny(gray,50,150)
lines = cv2.HoughLines(edge,1,np.pi/180,50)
#画线
for line in lines:
rho,theta = line[0]
a = np.cos(theta)
b = np.sin(theta)
x0 = rho * a
y0 = rho * b
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,255,0),2)
cv2.imshow("img",img)
cv2.imshow("gray",gray)
cv2.imshow("edges",edges)
cv2.waitKey(0)
cv2.destroyAllWindows()
代码如下(HoughLinesP):
import cv2
import numpy as np
img = cv2.imread("shape.png")#读取原图
#轮廓检测算法检测出轮廓
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray,50,150)
minLineLength = 10
maxLineGap = 30
lines = cv2.HoughLinesP(edge,1,np.pi/180,10,minLineLength,maxLineGap)
#画线
for line in lines:
x1,y1,x2,y2 = line[0]
cv2.line(img,(x1,y1),(x2,y2),(0,255,0),2)
cv2.imshow("img",img)
cv2.imshow("gray",gray)
cv2.imshow("edges",edges)
cv2.waitKey(0)
cv2.destroyAllWindows()
代码如下(HoughCircles):
import cv2
import numpy as np
img = cv2.imread("shape.png")#读取原图
#轮廓检测算法检测出轮廓
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
edge = cv2.Canny(gray,50,100)
#投射到Hough空间进行形状检测
circles = cv2.HoughCircles(edges,cv2.HOUGH_GRADIENT,1,30,\
param1=40,param2=20,minRadius=5,maxRadius=100)
#画图
if not circles is None:
#转化为int
circles = np.uint16(np.around(circles))
for circle in circles:
x,y,r = circle[0]
#画圆
cv2.circle(img,(x,y),r,(0,0,255),2)
cv2.imshow("img",img)
cv2.imshow("gray",gray)
cv2.imshow("edges",edges)
cv2.waitKey(0)
cv2.destroyAllWindows()