IndexError吗?它是什么,如何解决它



我是python的新手,我即将显示的这段代码刚刚从http://pythonprogramming.net/automated-image-thresholding-python/?completed=/thresholding-python-function/获得,我得到这个错误:

    Warning (from warnings module):
  File "C:/Users/User/Desktop/tolong aku/thresholding logic.py", line 15
    avgNum = reduce(lambda x, y: x + y, eachPix[:3])/len(eachPix[:3])
RuntimeWarning: overflow encountered in ubyte_scalars
Warning (from warnings module):
  File "C:/Users/User/Desktop/tolong aku/thresholding logic.py", line 21
    if reduce(lambda x, y: x + y, eachPix[:3])/len(eachPix[:3]) > balance:
RuntimeWarning: overflow encountered in ubyte_scalars
Traceback (most recent call last):
  File "C:/Users/User/Desktop/tolong aku/thresholding logic.py", line 41, in <module>
    iar = threshold(iar)
  File "C:/Users/User/Desktop/tolong aku/thresholding logic.py", line 25, in threshold
    eachPix[3] = 0
IndexError: index 3 is out of bounds for axis 0 with size 3

我该如何修复它,它有什么问题?

这是我在windows上的python 2.7代码。

# if you are on 32 bit OS:
#import Image
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import time
def threshold (imageArray):
    balanceAr = []
    newAr = imageArray
    for eachRow in imageArray:
        for eachPix in eachRow:
            avgNum = reduce(lambda x, y: x + y, eachPix[:3])/len(eachPix[:3])
            balanceAr.append(avgNum)
    balance = reduce(lambda x, y: x + y, balanceAr)/len(balanceAr)
    for eachRow in newAr:
        for eachPix in eachRow:
            if reduce(lambda x, y: x + y, eachPix[:3])/len(eachPix[:3]) > balance:
                eachPix[0] = 255
                eachPix[1] = 255
                eachPix[2] = 255
                eachPix[3] = 0
            else:
                eachPix[0] = 0
                eachPix[1] = 0
                eachPix[2] = 0
                eachPix[3] = 255
    return newAr
i = Image.open ('C:/Users/User/Desktop/tolong aku/50.0.png')
iar = np.array(i)
i2 = Image.open ('C:/Users/User/Desktop/tolong aku/50.1.png')
iar2 = np.array(i2)
iar = threshold(iar)
iar2 = threshold(iar2)
fig = plt.figure()
ax1 = plt.subplot2grid((8,6), (0,0), rowspan=4, colspan=3)
ax2 = plt.subplot2grid((8,6), (4,0), rowspan=4, colspan=3)
ax1.imshow(iar)
ax2.imshow(iar2)
plt.show()

我想让图像变成灰度像素,然后收集数组结果制作一个数据集…tq.

索引错误出现时,你试图获取一个序列的元素(如:(列表或元组),并使用超出现有元素范围的索引。

t = (1, 2, 3)     # has elements at indices 0, 1, and 2

如果您尝试访问元素3或4,您将获得索引错误。只有元素t[0]、t[1]和t[2]存在。

[[78 84 84][172 181 181][188 196 198]…, [111 116 113] [62 65][64 66 63]]那么,我只能用多少像素呢?

表示内部索引可以计数到2:元素[0]、[1]和[2]。下一个索引可以从0到(三元组的个数- 1)