1

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?

4
  • 2
    480 is from 0 to 479. Commented Apr 18, 2015 at 8:57
  • yes I know, tried that Commented Apr 18, 2015 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 Commented Apr 18, 2015 at 9:03
  • 1
    btw, pixel order is b g r, not r g b Commented Apr 18, 2015 at 9:05

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.