簡體   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