索引错误:索引512在尺寸为512的轴0的范围之外

问题描述 投票:-1回答:2

所以,我正在尝试在python中的图像上复制“弗洛伊德-斯坦伯格抖动”,到目前为止,这是我所要保护的:

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

我有点迷失在其中,如果有人可以帮助我,那将是非常不明智的举动

python arrays image indexing cv2
2个回答
1
投票

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]

1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.