Python-OpenCV 笔记2 – 霍夫变换(Hough)
1、标准霍夫变换 HoughLinesP
函数原型:
HoughLines(image, rho, theta, threshold, lines=None, srn=None, stn=None, min_theta=None, max_theta=None)
- image:8位、二值单通道图片
- rho:直线半径的搜索步长,单位为像素
- theta:直线角度使得搜索步长,单位为弧度
- threshold:累加阈值,只有属于同一直线的点数超过该阈值才会被检测为直线
- lines :存储检测结果,直线用半径和角度表示
- min_theta :检测直线的最小角度,[0, max_theta]
- max_theta :检测直线的最大角度
import cv2
import numpy as np
# 读取图片>转为灰度图>canny边缘检测>概率霍夫变换
img = cv2.imread('1.jpg')
gray = cv2.cvtColor(img,cv.COLOR_BGR2GRAY)
edges = cv2.Canny(gray,50,150,apertureSize = 3)
lines = cv2.HoughLines(edges,1,np.pi/180,200)
# 根据极坐标计算平面坐标
for line in lines:
rho,theta = line[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.imshow('houghlines', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
2、概率霍夫变换 HoughLinesP
函数原型:
HoughLinesP(image, rho, theta, threshold, lines=None, minLineLength=None, maxLineGap=None)
- image:8位、二值单通道图片
- rho:直线半径的搜索步长,单位为像素
- theta:直线角度使得搜索步长,单位为弧度
- threshold:累加阈值,只有属于同一直线的点数超过该阈值才会被检测为直线
- lines :存储检测结果1x1x4的矩阵,直线用两点坐标表示(x1, y1, x2, y2)
- minLineLength :检测为直线的最短长度,单位为像素
- maxLineGap:直线断点的最大距离
import cv2
import numpy as np
# 读取图像>高斯模糊>边缘检测
img = cv2.imread("1.jpg")
img = cv2.GaussianBlur(img, (3,3), 0)
edges = cv2.Canny(img, 50, 150, apertureSize = 3)
# 概率霍夫变换
minLineLength = 200
maxLineGap = 15
lines = cv2.HoughLinesP(edges, 1, np.pi/180, 80, minLineLength, maxLineGap)
# lines = np.squeeze(lines)
# 画线
for line in lines:
x1,y1,x2,y2 = line[0]
cv2.line(img,(x1,y1),(x2,y2),(0,255,0),2)
cv2.imshow('HoughLinesP', img)
cv2.waitKey(0)
cv2.destroyAllWindows()