python - 检测和隔离图像中的线条

标签 python opencv hough-transform canny-operator

我正在尝试编写一段代码来检测和隔离图像中的直线。我正在使用 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)

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

enter image description here

最佳答案

尽管 opencv 的 Hough Transform tutorial仅使用一个循环,lines 的形状是实际的 [None,1,2],因此当您使用 lines[0] 时,您只会获得一项 rhotheta 的一项,这只会让你得到一行。因此,我的建议是使用双循环(如下)或一些 numpy slice 魔术来保持仅使用 1 个循环。如 Dan Masek 所述,要检测到所有网格,您需要使用边缘检测逻辑。也许看到 solution使用 HoughLinesP

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

enter image description here

关于python - 检测和隔离图像中的线条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56318281/

相关文章:

python - 在一行中按升序排列数字

opencv - 如何修复HOG以检测场景中的所有人?

opencv - 如何 “translate”摄像机到图像的运动?

opencv - OpenCV中的广义Hough变换

python - 如果数组中的两个连续行在第一列中具有相同的字符串,则将第一行中的剩余条目设置为零

python - Flask 不会在 html 中播放视频

python - setup.py 中的 extras_require() 和 install_requires() 之间的区别?

opencv - 将模板图像(缩放)匹配到主图像/大图像

c++ - 使用 Hough OpenCV 时出错

opencv - OpenCV中概率霍夫变换的具体实现是什么?