-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconverter.py
44 lines (35 loc) · 1.17 KB
/
converter.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
import PIL
import matplotlib
# Variables
ASCII_CHARS = ["@", "#", "S", "%", "?", "*", "+", ";", ":", ",", "."]
NEW_WIDTH = 50 # Change the size
IMAGE_PATH = "input.png"
# Functions
def resize_image(image, to_width=100):
width, height = image.size
ratio = height / width
to_height = int(to_width * ratio) - 20 # Change the -20 to change the padding
resized_image = image.resize((to_width, to_height))
return resized_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
# Startup
try:
image = PIL.Image.open(IMAGE_PATH)
# convert
image = resize_image(image, NEW_WIDTH)
image = image.convert("L")
data = pixels_to_ascii(image)
# formatting
pixel_count = len(data)
ascii_image = "\n".join([data[index:(index+NEW_WIDTH)] for index in range(0, pixel_count, NEW_WIDTH)])
print(ascii_image)
# save result to "ascii_image.txt"
with open("output.txt", "w") as f:
f.write(ascii_image)
except Exception as e:
print(e)
print(IMAGE_PATH, " is not a valid path of an image.")