HoughLinesP openCV函数中的多行检测

时间:2018-04-24 04:45:45

标签: opencv image-processing hough-transform

我是Python和OpenCV的新手。我试图用来自互联网的代码检测具有HoughLinesP功能的单行,检测到3-4行。我尝试使用maxLineGap变量,但没有帮助。

输入图片: enter image description here 输出图像: enter image description here

import sys
import math
import cv2 as cv
import numpy as np

def main(argv):

    default_file =  "line.png"
    filename = argv[0] if len(argv) > 0 else default_file
    # Loads an image
    src = cv.imread(filename, cv.IMREAD_GRAYSCALE)
    # Check if image is loaded fine
    if src is None:
        print ('Error opening image!')
        print ('Usage: hough_lines.py [image_name -- default ' + default_file + '] \n')
        return -1


    dst = cv.Canny(src, 50, 200, None, 3)

    # Copy edges to the images that will display the results in BGR
    cdst = cv.cvtColor(dst, cv.COLOR_GRAY2BGR)
    cdstP = np.copy(cdst)

    lines = cv.HoughLines(dst, 1, np.pi / 180, 150, None, 0, 0)

    if lines is not None:
        for i in range(0, len(lines)):
            rho = lines[i][0][0]
            theta = lines[i][0][1]
            a = math.cos(theta)
            b = math.sin(theta)
            x0 = a * rho
            y0 = b * rho
            pt1 = (int(x0 + 1000*(-b)), int(y0 + 1000*(a)))
            pt2 = (int(x0 - 1000*(-b)), int(y0 - 1000*(a)))
            cv.line(cdst, pt1, pt2, (0,0,255), 3, cv.LINE_AA)


    linesP = cv.HoughLinesP(dst, 1, np.pi / 180, 50, None, 50, 150)

    no_of_Lines = 0
    if linesP is not None:
        for i in range(0, len(linesP)):
            l = linesP[i][0]
            no_of_Lines = no_of_Lines + 1
            cv.line(cdstP, (l[0], l[1]), (l[2], l[3]), (0,0,255), 3, cv.LINE_AA)



    print('Number of lines:' + str(no_of_Lines))

    cv.imshow("Source", src)
    cv.imshow("Detected Lines (in red) - Standard Hough Line Transform", cdst)

    cv.imshow("Detected Lines (in red) - Probabilistic Line Transform", cdstP)

    cv.waitKey()
    return 0

if __name__ == "__main__":
    main(sys.argv[1:])

2 个答案:

答案 0 :(得分:1)

将Canny应用于粗线的结果是粗线的轮廓。这给你多行。因此,你不能指望Hough变换产生一条线。

您有两个选项:合并输出行或预处理您的输入,使其onyl包含一行。

答案 1 :(得分:1)

Canny边缘检测器的输出有多条线。因此,函数cv.HoughLines()返回多行。您需要对图像进行骨架化,以便将所有线条合并为一个。

这就是我做的

由于这是一个简单的图像,我在Canny边缘输出上执行了几个形态学操作。膨胀后继续侵蚀。如果您注意到下面的代码,我使用更大的内核大小来执行侵蚀,以便得到一条细线。

补充代码:

kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE, (3, 3))
dilation = cv.dilate(dst, kernel, iterations = 1)
kernel1 = cv.getStructuringElement(cv.MORPH_ELLIPSE, (5, 5))
erosion = cv.erode(dilation, kernel1, iterations = 1)

输出

这是我在python控制台上得到的内容:

Number of lines:1

侵蚀后的输出:

enter image description here

霍夫线变换的输出:

enter image description here

概率Hough线变换的输出:

enter image description here

注意:

在尝试识别图像之前,请务必确保图像中的细线。