霍夫变换
霍夫变换检测直线
cv2.HoughLines() 第一个参数image为二值化图像或者进行Canny 边缘检测后的图像;第二个参数rho和第三个参数theta:对应直线搜索的步长半径和角度;第四个参数是
阈值,高于阈值时才被认为是一条直线。 返回值为直线到远点的
cv2.HoughLinesP() 前四个参数等同于cv.2HoughLines();第五个参数为minLineLength - 线的最短长度。比这个短的线都会被忽略。
第六个参数:MaxLineGap - 两条线段之间的最大间隔,如果小于此值,这两条直线就被看成是一条直线。返回值为直线的起点和终点。
代码
import cv2
import numpy as np
src = cv2.imread(r'F:\OPENCV\Opencv\line.png')
img = cv2.medianBlur(src, 5)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 50, 150, apertureSize=3)
cv2.imshow('edges', edges)
# 霍夫变换
lines = cv2.HoughLines(edges, 1, np.pi / 180, 100)
img1 = src.copy()
for line in lines:
rho = line[0][0]
theta = line[0][1]
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(img1, (x1, y1), (x2, y2), (0, 0, 255), 2)
cv2.imshow('img1', img1)
# 霍夫变换 概率
lines = cv2.HoughLinesP(edges, 3, np.pi / 180, 50, minLineLength=50, maxLineGap=20)
img2 = src.copy()
for line in lines:
x1, y1, x2, y2 = line[0]
# x1 = line[0][0]
# y1 = line[0][1]
# x2 = line[0][2]
# y2 = line[0][3]
cv2.line(img2, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.imshow('img2', img2)
cv2.waitKey()
cv2.destroyAllWindows()
结果显示