2016-03-19 58 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."