我正在尝试编写一段代码来检测和隔离图像中的直线。我正在使用 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仅使用一个循环,lines
的形状是实际的 [None,1,2],因此当您使用 lines[0]
时,您只会获得一项 rho
和 theta
的一项,这只会让你得到一行。因此,我的建议是使用双循环(如下)或一些 numpy slice 魔术来保持仅使用 1 个循环。如 Dan Masek
所述,要检测到所有网格,您需要使用边缘检测逻辑。也许看到 solution使用 HoughLinesP
。
for item in lines:
for rho,theta in item:
...
关于python - 检测和隔离图像中的线条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56318281/