Python OpenCV:Hough变换无法检测到明显的线条

时间:2019-05-25 12:50:31

标签: python opencv hough-transform houghlines

问题: 我想在Python中使用OpenCV检测给定图像中的线条。尽管有多个明显的垂直线,但正常的HoughLines和概率性的HoughLines均未找到它们。当我花大量时间玩弄参数时,我想我在这里做了一些根本性的错误。我知道以下事实:通常在边缘上应用粗线,例如用完后。由于canny的非最大压迫感,因此canny在此处的效果不佳。

检测垂直线失败的图像:

enter image description here

原因: 鉴于此(水表的图像):

enter image description here

我想检测每个数字周围的矩形。为了检测矩形,我在x和y方向上使用了sobel滤波器,并计算了梯度的幅值和角度/相位。当我假设图像在此步骤中正确旋转时,我提取了图像中所示的垂直和水平边缘。我的希望是利用houghLines查找边界框。如

所示,找到水平线非常有效

调试图包含有关问题的更多见解,因为我无法处理垂直组件(第二行):

enter image description here

检测每个数字周围的矩形将对我有帮助

  1. 找到感兴趣的区域
  2. 切出矩形内的区域,即数字。其他几种通过轮廓直接检测数字的方法,都存在外部矩形干扰数字的问题。

更新:用于检测垂直线的代码:

#img is initialized with the binarized, vertical component image, as shown above
minLength = 30
maxGap = 7
angle_res = np.pi / 180
rad_res = 2
threshold_val = 100

linesP = cv2.HoughLinesP(img, rad_res, angle_res, threshold_val, minLineLength=minLength, maxLineGap=maxGap)

cdst = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
cdstP = np.copy(cdst)
if linesP is None:
    print("Error when finding lines (probabilistic hough transformation). No lines detected")
else:
    # Copy edges to the images that will display the results in BGR
    for i in range(0, len(linesP)):
        l = linesP[i][0]
        cv2.line(cdstP, (l[0], l[1]), (l[2], l[3]), (255,0,0), 3, cv2.LINE_AA)

plt.imshow(cdstP); plt.show()

1 个答案:

答案 0 :(得分:1)

首先以适当的阈值设置应用佳能边缘。然后应用概率霍夫线变换。应用霍夫变换后,对具有斜率的线进行过滤。您要过滤该框,因此需要过滤水平和垂直线。在过滤线之后,将形态学扩张和腐蚀操作背对背对结果图像进行处理,以在每个数字周围得到整洁的框。在应用霍夫变换时,请选择适当的最小线长,最大线长和最大线间距参数。 您可以在选择适当的参数时使用跟踪栏功能。下面给出了用于选择Canny Edge阈值的示例代码。

import cv2
import numpy as np

cv2.namedWindow('Result')
img = cv2.imread('qkEuE.png')

v1 = 0
v2 = 0

def doEdges():
    edges = cv2.Canny(img,v1,v2)
    edges = cv2.cvtColor(edges,cv2.COLOR_GRAY2BGR)
    res = np.concatenate((img,edges),axis = 0)
    cv2.imshow('Result',res)
def setVal1(val):
    global v1
    v1 = val
    doEdges()
def setVal2(val):
    global v2
    v2 = val
    doEdges()

cv2.createTrackbar('Val1','Result',0,500,setVal1)
cv2.createTrackbar('Val2','Result',0,500,setVal2)

cv2.imshow('Result',img)
cv2.waitKey(0)
cv2.destroyAllWindows

希望它对您有帮助。