检测和隔离图像中的线条

Detecting and isolating lines in an image

我正在尝试编写一段代码来检测和隔离图像中的直线。我正在使用 opencv 库,结合 Canny 边缘检测和霍夫变换来实现这一点。到目前为止,我已经想出了以下内容:

import numpy as np
import cv2

# Reading the image
img = cv2.imread('sudoku-original.jpg')
# Convert the image to grayscale
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# Edge detection
edges = cv2.Canny(gray,50,150,apertureSize = 3)
# Line detection
lines = cv2.HoughLines(edges,1,np.pi/180,200)

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(img,(x1,y1),(x2,y2),(0,0,255),2)

cv2.imwrite('linesDetected.jpg',img)

理论上这个代码片段应该可以完成这项工作,但不幸的是它不能。结果图片清楚地显示只找到一条线。我不太确定我在这里做错了什么以及为什么它只检测到一条特定的线路。有人能找出这里的问题吗?

尽管 opencv 的 Hough Transform tutorial is using just one loop, the shape of lines is actual [None,1,2], thus when you use lines[0] you will only get one item for rho and one item for theta, which will only get you one line. therefore, my suggestion is to use a double loop (below) or some numpy slice magic to maintain using just 1 loop. To get all the grid detected, as Dan Masek mentioned, you will need to play with the edge detection logic. Maybe see the 使用了 HoughLinesP.

for item in lines:
    for rho,theta in item:
        ...