Perry Hotter
Perry Hotter

Reputation: 1

Python Loop Why is this index out of bounds

Hi I'd like to scan a picture for a certain color. The array seems to be to big although -1 is added. The solution might be simple but I need some help here. (the width of the image is 856 px) THX

img = cv2.imread(path)
 
height = img.shape[0]
width = img.shape[1]
channels = img.shape[2]

print('Image Height       : ',height)
print('Image Width        : ',width)
print('Number of Channels : ',channels)

print ( )
mid = (int(height/2), int(width/2)) 
print ('Image middle       : ',mid)
print ( )


for i in range(0, width-1):
      for j in range(0, height-1):
               if img[i,j,0]==all(color):
                print("Found color at ",i,j)

Exception :

Traceback (most recent call last)
    Input In [56], in <cell line: 23>()
         23 for i in range(0, width-1):
         24       for j in range(0, height-1):
    ---> 25                if img[i,j,0]==all(color):
         26                 print("Found color at ",i,j)
    
IndexError: index 856 is out of bounds for axis 0 with size 856

Upvotes: 0

Views: 73

Answers (1)

ShadowRanger
ShadowRanger

Reputation: 155418

Your height is your first dimension (img.shape[0]), width the second, but you used values derived from height (j in range(0, height - 1)) as your second dimension and vice-versa. Fix up your loops or the order in which you use i and j.

Your loop bounds are also narrower than they should be; range(width) would include all indices, range(width - 1) would omit the final index.

Upvotes: 1

Related Questions