霍夫变换是图像处理中从图像中识别几何形状的基本方法之一, 应用很广泛, 也有很多改进算法. 主要用来从图像中分离出具有某种相同特征的几何形状 (如, 直线, 圆等).
python 实现
- import cv2
- import numpy as np
- # 使用霍夫直线变换做直线检测, 前提条件: 边缘检测已经完成
- __author__ = "boboa"
- # 标准霍夫线变换
- def line_detection_demo(image):
- gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
- edges = cv2.Canny(gray, 50, 150, apertureSize=3)
- lines = cv2.HoughLines(edges, 1, np.pi/180, 200) # 函数将通过步长为 1 的半径和步长为π/180 的角来搜索所有可能的直线
- for line in lines:
- rho, theta = line[0] # line[0] 存储的是点到直线的极径和极角, 其中极角是弧度表示的
- a = np.cos(theta) # 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), (0, 0, 255), 2)
- cv2.imshow("image_lines", image)
- # 统计概率霍夫线变换
- def line_detect_possible_demo(image):
- gray = cv2.cvtColor(image, cv2.COLOR_BGRA2GRAY)
- edges = cv2.Canny(gray, 50, 150, apertureSize=3)
- # 函数将通过步长为 1 的半径和步长为π/180 的角来搜索所有可能的直线
- lines = cv2.HoughLinesP(edges, 1, np.pi / 180, 100, minLineLength=50, maxLineGap=10)
- for line in lines:
- x1, y1, x2, y2 = line[0]
- cv2.line(image, (x1, y1), (x2, y2), (0, 0, 255), 2)
- cv2.imshow("line_detect_possible_demo", image)
- if __name__ == "__main__":
- img = cv2.imread("image/lines.jpg")
- cv2.namedWindow("input image", cv2.WINDOW_AUTOSIZE)
- cv2.imshow("input image", img)
- line_detect_possible_demo(img)
- cv2.waitKey(0)
- cv2.destroyAllWindows()
标准霍夫线变换运行结果
统计概率霍夫线变换运行结果
标准霍夫线变换 cv2.HoughLines(image, rho, theta, threshold[, lines[, srn[, stn[, min_theta[, max_theta]]]]]) -> lines
参数: image - 边缘检测的输出图像, 8 位, 单通道二进制源图像
rho - 距离步长
theta - 角度步长
threshold - 阈值, 只有大于该值的点才有可能被当作极大值, 即至少有多少条正弦曲线交于一点才被认为是直线
统计概率霍夫线变换 cv2.HoughLinesP(image, rho, theta, threshold[, lines[, minLineLength[, maxLineGap]]]) -> lines
参数: image - 边缘检测的输出图像, 该图像为单通道 8 位二进制图像
rho - 参数极径 以像素值为单位的分辨率, 这里一般使用 1 像素
theta - 参数极角 以弧度为单位的分辨率, 这里使用 1 度
threshold - 检测一条直线所需最少的曲线交点
minLineLength - 线的最短长度, 比这个线短的都会被忽略
maxLineGap - 两条线之间的最大间隔, 如果小于此值, 这两条线就会被看成一条线.
HoughLinesP, 效果更好, 检测图像中分段的直线 (而不是贯穿整个图像的直线)
来源: http://www.bubuko.com/infodetail-3106539.html