forked from smaranjitghose/ArtCV
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ascii_art.py
49 lines (39 loc) · 1.43 KB
/
ascii_art.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import PIL.Image
# ascii characters used to build the output text
ASCII_CHARS = ["@", "#", "S", "%", "?", "*", "+", ";", ":", ",", "."]
# resize image according to a new width
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 grayify(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):
# attempt to open image from user-input
path = input("Enter a valid pathname to an image:\n")
try:
image = PIL.Image.open(path)
except:
print(path, " is not a valid pathname to an image.")
return
# convert image to ascii
new_image_data = pixels_to_ascii(grayify(resize_image(image)))
# format
pixel_count = len(new_image_data)
ascii_image = "\n".join([new_image_data[index:(index+new_width)] for index 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)
# run program
main()