目录
[1. 霍夫直线变换](#1. 霍夫直线变换)
[2. 霍夫圆变换](#2. 霍夫圆变换)
[1. 标准霍夫直线变换](#1. 标准霍夫直线变换)
[2. 统计概率霍夫直线变换](#2. 统计概率霍夫直线变换)
在图像处理中,霍夫变换是一种强大的工具,用于从复杂的图像中提取简单的几何形状,如直线和圆。本文将详细介绍霍夫变换的原理和实现方法,并通过代码示例展示如何使用 OpenCV 进行直线检测和圆检测。
一、什么是霍夫变换?
霍夫变换是一种用于检测图像中特定几何形状(如直线、圆等)的方法。它的核心思想是将图像从笛卡尔坐标系转换到参数空间(霍夫空间),通过累加器投票机制来检测形状。
1. 霍夫直线变换
对于一条直线,可以用方程 y=kx+b 表示。在霍夫空间中,直线被表示为一个点 (ρ,θ),其中 ρ 是直线到原点的距离,θ 是直线与 x 轴的夹角。
2. 霍夫圆变换
对于一个圆,可以用方程 (x−x0)2+(y−y0)2=r2 表示。在霍夫空间中,圆被表示为一个点 (x0,y0,r),其中 (x0,y0) 是圆心坐标,r 是半径。
二、霍夫直线变换的实现
1. 标准霍夫直线变换
标准霍夫直线变换会检测图像中的所有直线,并返回它们的参数 (ρ,θ)。
代码示例
python
import cv2
import numpy as np
def test_hough_lines():
# 读取图像
img = cv2.imread("./opencv_work/src/huofu.png")
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img_edge = cv2.Canny(img_gray, 40, 120) # 使用 Canny 边缘检测
# 使用霍夫变换检测直线
lines = cv2.HoughLines(img_edge, 0.8, 0.0178, 90)
# 绘制检测到的直线
if lines is not None:
for el in lines:
rho, theta = el[0]
a = np.cos(theta)
b = np.sin(theta)
x0 = a * rho
y0 = b * rho
x1 = int(x0 + b * 1000)
y1 = int(y0 - a * 1000)
x2 = int(x0 - b * 1000)
y2 = int(y0 + a * 1000)
cv2.line(img, (x1, y1), (x2, y2), (0, 0, 255), 1)
# 显示结果
cv2.imshow("img", img)
cv2.imshow("img_edge", img_edge)
cv2.waitKey(0)
cv2.destroyAllWindows()
if __name__ == '__main__':
test_hough_lines()
2. 统计概率霍夫直线变换
统计概率霍夫直线变换是一种改进的霍夫变换,它不仅检测直线,还返回直线的端点坐标。
代码示例
python
import cv2
import numpy as np
def test_probabilistic_hough_lines():
# 读取图像
img = cv2.imread("./opencv_work/src/huofu.png")
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img_edge = cv2.Canny(img_gray, 30, 70) # 使用 Canny 边缘检测
# 使用统计概率霍夫变换检测直线
lines = cv2.HoughLinesP(img_edge, 1, 0.01745, 90, minLineLength=50, maxLineGap=10)
# 绘制检测到的直线
if lines is not None:
for line in lines:
x1, y1, x2, y2 = line[0]
cv2.line(img, (x1, y1), (x2, y2), (0, 0, 255), 1, lineType=cv2.LINE_AA)
# 显示结果
cv2.imshow("img", img)
cv2.imshow("img_edge", img_edge)
cv2.waitKey(0)
cv2.destroyAllWindows()
if __name__ == '__main__':
test_probabilistic_hough_lines()
三、霍夫圆变换的实现
霍夫圆变换用于检测图像中的圆形。它通过累加器投票机制来检测圆心和半径。
代码示例
python
import cv2
import numpy as np
def test_hough_circles():
# 读取图像
img = cv2.imread("./opencv_work/src/huofu.png")
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img_edge = cv2.Canny(img_gray, 30, 70) # 使用 Canny 边缘检测
# 使用霍夫圆变换检测圆
circles = cv2.HoughCircles(img_edge, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=30, minRadius=0, maxRadius=0)
# 绘制检测到的圆
if circles is not None:
circles = np.int_(np.around(circles))
for i in circles[0, :]:
cv2.circle(img, (i[0], i[1]), i[2], (0, 255, 0), 2) # 画出外圆
cv2.circle(img, (i[0], i[1]), 2, (0, 0, 255), 3) # 画出圆心
# 显示结果
cv2.imshow("img", img)
cv2.imshow("img_edge", img_edge)
cv2.waitKey(0)
cv2.destroyAllWindows()
if __name__ == '__main__':
test_hough_circles()
四、总结
霍夫变换是一种非常强大的图像处理技术,可以用于检测图像中的直线和圆等几何形状。通过本文的介绍和代码示例,相信你已经对霍夫变换有了更深入的理解。
-
霍夫直线变换:适用于检测图像中的直线。
-
统计概率霍夫直线变换:适用于检测图像中的直线,并返回直线的端点坐标。
-
霍夫圆变换:适用于检测图像中的圆形。