I am making an image to ASCII converter in Python.
I get IndexError out of range on line 38.
What’s strange is that on some images the program works just fine and on others it throws this error.
Here is the code:
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()
This is the full traceback:
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
What the while statement is trying to do is, divide the grayscale value of each individual pixel by 5 (because I have 50 levels of brightness represented in ASCII characters), and then write the appropriate ASCII character for it.
I tried ChatGPT. I also tried some other stack overflow questions.
Furthermore, I tried adding conditions such as:
if int((tuple_list[index])/5)-1 < 0:
o.write(ascii_chars[0])
That still doesn’t work the slightest, though.