将图像转换为ASCII艺术



我使用了一个教程来编程这个图像到ASCII艺术转换器,但它给了我一个错误。下面是代码:

import PIL.Image
from tkinter import filedialog
# Ascii characters
ASCII_CHARS = ["@", "#" ,"S" ,"%" ,"?" ,"*" ,"+" , ";", ":", "," "."]
def resize_image(image,new_width=100):
width,height =image.size
ratio = height / width / 1.65
new_height = int(new_width*ratio)
resized_image = image.resize((new_width,new_height))
return(resized_image)
# convert each pixel to grayscale
def grayscaler(image):
grayscale_image = image.convert("L")
return(grayscale_image)
#convert pixels to a string of ASCII characters
def pixels_to_ascii(image):
pixels = image.getdata()
characters = "".join([ASCII_CHARS[pixel // 25]for pixel in pixels])
return(characters)
def main(new_width=100):
# Get image path
path = filedialog.askopenfilename(title="Select an image", filetypes=(("Image File", "*.png"),("all files", "*.*")))
try:
image = PIL.Image.open(path)
except:
print(path, "is not a valid pathname to an image")

# convert image to ascii
new_image_data = pixels_to_ascii(grayscaler(resize_image(image)))
# format
pixel_count = len(new_image_data)
ascii_image = "n".join(new_image_data[i:(i+new_width)] for i in range(0, pixel_count, new_width))
# print result
print(ascii_image)
# save result to "ascii_image.txt"
with open("ascii_image.txt", "w") as f:
f.write(ascii_image)
main()

应该是打印和保存ascii艺术。相反,它在第34行和第22行给了我这个错误:

Traceback (most recent call last):
File "c:UsersFornaDocumentsPYTHONImage to Asciimain.py", line 47, in <module>
main()
File "c:UsersFornaDocumentsPYTHONImage to Asciimain.py", line 34, in main
new_image_data = pixels_to_ascii(grayscaler(resize_image(image)))
File "c:UsersFornaDocumentsPYTHONImage to Asciimain.py", line 22, in pixels_to_ascii
characters = "".join([ASCII_CHARS[pixel // 25]for pixel in pixels])
File "c:UsersFornaDocumentsPYTHONImage to Asciimain.py", line 22, in <listcomp>
characters = "".join([ASCII_CHARS[pixel // 25]for pixel in pixels])
IndexError: list index out of range
如果有人能帮我,那就太好了。

错误出现ASCII_CHARS = ["@", "#" ,"S" ,"%" ,"?" ,"*" ,"+" , ";", ":", "," "."]","之后没有,

相关内容

  • 没有找到相关文章

最新更新