检测和隔离图像中的线条

时间:2019-05-27 00:05:23

标签: python opencv hough-transform canny-operator

我正在尝试编写一段代码,该代码可以检测并隔离图像中的直线。我正在使用opencv库以及Canny边缘检测和Hough变换来实现此目的。到目前为止,我已经提出了以下建议:

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)

从理论上讲,此代码段可以完成此任务,但不幸的是,它不能完成任务。结果图片清楚地显示仅找到了一行。我不太确定自己在做什么错,为什么它只检测到一条特定的线。有人可以在这里解决问题吗?

enter image description here

1 个答案:

答案 0 :(得分:2)

尽管opencv的Hough Transform tutorial仅使用一个循环,lines的形状是实际的[None,1,2],所以当您使用lines[0]时,您只会得到一个项目rhotheta的一项,只会给您一行。因此,我的建议是使用双循环(在下面)或使用一些numpy slice魔术来仅使用1个循环来进行维护。如Dan Masek所述,要检测所有网格,您将需要使用边缘检测逻辑。也许会看到使用HoughLinesP的{​​{3}}。

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

solution