2016-03-19 55 views
0

我在樹莓派上使用OpenCV並使用Python構建。試圖製作一個簡單的對象跟蹤器,使用顏色通過閾值化圖像找到對象並找到輪廓來定位質心。當我使用以下代碼:在Python中使用findContours和OpenCV

image=frame.array 
imgThresholded=cv2.inRange(image,lower,upper)  
_,contours,_=cv2.findContours(imgThresholded,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) 
cnt=contours[0] 
Moments = cv2.moments(cnt) 
Area = cv2.contourArea(cnt) 

我收到以下錯誤消息。

Traceback (most recent call last): 
File "realtime.py", line 122, in <module> 
    cnt=contours[0] 
IndexError: list index out of range 

我已經嘗試了一些其他的設置,並得到同樣的錯誤或

ValueError: too many values to unpack 

我使用的PiCamera。有關獲取質心位置的任何建議?

感謝

ž

回答

1

錯誤1:

Traceback (most recent call last): 
File "realtime.py", line 122, in <module> 
    cnt=contours[0] 
IndexError: list index out of range 

簡單地表示,該cv2.findContours()方法沒有找到指定圖像中的任何輪廓,所以它總是建議做一個理智在訪問輪廓之前進行檢查,如:

if len(contours) > 0: 
    # Processing here. 
else: 
    print "Sorry No contour Found." 

錯誤2

ValueError: too many values to unpack 

引發此錯誤是由於_,contours,_ = cv2.findContours,因爲cv2.findContours回報只有2個值,輪廓和層次,所以,很顯然,當你嘗試從由cv2.findContours返回2元元組解包3倍的值,它會提高上面提到的錯誤。

另外,cv2.findContours改變的地方輸入墊,所以建議調用cv2.findContours爲:

contours, hierarchy = cv2.findContours(imgThresholded.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) 
if len(contours) > 0: 
    # Processing here. 
else: 
    print "Sorry No contour Found."