繁体   English   中英

Hough Line 仅在 python 中写入 1 行,其中 OpenCV 和 Numpy

[英]Hough Line only writes 1 line in python with OpenCV and Numpy

我正在学习将 HoughLines() 与 Python、OpenCV 和 numpy 一起使用。 我使用下面的图片:

在此处输入图像描述

我正在尝试检测所有线条,而不仅仅是最粗的线条。 结果如下:

在此处输入图像描述

这是我的代码:

import cv2
import numpy as np
import argparse

ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="path to the imput image")
args = vars(ap.parse_args())

img = cv2.imread(args['image'])
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray,50,150,apertureSize = 3)
cv2.imwrite('edges_found.jpg',edges)
lines = cv2.HoughLines(edges, 1, np.pi/180, 200)

for r,theta in lines[0]:
    a = np.cos(theta)
    b=np.sin(theta)
    x0 = a*r
    y0 = b*r
    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)

我在这里使用教程/代码: https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_houghlines/py_houghlines.html

这看起来很简单,但在本教程中,使用的图像是报纸上的数独,并且在我得到单行的地方返回了许多行。 正如您在代码中看到的,我将 output edges设置为单独的图像,以查看那里发生了什么,结果如下:

在此处输入图像描述

似乎找到了许多边缘,但我只得到一条红线,而不是很多。 我的代码在哪里不正确?

这是因为您只在代码中显示一行,实际上不止一行。

for r,theta in lines[0]:
    a = np.cos(theta)
    b=np.sin(theta)
    x0 = a*r
    y0 = b*r
    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)

应该

for line in lines:
    for r,theta in line:
        a = np.cos(theta)
        b=np.sin(theta)
        x0 = a*r
        y0 = b*r
        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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM