IndexError:列表索引超出范围Python枕头图像库

问题描述 投票:0回答:1

我正在用 Python 制作图像到 ASCII 转换器。

我在第 38 行得到 IndexError 超出范围。

奇怪的是,在某些图像上程序运行得很好,而在其他图像上却抛出此错误。

这是代码:

from PIL import Image, ImagePalette, ImageOps

ascii_chars = list("$B%&W#*oakbdqmZOQLCUXcvnxjf/|)1}[]-_~<>!lI;:,^`'. ")
index = 0

print('If you get an error in image location use absolute path. Otherwise use ./[...] path')

# open image
i = Image.open("/home/m/cs/python/img2ascii/2.jpg") #fixed path
# i = Image.open(input("Image location: "))
# ask for image size
size = input("ASCII art max width/height size (in characters): ")
size = int(size)
size_tuple = (size, size)
# resize image
width, height = i.size
width = width*2
if int(width) > int(height):
    height = int(size / (width / height))
    width = size
else:
    width = int(size / (height / width))
    height = size
i = i.resize((width,height))

# convert rgb to grayscale
i = i.convert("L")

# getting all the pixels
tuple_list = list(i.getdata())

# write to the output file
o = open('output.txt', 'w')

while index < len(tuple_list): 
    if index % width == 0 and index != 0:
        o.write('\n')          
    o.write(ascii_chars[int((tuple_list[index])/5)-1])       #line 38
    index += 1

# close output file
o.write('\n')
o.close()

# print file output
o = open('output.txt', 'r')
print(o.read())
o.close()

这是完整的回溯:

Exception has occurred: IndexError
list index out of range
  File "/home/m/cs/python/img2ascii/main.py", line 38, in <module>
    o.write(ascii_chars[int((tuple_list[index])/5)-1])
IndexError: list index out of range

while 语句试图做的是将每个像素的灰度值除以 5(因为我有 50 个以 ASCII 字符表示的亮度级别),然后为其写入适当的 ASCII 字符。

我尝试过 ChatGPT。我还尝试了其他一些堆栈溢出问题。

此外,我尝试添加条件,例如:

if int((tuple_list[index])/5)-1 < 0:
    o.write(ascii_chars[0])

但这仍然没有丝毫作用。

python python-3.x while-loop python-imaging-library
1个回答
0
投票

问题出在表达式 int((tuple_list[index])/5)-1 最大灰度值为255。int(255/5)-1=50 ascii_chars 的最大索引是 49。您应该除以 5.1,而不是除以 5。

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