2014-10-29 58 views
0

我使用openCV來檢測兩條線之間的距離以及它們相對於圖像中心點的位置。不需要是一個確切的距離 - 只是某種上下文值(像素會很好)cv2 lienes和屏幕中心之間的距離 - python

我的代碼,我工作檢測兩條線是這樣的;

import PIL 
import time 
import io 
import picamera 
import cv2 
import numpy as np 

image_count = 0 

with picamera.PiCamera() as camera: 
    camera.start_preview() 
    camera.resolution = (340, 240) 
    time.sleep(2) 

while(True): 
    try: 
     stream = io.BytesIO() 
     image_counter+=1 
     camera.capture(stream, format='png') 
     data = np.fromstring(stream.getvalue(), dtype=np.uint8) 
     image = cv2.imdecode(data, 1) 
     grey_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) 
     edge_image = cv2.Canny(grey_image, 50, 150, apertureSize = 3) 
     lines = cv2.HoughLines(edge_image, 1, np.pi/180, 95) 
     if(lines.any): 
      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(image, (x1, y1), (x2, y2), (0,0,255), 2) 

      cv2.imwrite('lined_image_' + str(image_counter) + '.png, image) 

    except: 
     print 'loop error' 

它檢測諸如此圖像中的行;

lines around boundaries

我一直在試圖找出如何數值做到這一點,但它是令人費解的,可能錯了 - 必須有一個更簡單的方法,但我不能使用開放的簡歷我的經驗不足看看吧。

我怎樣才能找到圖像的中心點和你看到的最內層的紅線之間的距離? (在線與相交於圖像中心點的水平線相交的點處)

謝謝!

回答

0

如果您要使用HoughLinesP,您可以直接獲取行的起點和終點。然後,當 DX爲(x2-x1)和Dy是(y2-y1),從中心點你需要的距離d(x0,y0)

enter image description here

如果您打算堅持HoughLines,您可以輕鬆地將rhotheta得到線的方程式,並使用描述爲here,的許多公式中的一個,這也是上述公式從中借用的地方。