【问题标题】:Index Error: index 512 is out of bounds for axis 0 with size 512索引错误:索引 512 超出轴 0 的范围,大小为 512
【发布时间】:2020-03-19 13:21:00
【问题描述】:

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

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


    【解决方案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]
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2018-02-12
        • 2021-01-22
        • 1970-01-01
        • 1970-01-01
        • 2021-11-03
        • 2021-12-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多