Index Error: index 512 is out of bounds for axis 0 with size 512

Index Error: index 512 is out of bounds for axis 0 with size 512

所以,我正在尝试在 python 中复制图像上的 "Floyd–Steinberg dithering",到目前为止,这是我所做的:

import cv2

# returns an array with rgb values of all pixels
x_img = cv2.imread("lenac.tif")

# returns an image with the rgb values turned to black and white
x_img_g = cv2.cvtColor(x_img,cv2.COLOR_BGR2GRAY)



def dither(img):

    col = len(img[0])
    li = len(img)

    print(col)
    print(li)

    for i in range (li):
        for j in range(col):

            oldpixel = img[li][col]
            newpixel = quantificacao(oldpixel)

            print(newpixel)

print(dither(x_img_g))

所以基本上这个方法还没有完成,它唯一要做的就是遍历 "lena.tif" 图像(在图像处理中非常有名)的黑白版本的每个像素,并且向他们应用一种名为 "quantificacao" 的方法,与问题无关。

图像是,512 x 512

一切顺利,直到在给定点弹出以下错误:

oldpixel = img[li][col]

IndexError: index 512 is out of bounds for axis 0 with size 512

变量 colli 都显示为 512,那么 for cycle 应该从 0 到 511 对吗?

因此只能索引到 511

我有点不知所措,如果有人能帮助我,我将非常感激

您当然遇到了那个错误,li,并且 col 的值为 512,并且在循环中您正在访问该值。 img[li][col] 应该是 img[i][j].

dither 函数中,您试图遍历 img 的轴并将值提取到变量 oldpixel 中。 licol对应img数组的大小; ij 是你的变量,它们从 0 增加到每个轴的长度(两者都是 512)。因此,在 for 循环中,您应该使用这些变量,而不是 licol,即:

for i in range(li):
    for j in range(col):
        oldpixel = img[i][j]

您可以通过内联临时变量 licol:

使这一点更清楚
for i in range (len(img)):
    for j in range(len(img[0])):
        oldpixel = img[i][j]