Opencv houghLines 不检测线

Opencv houghLines not detecting lines

我正在尝试使用 Hough 线过滤图像,但有些东西不起作用。

我创建了以下子例程,它是从文档中未经修改而复制粘贴的:

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

然后我给它下面的测试图像:

但是函数输出:

所以它有点检测到底部的几行,没有其他任何东西。

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

问题出在这一行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")

这是输出在我的电脑上的样子:

使用此代码。 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)