2015-04-18 37 views
0

我已经使用Python 2.7,Numpy和OpenCV编写了一个程序,以从我的摄像头中抓取照片并给出每个像素的rgb值。在Python中索引NumPy图像数组时出错

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

我得到的错误信息:

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

有谁知道这是为什么在一个640×480像素的照片中运行代码后?

+2

480是从0到479. – Maroun

+0

是的我知道,试过 – skrhee

+4

它是numpy和opencv中的[y,x]。另外,请不要**重复像这样的像素,这是可怕的慢,容易出错,并且完全击败了高级库的目的 – berak

回答

1

简短的回答是一个640 x 480的图像已形状(480, 640, n_channels)。如果您将代码更改为image[y, x],则不会出现此错误。

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

这里有indexing image data一个教程,告诉您如何有效地做了一些操作和对索引约定的一些细节:如果你写的代码,因为它可能会更容易理解。

+1

谢谢!这很有道理 – skrhee