用python把小姐姐变成代码 ASCII艺术
参考链接:
Turn any image into ASCII art! (Easy Python PIL Tutorial)
https://www.youtube.com/watch?v=v_raWlX7tZY
Jupyter note book codes:
from PIL import Image
image = Image.open("pikachu.jpg")
image
image.size
width = image.size[0]
height = image.size[1]
width, height
height = int((height/width) * 200)
width = 100
width, height
image_resized = image.resize((width, height))
image_resized
# # https://www.geeksforgeeks.org/python-pil-image-convert-method/
image_grayed = image_resized.convert("L")
image_grayed
pixels = image_grayed.getdata()
type(pixels)
ASCII_CHARS = ["@", "#", "S", "%", "?", "*", "+", ";", ":", ",", "."]
len(ASCII_CHARS)
list_pixels = [p for p in pixels]
[len(list_pixels) ,max(list_pixels), min(list_pixels), sum(list_pixels)/len(list_pixels)]
myTuple = ("John", "Peter", "Vicky")
x = " ".join(myTuple)
print(x)
[0//25, 30//25, 60//25, 240//25, 250//25]
characters = "".join([ASCII_CHARS[pixel//25] for pixel in pixels])
characters
print(characters[width*0: width*1])
print(characters[width*1: width*2])
print(characters[width*2: width*3])
print(characters[width*3: width*3])
print(characters[width*4: width*4])
for i in range(len(characters)):
ii = i + 1
if (ii%width !=0):
print(characters[i], end="")
else:
print(characters[i], end="\n")
for i in range(len(characters)):
ii = i + 1
if (ii%width !=0):
print(characters[i], end="")
else:
print(characters[i], end="\n")
ascii_image = "\n".join(characters[i:(i+width)] for i in range(0, len(characters), width))
print(ascii_image)
Original Codes on the Youtube
from PIL import Image
ASCII_CHARS = ["@", "#", "S", "%", "?", "*", "+", ";", ":", ",", "."]
# resize image according to a new width
def resize_image(image, new_width=100):
width, height = image.size
ratio = height / width
new_height = int(new_width * ratio)
resized_image = image.resize((new_width, new_height))
return(resized_image)
# convert each pixel to grayscale
def grayify(image):
grayscale_image = image.convert("L")
return(grayscale_image)
# convert pixels to 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):
# attempt to open image from user-input
path = input("Enter a valid pathname to an image:\n")
try:
image = Image.open(path)
except:
print(path, "it is not a valid pathname to an image")
new_image_data = pixels_to_ascii(grayify(resize_image(image)))
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(ascii_image)
with open("ascii_image.txt", "w") as f:
f.write(ascii_image)
main()