一文带你了解python opencv中霍夫变换(Hough transform)的常用操作

本文介绍了霍夫变换在Python OpenCV中的应用,包括霍夫直线变换的cv2.HoughLines和cv2.HoughLinesP函数,以及霍夫圆变换的cv2.HoughCircles函数。通过实例展示了如何使用这些方法进行道路检测和硬币检测,提供了详细的代码示例。
摘要由CSDN通过智能技术生成


前言

霍夫变换是一种特征检测(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<
  • 8
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值