在 Python 中索引 NumPy 图像数组时出错

Error indexing a NumPy image array in Python

提问人:skrhee 提问时间:4/18/2015 最后编辑:YXDskrhee 更新时间:4/18/2015 访问量:1115

问:

我使用 Python 2.7、Numpy 和 OpenCV 编写了一个程序,从我的网络摄像头中抓取照片并给出每个像素的 rgb 值。在 640x480 像素的照片上运行代码后:

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

有谁知道这是为什么?

Python 数组 opencv numpy 索引

评论

2赞 Maroun 4/18/2015
480 是从 0 到 479。
0赞 skrhee 4/18/2015
是的,我知道,试过了
4赞 berak 4/18/2015
它在 numpy 和 opencv 中是 [y,x]。另外,请不要像那样迭代像素,它非常慢,容易出错,并且完全违背了高级库的目的
1赞 berak 4/18/2015
顺便说一句,像素顺序是 b g r,而不是 r g b

答:

1赞 YXD 4/18/2015 #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]

下面是一个关于为图像数据编制索引的教程,其中介绍了如何有效地执行一些操作,并提供了有关索引约定的一些详细信息。