'Python Error while going through a contour : tuple index out of range

I'm trying to code a piece of code to check if a contour (obtained using cv2.FindContour) is touching the border of an image or not. The contour is a tuple object.

So far here is what my code looks like :

for a in range(len(contours)):
     contoursNew = []
     if not np.any(contours[a][:,0,:]) == 0 \
        or not np.any(contours[a][:,0,0]) == (np.size(self.imageDeBase, 1)-1) \
        or not np.any(contours[a][:,0,0]) == (np.size(self.imageDeBase, 0)-1) :
          contoursNew.append(contours[a])
                    
     contours = tuple(contoursNew)

This is supposed to compare the coordinates (x;y) of each point of the contour to see if any of them is on one of the borders of the image. if none is on the border, then we save the contour in contourNew which is a list and after the loop is completed, we make it a tuple.

However, this code won't work : Here is the error the terminal will return :

    if np.any(contours[a][:,0,:]) == 0 \

IndexError: tuple index out of range

I tried to print contours[a] to see how it's like but I had the same error, meaning the part that doesn't work is contours[a]. Probably I didn't manipulated the tuple right, but I don't know what to do then.

Can someone help me please ? Thank you !!

EDIT : about cv2.findContour() this is what the documentation says : This method returns two values. contours, and hierarchy. contours is a Python list of all the contours in the image. Each individual contour is a Numpy array of (x,y) coordinates of boundary points of the object.



Solution 1:[1]

Try this

    for contour in contours:
         contoursNew = []
         if not np.any(contour[:,0,:]) == 0 \
            or not np.any(contour[:,0,0]) == (np.size(self.imageDeBase, 1)-1) \
            or not np.any(contour[:,0,0]) == (np.size(self.imageDeBase, 0)-1) :
              contoursNew.append(contour)
                        
         contours = tuple(contoursNew)

And I'm not sure about your comparison, np.any() returns a boolean but you are comparing it with int and tuple. Maybe it should be something like this?

 if not np.any(contour[:,0,:] == 0) \
            or not np.any(contour[:,0,0] == (np.size(self.imageDeBase, 1)-1)) \
            or not np.any(contour[:,0,0] == (np.size(self.imageDeBase, 0)-1)) :

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 stahh