Hough变换检测直线和圆

引言:
Hough变换被常用于检测图像中的直线和圆。其本质是将直角坐标系映射到极坐标系,有关Hough变换的原理

————————————————————-


Hough变换检测直线

OpenCV中提供了HoughLines 和 HoughLinesP来检测直线。第一个函数使用标准的Hough变换,第二个函数使用概率Hough变换,通过计算点属于直线的概率,提高了算法速度,是标准Hough变换的优化版。

例子里使用到的图像如下(下载自百度):

OpenCV自学笔记5:Hough变换检测直线和圆_百度

# -*- coding:utf-8 -*-

import cv2
import numpy as np

# Step1. 读入图像
src = cv2.imread('images/roof.jpg')
gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)

# Step2. 边缘检测
edges = cv2.Canny(gray, 50, 150)
dst1 = cv2.cvtColor(edges, cv2.COLOR_GRAY2BGR)
dst2 = cv2.cvtColor(edges, cv2.COLOR_GRAY2BGR)

# Step3. Hough直线检测
minLineLength = 100
maxLineGap = 10
lines1 = cv2.HoughLines(edges, 1, np.pi/180.0, 200, minLineLength, maxLineGap)
if lines1 is not None:
_lines1 = lines1[:, 0, :] # 提取为二维
for rho,theta in _lines1[:]:
a = np.cos(theta)
b = np.sin(theta)
x0, y0 = a * rho, b * rho
pt1 = ( int(x0 + 1000 * (-b)), int(y0 + 1000 * (a)) )
pt2 = ( int(x0 - 1000 * (-b)), int(y0 - 1000 * (a)) )
cv2.line(dst1, pt1, pt2, (0, 255, 0), 2)
cv2.imshow("hough lines", dst1)

# Step4. HoughLineP直线检测
minLineLength = 50
maxLineGap = 10
lines2 = cv2.HoughLinesP(edges, 1, np.pi/180.0, 50, minLineLength, maxLineGap)
if lines2 is not None:
_lines2 = lines2[:,0,:]
for x1,y1,x2,y2 in _lines2[:]:
cv2.line(dst2,(x1, y1), (x2, y2), (0,255,0), 2)

cv2.imshow("hough lines P", dst2)

cv2.waitKey(0)

程序的运行结果如下,检测出了一些主要的直线。由于参数不同,两种方法检测出的直线效果不同,如果想调整检测的效果,需要调整函数中的参数值。

OpenCV自学笔记5:Hough变换检测直线和圆_hough变换_02

————————————————————-


Hough变换检测圆

OpenCV中提供了HoughCircles函数用来检测圆,下面是使用HoughCircles检测圆的例子

例子里使用到的图像如下:

OpenCV自学笔记5:Hough变换检测直线和圆_直线检测_03

# -*- coding:utf-8 -*-

import cv2
import numpy as np

# Step1. 读入图像
src = cv2.imread('images/moon.jpg')
gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)

# Step2. Hough圆检测
# 根据多次尝试的结果,将param1调整为220时,检测效果较好
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 100, \
param1=220, param2=30, minRadius=100, maxRadius=200)
if circles is not None:
for i in circles[0,:]:
cv2.circle(src, (i[0], i[1]), i[2], (0, 255, 0), 2)

cv2.imshow("hough circle ", src)

cv2.waitKey(0)

程序的运行结果如下:

OpenCV自学笔记5:Hough变换检测直线和圆_直线检测_04