hough直线检测
霍夫变换常用来提取图像中的几何形状,比如直线,圆等等。
霍夫线检测使用的内置函数为:
cv.Huogh(image,rho,theat,threshold)
其中rho,theat表示极坐标系下的半径和角度
threshold表示阈值,限制条件,高于该阈值才会被确定为直线
而且,cv.Huogh(image,rho,theat,threshold)获取到的是极坐标系下的点的数据,需要转化为x,y坐标,再利用cv.line函数将直线绘制出来
补充:cv.Huogh(image,rho,theat,threshold)只适用于二值图像,所以在检测之前,需要进行图像二值化操作
代码:
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plot
img=cv.imread(r"C:\Users\Windows\Desktop\1.png",0)
img1=cv.Canny(img,20,80)#二值化边缘检测
plot.imshow(img1,cmap=plot.cm.gray)
plot.show()
img2=cv.HoughLines(img1,0.8,np.pi/100,300)
print(img2)
for i in img2:
r,t=i[0]
s=np.cos(t)
ss=np.sin(t)
x=r*s
y=r*ss
xi=int(x+1000*(-ss))
yi=int(y+1000*s)
x2=int(x-1000*(-ss))
y2=int(y-1000*s)
cv.line(img1,(xi,yi),(x2,y2),(255,255,0),2)#绘制直线
plot.imshow(img1,cmap=plot.cm.gray)
plot.show()
实验结果
原始图像:
二值化:
hough直线检测: