文章目录
前言
霍夫变换是一种特征检测(feature extraction),被广泛应用在图像分析(image analysis)、计算机视觉(computer vision)以及数位影像处理(digital image processing)。霍夫变换是用来辨别找出物件中的特征,例如:线条。他的算法流程大致如下,给定一个物件、要辨别的形状的种类,算法会在参数空间(parameter space)中执行投票来决定物体的形状,而这是由累加空间(accumulator space)里的局部最大值(local maximum)来决定。
霍夫直线变换
cv2.HoughLines
lines = cv2.HoughLines(edges,1,np.pi/180,200)
返回一组(rho, theta)列表。rho以像素为单位测量,并且theta以弧度为单位。
第一个参数,输入图像应该是一个二值图像,所以在应用霍夫变换之前应用阈值或使用精明的边缘检测(Canny)。
第二个和第三个参数分别是rho 和theta的精度。
第四个参数是阈值,这意味着它应该被视为一条线的最低投票数。投票数取决于线上的点数。所以它可能代表了应该检测的最小线长。
代码示例
import cv2
import numpy as np
img = cv2.imread('../data/sudoku.png')
gray = cv2.cvtColor(img,cv2.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.imwrite('houghlines3.jpg',img)
cv2.HoughLinesP
lines = cv2.HoughLinesP(edges, rho, theta, threshold, min_line_length, max_line_gap)
HoughLinesP(image, rho, theta, threshold, lines=…, minLineLength=…, maxLineGap=…)
rho参数表示参数极径 r 以像素值为单位的分辨率,这里一般使用 1 像素。
theta参数表示参数极角 \theta 以弧度为单位的分辨率,这里使用 1度。
threshold参数表示检测一条直线所需最少的曲线交点。
lines参数表示储存着检测到的直线的参数对 (x_{start}, y_{start}, x_{end}, y_{end}) 的容器,也就是线段两个端点的坐标。
minLineLength参数表示能组成一条直线的最少点的数量,点数量不足的直线将被抛弃。
maxLineGap参数表示能被认为在一条直线上的亮点的最大距离。
代码示例
rho = 1
theta = np.pi/180
threshold = 30
min_line_length = 50
max_line_gap = 20
line_image = np.copy(image) #creating an image copy to draw lines on
# Run Hough on the edge-detected image
lines = cv2.HoughLinesP(edges, rho, theta, threshold, np.array([]), min_line_length, max_line_gap)
# Iterate over the output "lines" and draw lines on the image copy
for line in lines:
for x1,y1,x2,y2 in line:
cv2.line(line_image,(x1,y1),(x2,y2),(255,0,0),5)
plt.figure(dpi=200, figsize=(3, 3))
plt.tick_params(labelsize=5)
plt.imshow(line_image)
skimage.transform.hough_line
h, angles, d = st.hough_line(img_edges)
h: 霍夫变换累积器
angles: 点与x轴的夹角集合,一般为0-179度
distance: 点到原点的距离
代码示例
import skimage.transform as st
h, angles, d = st.hough_line(img_edges)
print("hough space type:",type(h)," data type:",h.dtype," shape: ",h<