我必须说在学Hough检测的时候,我走了一些弯路,因为网上有些代码有错误。
https://www.cnblogs.com/Undo-self-blog/p/8439279.html
这里面有两段代码,我给各位贴出来。这两段代码的作用都是画线的,都能画出线,如下图。
import cv2
import numpy as np
img = cv2.imread('dave.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 rho,theta in lines[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.imwrite('houghlines3.jpg',img)
import cv2
import numpy as np
img = cv2.imread('dave.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray,50,150,apertureSize = 3)
minLineLength = 100
maxLineGap = 10
lines = cv2.HoughLinesP(edges,1,np.pi/180,100,minLineLength,maxLineGap)
for x1,y1,x2,y2 in lines[0]:
cv2.line(img,(x1,y1),(x2,y2),(0,255,0),2)
cv2.imwrite('houghlines5.jpg',img)
但其实你按照上面的两段代码运行,并不能画出这么多的线。你只能画出一条,因为代码里写的就是画一条的代码。画出来大概是下面这样,就是右面有一条不明显的红线。
for rho,theta in lines[0]
for x1,y1,x2,y2 in lines[0]
下面两段才是正确的代码,各位请自行在原来的代码里替换。
for i in range(len(lines)):
rho, theta=lines[i][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)
for l in range(len(lines)):
x1, y1, x2, y2 = lines[l][0]
cv2.line(img, (x1,y1),(x2,y2),(0,255,0),1)
cv2.imwrite('houghlines5.jpg', img)
下面是真正想要达到的效果:
给各位看一下储存了线的数组lines的真面目,这两个lines不太一样,不过取出数来使用的原理是一样的。一个是储存了两个数,一个是储存了四个数。我们不列那么多,就列几个给大家看看。
print(lines)
print(len(lines))
[[[498. 0. ]]
[[498. 1.5707964]]
[[ 1. 0. ]]
。。。
[[189. 1.5707964]]
[[133. 0. ]]
[[190. 0. ]]
[[131. 0. ]]]
44
可以看出,这个结构是有三层的。所以我们的代码里是这样的。
rho, theta=lines[i][0]
x1, y1, x2, y2 = lines[l][0]