-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.py
77 lines (56 loc) · 2.4 KB
/
app.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import sys
import os
import argparse
from PIL import Image
ASCII_CHARS = "`^\",:;Il!i~+_-?][}{1)(|\\/tfjrxnuvczXYUJCLQ0OZmwqpdbkhao*#MW&8%B@$"
MAX_PIXEL_VALUE = 255
MAX_HEIGHT = 100 # Higher values dont fit well in the console
def build_pixel_matrix(image):
if image.height > MAX_HEIGHT:
half_height = image.height // 2
new_height = half_height if half_height <= MAX_HEIGHT else MAX_HEIGHT
new_width = int(new_height * image.width / image.height) # Conserving ratio
image = image.resize((new_width, new_height), Image.ANTIALIAS) # We resize the image
# To build the pixel matriz we get the average of the pixel, each pixel in the image has the format (R, G, B)
pixel_matrix = [[(sum(image.getpixel((x, y))) / 3) for x in range(image.width)] for y in range(image.height)]
return pixel_matrix
def convert_to_ascii(pixel_matrix):
# We try to map our pixels in the matrix to the ascii list
# for this we do a cross-multiplication
# P --> MAX_PIXEL_VALUE
# ? ---> len(ASCII_CHARS)
# We rest 1 at the end so we dont get an index out of range when ? is the last element in the ASCII_CHARS
ascii_matrix = []
for row in pixel_matrix:
ascii_row = []
for pixel in row:
ascii_row.append(ASCII_CHARS[int(len(ASCII_CHARS)*(pixel/MAX_PIXEL_VALUE)-1)])
ascii_matrix.append(ascii_row)
return ascii_matrix
def ascii_art(ascii_matrix, filename=None):
if filename:
filename = f'{filename}.txt'
with open(filename, 'w') as f:
for row in ascii_matrix:
line = [p for p in row]
f.write("".join(line)+'\n')
else:
for row in ascii_matrix:
line = [p for p in row]
print("".join(line))
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Image2ASCII Converter')
parser.add_argument('filename', help='File to convert')
parser.add_argument('-f', help='If you want to store the ASCII as a txt file', action='store_true')
args = parser.parse_args()
filepath = args.filename
filename = None
if args.f:
filename = os.path.splitext(filepath)[0]
try:
image = Image.open(filepath)
except Exception:
raise SystemExit(f"File was not found.")
pixel_matrix = build_pixel_matrix(image)
ascii_matrix = convert_to_ascii(pixel_matrix)
ascii_art(ascii_matrix, filename)