1

I'm using OpenCV on the raspberry pi and building with Python. Trying to make a simple object tracker that uses color to find the object by thresholding the image and finding the contours to locate the centroid. When I use the following code:

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)

I get the following error.

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

I've tried a few other settings and get the same error or

ValueError: too many values to unpack

I'm using the PiCamera. Any suggestions for getting centroid position?

Thanks

Z

1 Answer 1

3

Error 1:

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

Simply stands that the cv2.findContours() method didn't found any contours in the given image, so it is always suggested to do a sanity checking before accessing the contour, as:

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

Error2

ValueError: too many values to unpack

This error is raised due to _,contours,_ = cv2.findContours, since the cv2.findContours returns only 2 values, contours and hierarchy, So obviously when you try to unpack 3 values from 2 element tuple returned by the cv2.findContours, it would raise the above mentioned error.

Also the cv2.findContours changes the input mat in place, so it is suggested to call the cv2.findContours as:

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."
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.