This repository has been archived by the owner on May 2, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 84
/
community_version.py
239 lines (189 loc) · 8.44 KB
/
community_version.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
# this project requires Pillow installation: https://pillow.readthedocs.io/en/stable/installation.html
# code credit goes to: https://www.hackerearth.com/practice/notes/beautiful-python-a-simple-ascii-art-generator-from-images/
# code modified to work with Python 3 by @aneagoie
# Usage Instructions:
# 1. Clone this repo as it is!
# 2. Open Terminal/cmd prompt, change the directory to the location of this repo
# 3. Run the cmd 'python3 community_version.py -i image_file_path'
# 4. Get the output on cmd window and checkout the saved text file too
# 5. To see what more the script can do with ascii, run: 'python3 community_version.py --help`
import argparse
# Note:
# Please change the instructions according to the fix or features contributed code.
# comment the contribution to make others understand easy (follow the best comment practices).
import logging.config
import os
from PIL import Image, ImageDraw, ImageOps
from logger_config import LOGGING_CONFIG
logging.config.dictConfig(LOGGING_CONFIG)
logger = logging.getLogger(__name__)
import argparse
# ASCII_CHARS = ['#', '?', '%', '.', 'S', '+', '.', '*', ':', ',', '@']
# ASCII_CHARS = [ '#', '@', '$', '0', '+', '?', '!', '=', '&', ';', '-', '*', ':', '~', ',', '.']
ALLOWED_EXTENSIONS = ["jpg", "jpeg", "png", "bmp", "jfif", "tiff", "gif"]
DEFAULT_KEY = "./keys/akey.txt"
def get_ascii_key(akey_filepath):
"""Pull a specific keyfile to index for ASCII rendering
"""
with open(akey_filepath) as keyfile:
return list(keyfile.read().strip())
def scale_image(image, new_width, font_aspect_ratio=0.542):
"""Resizes an image preserving the aspect ratio.
Default font aspect ratio is 'System' font.
"""
(original_width, original_height) = image.size
aspect_ratio = original_height / float(original_width)
new_height = int(aspect_ratio * new_width * font_aspect_ratio)
return image.resize((new_width, new_height))
def convert_to_grayscale(image):
return image.convert('L')
def map_pixels_to_ascii_chars(image, key):
"""Maps each pixel to an ascii char based on the range
in which it lies.
Using the default key 'akey.txt' 0-255 is divided into
16 ranges of 16 pixels each.
"""
ascii_key = get_ascii_key(key)
range_width = 256/len(ascii_key)
pixels_in_image = list(image.getdata())
pixels_to_chars = [ascii_key[int(pixel_value / range_width)]
for pixel_value in pixels_in_image]
return "".join(pixels_to_chars)
def convert_image_to_ascii(image, key, new_width):
logger.debug("Converting the image to ascii")
image = scale_image(image, new_width)
image = convert_to_grayscale(image)
pixels_to_chars = map_pixels_to_ascii_chars(image, key)
len_pixels_to_chars = len(pixels_to_chars)
image_ascii = [pixels_to_chars[index: index + new_width]
for index in range(0, len_pixels_to_chars, new_width)]
logger.debug("Successfully converted the image to ascii")
return "\n".join(image_ascii)
def write_to_txtfile(image_txt, out_file):
logger.debug("Saving ASCII into specified text file")
with open(out_file, "w") as text_file:
text_file.write(image_txt)
logger.debug("Successfully Saved ASCII into text file")
def save_as_img(image_txt, out_file):
logger.debug("Saving ASCII into specified image file")
"""Takes the ASCII text as input, writes it to an image file and the saves
it to the path inputted."""
if os.path.isfile(out_file):
logger.error(f"{out_file} already exists.")
return
# Make a blank white image.
text_list = image_txt.split("\n")
"""Every row takes 10px, so height should be len(text_list) * 10 and every
letter of a row takes 6px, so len(elements in a row) * 6 would get the
correct width."""
img = Image.new(
'RGB', (len(text_list[0]) * 6, len(text_list) * 10), color='white')
draw = ImageDraw.Draw(img) # Creates an ImageDraw object of img.
for i in range(len(text_list)):
# Draws the text on the blank image.
draw.text((0, (10 * i)), text_list[i], (0, 0, 0))
try:
img.save(out_file)
logger.debug("Successfully saved ASCII into specified image file")
except ValueError as err:
logger.error(err)
logger.info(f"Enter a valid path with a valid file extension.\nAllowed Extensions: {', '.join(ALLOWED_EXTENSIONS)}")
def handle_image_conversion(image_file_path, key_file_path, width=150, mirror=False):
try:
image = Image.open(image_file_path)
except Exception as err:
print(f"Unable to open image file {image_file_path}.")
logger.error(err)
else:
if mirror:
image = ImageOps.mirror(image)
return convert_image_to_ascii(image, key_file_path, width)
def validate_file_path(path):
logger.debug("Validating the file path")
if not os.path.isfile(path):
print(f'Invalid input. Could not find file at "{path}".')
print('A test image is located at "example/ztm-logo.png"')
path = input('Enter a valid file path: ')
validate_file_path(path)
logger.debug("Successfully Validated the file path")
return path
def validate_key_path(path):
logger.debug("Validating the key path")
if not os.path.isfile(path):
logger.warning(f"Invalid key file. Could not find '{path}'")
return DEFAULT_KEY
logger.debug("Successfully validated the key path")
return path
def is_supported(path: str) -> bool:
"""
Checks if the given path is for a supported file.
It uses the file extension in the path and compares
it against ALLOWED_EXTENSIONS.
"""
_, ext = os.path.splitext(path)
return ext[1:].lower() in set(ALLOWED_EXTENSIONS)
def validate_file_extension(path):
logger.debug("Validating the file extension of input file")
if not is_supported(path):
print(f"File not supported. Make sure it is one of {', '.join(ALLOWED_EXTENSIONS)}.")
path = input('Enter a valid image path: ')
validate_file_extension(path)
logger.debug("Successfully Validated the file extension of input file")
return path
def _parse_args():
"""
Parses command-line arguments.
The function returns an object that has the added arguments as attributes.
To add a new argument, add another entry of 'parser.add_argument(...)'
and specify the details you want.
The docs for argparse are at: https://docs.python.org/3/library/argparse.html
"""
parser = argparse.ArgumentParser(description="Converts images into ASCII art.")
parser.add_argument("-i", "--image",
help="File path to input image (default: %(default)s)",
default="./example/ztm-logo.png",
action="store")
parser.add_argument("-o", "--outfile",
help="write the ASCII into this file instead of the default STDOUT",
nargs="?",
action="store")
parser.add_argument("-k", "--key",
help="Key of ASCII characters to use in rendering",
default=DEFAULT_KEY,
action="store")
parser.add_argument("-s", "--saveimg",
help="Save the ASCII into an image file",
nargs="?",
action="store")
parser.add_argument("-m", "--mirror",
help="Mirror image horizontally",
action="store_true")
parser.add_argument("-w", "--width",
help="New image width in pixels (default: %(default)s). Max=300. ",
type=int,
choices=range(1,301),
default=150,
action="store",
metavar='')
return parser.parse_args()
def main():
args = _parse_args()
mirror = False
if args.mirror:
mirror = True
image_file_path = validate_file_extension(args.image)
image_file_path = validate_file_path(image_file_path)
logger.info(image_file_path)
ascii_key_path = validate_key_path(args.key)
logger.info(ascii_key_path)
width = args.width
logger.info(f'width={width}px')
ascii_img = handle_image_conversion(image_file_path, ascii_key_path, width, mirror)
if args.outfile:
write_to_txtfile(ascii_img, args.outfile)
if args.saveimg:
save_as_img(ascii_img, args.saveimg)
else:
print(ascii_img)
if __name__ == '__main__':
main()