Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

I've written a program using Python 2.7, Numpy and OpenCV to grab a photo from my webcam and give the rgb value of every pixel. After running the code on a 640x480 pixel photo:

for x in range(638):
    for y in range(478):
        red, green, blue = image[x, y]
        print(red, green, blue)

I get the error message:

red, green, blue = image[x, y]
IndexError: index 480 is out of bounds for axis 0 with size 480

Does anybody know why this is?

share|improve this question
2  
480 is from 0 to 479. – Maroun Maroun Apr 18 '15 at 8:57
    
yes I know, tried that – skrhee Apr 18 '15 at 8:58
4  
it's [y,x] in numpy and opencv. also, please, never iterate over pixels like that, it's horrible slow, error-prone, and totally defeats the purpose of a high-level library – berak Apr 18 '15 at 9:03
1  
btw, pixel order is b g r, not r g b – berak Apr 18 '15 at 9:05
up vote 1 down vote accepted

The short answer is a 640 x 480 image has shape (480, 640, n_channels). If you change your code to image[y, x] you will not get this error. It might be easier to understand if you write the code as:

for row in range(image.shape[0]):
    for col in range(image.shape[1]):
      r, g, b = image[row, col]

Here's a tutorial on indexing image data which shows you how to do a few operations efficiently and has some details on indexing conventions.

share|improve this answer
1  
thank you! that makes so much sense – skrhee Apr 18 '15 at 17:30

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.