OpenCV HoughLines无法检测到线

时间:2019-01-14 20:10:30

标签: python opencv image-processing hough-transform

我正在尝试使用霍夫线对图像进行过滤,但有些功能不起作用。

我创建了以下子例程,该子例程未经文档的修改即被复制粘贴:

def FilterLines(img):
    lines = cv2.HoughLines(img,1,np.pi/180,200)
    blank_image = np.zeros((img.shape[0], img.shape[1]), np.uint8)
    if (lines is None):
        return blank_image
    for rho,theta in lines[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(blank_image,(x1,y1),(x2,y2),255,1)

    return blank_image

然后我给它以下测试图像: enter image description here

但是函数enter image description here输出:

所以它在底部检测到了几行,什么也没发现。

为什么函数不能在如此简单的图像中检测到线条?

2 个答案:

答案 0 :(得分:1)

问题是此行for rho,theta in lines[0]:。您仅使用一行,第一行line[0]

您需要像这样更改for循环:

    for x in range(0, len(lines)):    
        for rho, theta in lines[x]:

然后,整个代码如下所示(在我将它们放入测试中之后,注释了额外的调试语句):

import cv2
import os
import numpy as np

#path = os.path("D:\")
img = cv2.imread("D:\\oV1PG.png")

#cv2.imshow('image',img)
#cv2.waitKey(0)

img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#print(img)

'''height, width, channel = img.shape[:3]
size = img.size

print(height, width, channel, size)'''


if img is not None:
    lines = cv2.HoughLines(img, 1, np.pi / 180, 100)


    blank_image = np.zeros((img.shape[0], img.shape[1]), np.uint8)

    for x in range(0, len(lines)):    
        for rho, theta in lines[x]:
            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(blank_image, (x1, y1), (x2, y2), 255, 1)
            print(x1, y1, x2, y2)

        print("\n")

    cv2.imshow("out", blank_image)
    cv2.waitKey(0)
else:
    print("empty img. Cannot read file")

这是我的PC上输出的外观:

enter image description here

答案 1 :(得分:0)

使用此代码。 openCV版本存在冲突,因此我们无法以这种方式执行上述操作。


import cv2
import numpy as np

img = cv2.imread('image.jpg')
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 = line[0][0]
    theta = line[0][1]
    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)