2013-07-10 42 views
0

所以我想要做的是使用hough變換來查找圖像上的線條,然後將線條繪製到圖像中。在OpenCV中繪製線條時出錯Python

但我得到一個錯誤,指出:

Traceback (most recent call last): 
    File "houghLines.py", line 31, in <module> 
    main() File "houghLines.py", line 13, in main 
    a = hough(image) 
    File "houghLines.py", line 29, in hough 
    (0,0,255)) 
    TypeError: only length-1 arrays can be converted to Python scalars 

這是我的代碼:

import cv2 
import os 
import math 
def main(): 

    directory = os.path.dirname(__file__) 
    picLoc = os.path.join(directory, "../video-image/1m50s.png") 

    image = cv2.imread(picLoc) 
    print "sending image to houghLines.py" 

    a = hough(image) 
    cv2.imshow("", a) 
    cv2.waitKey(0) 
    cv2.destroyAllChildren() 

def hough(image): 
    canny = cv2.Canny(image, 50, 200) 
    color_image = cv2.cvtColor(canny, cv2.COLOR_GRAY2BGR) 
    houghLines = cv2.HoughLinesP(canny, 1, math.pi/180, 50) 
    for x in range(len(houghLines)): 
     print x 
     pt1 = (houghLines[x][0], houghLines[x][1]) 
     pt2 = (houghLines[x][2], houghLines[x][3]) 
     cv2.line(color_image, pt1, pt2, (0,0,255), 3) 
    return color_image 

main() 

回答

1

出現此問題的原因cv2.line()預計pt1pt2是僅由單一元素的元組每個xy座標。如果您在示例中使用print pt1,則很快就會發現情況並非如此。

cv2.HoughLinesP()返回一個只有一個元素的numpy數組。此元素包含四個點的列表,這些點是線條的起點和終點。知道這一點,正確的實施如下:

for line in houghLines[0]: 
     pt1 = tuple(line[:2]) 
     print pt1 
     pt2 = tuple(line[-2:]) 
     cv2.line(color_image, pt1, pt2, (0,0,255), 3)