小言_互联网的博客

在OpenCV里实现霍夫直线检测2

545人阅读  评论(0)

有了这个直线检测,就可以进行车道识别了,下面先来对前面提到的车道照片做高斯平滑:

out = cv2.GaussianBlur(image,(5,5),1.5)

这时图像平滑之后,再做形态学的闭运算,以便把小黑点去掉:

kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(5,5))

out = cv2.morphologyEx(out, cv2.MORPH_CLOSE, kernel, iterations=2)

接着下来使用Canny函数对边缘进行识别:

edges = cv2.Canny(out,150,255,apertureSize = 3)

edges_out = cv2.resize(edges, (400,400))

cv2.imshow('edges',edges_out)

这时可以看到图片处理之后的效果:

通过这样处理之后,就可以使用霍夫直线检测了,如下代码:

lines = cv2.HoughLines(edges,1,np.pi/180,200)#霍夫检测

这样就可以把图片上的直线识别出来,最后就是把识别出来的直线绘在原图上,如下:

可以看到车道线已经被白线显示出来,到这里就完成了简单的直线识别。整个例子的代码如下:

#python 3.7.4,opencv4.1
#蔡军生 https://blog.csdn.net/caimouse/article/details/51749579
#
import cv2
import numpy as np
from scipy import signal

#图片的路径
imgname = "chedao1.png"

#读取图片
image = cv2.imread(imgname, cv2.IMREAD_GRAYSCALE)

#图片的高度和宽度
h,w = image.shape[:2]
print('imagesize={}-{}'.format(w,h))

out = cv2.GaussianBlur(image,(5,5),1.5)

#闭运算
kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(5,5))
out = cv2.morphologyEx(out, cv2.MORPH_CLOSE, kernel, iterations=2)

edges = cv2.Canny(out,150,255,apertureSize = 3)
edges_out = cv2.resize(edges, (400,400))
cv2.imshow('edges',edges_out)

lines = cv2.HoughLines(edges,1,np.pi/180,200)#霍夫检测
if lines.shape[0]:
    line_count = lines.shape[0]
else:
    raise Exception('field not detected')
print(line_count)

for x in range(line_count):
    for rho,theta in lines[x]:
        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(image,(x1,y1),(x2,y2),(255,255,255),2)
        break
#显示原图
image = cv2.resize(image, (400,400), interpolation=cv2.INTER_AREA)
cv2.imshow("Image",image)

cv2.waitKey(0)
cv2.destroyAllWindows()

https://blog.csdn.net/caimouse/article/details/51749579


转载:https://blog.csdn.net/caimouse/article/details/102319300
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场