2013-09-27 52 views
4

我在圖像中有一個簡單的網格,我試圖確定網格大小,例如, 6x6,12x12等。使用Python和cv2。Python cv2 HoughLines網格線檢測

enter image description here

我正在與上述3×3柵格測試它,我打算通過在圖像中檢測它們計數多少垂直/水平線有確定網格尺寸:

import cv2 
import numpy as np 

im = cv2.imread('photo2.JPG') 
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) 

imgSplit = cv2.split(im) 
flag,b = cv2.threshold(imgSplit[2],0,255,cv2.THRESH_OTSU) 

element = cv2.getStructuringElement(cv2.MORPH_CROSS,(1,1)) 
cv2.erode(b,element) 

edges = cv2.Canny(b,150,200,3,5) 

while(True): 

    img = im.copy() 

    lines = cv2.HoughLinesP(edges,1,np.pi/2,2, minLineLength = 620, maxLineGap = 100)[0] 

    for x1,y1,x2,y2 in lines:   
     cv2.line(img,(x1,y1),(x2,y2),(0,255,0),1) 

    cv2.imshow('houghlines',img) 

    if k == 27: 
     break 

cv2.destroyAllWindows() 

我的代碼檢測線,如在下面可以看到,但有在我的圖像的每一行檢測到的多個行:

enter image description here

(對於圖像中的每一行都繪製了兩條1px綠線)

我不能簡單地將行數除以2,因爲(取決於網格大小)有時只是繪製一條線。

如何更準確地檢測並繪製原始圖像中檢測到的每一行的單行?

我調整了閾值設置,將圖像減少爲黑色和白色,但我仍然得到多行。我認爲這是因爲Canny邊緣檢測?

+2

問題可能是因爲canny檢測到您的線條的兩個邊緣,因此將其視爲兩條線。一種選擇是迭代線路,並找到附近的線路。如果接近丟棄一個。 –

+0

感謝@AbidRahmanK,那就是我最終做的。 – StuR

回答

9

我最終通過迭代線和去除是在彼此的10px的線路:

lines = cv2.HoughLinesP(edges,1,np.pi/180,275, minLineLength = 600, maxLineGap = 100)[0].tolist() 

for x1,y1,x2,y2 in lines: 
    for index, (x3,y3,x4,y4) in enumerate(lines): 

     if y1==y2 and y3==y4: # Horizontal Lines 
      diff = abs(y1-y3) 
     elif x1==x2 and x3==x4: # Vertical Lines 
      diff = abs(x1-x3) 
     else: 
      diff = 0 

     if diff < 10 and diff is not 0: 
      del lines[index] 

gridsize = (len(lines) - 2)/2 
1

你可以用 kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (2, 2)) dilated = cv2.dilate(edges, kernel, iterations=5) 擴張圖像,然後申請cv2.HoughLinesP

1

不Hough函數有一個參數可以做到這一點? MaxLineGap?所以,如果你的線條厚度爲2px,那麼你將該參數設置爲3?它不起作用嗎?