Skip to content

Instantly share code, notes, and snippets.

@vindard
Last active May 4, 2020 17:43
Show Gist options
  • Save vindard/f9b14e46ba8058caa009d175932acc88 to your computer and use it in GitHub Desktop.
Save vindard/f9b14e46ba8058caa009d175932acc88 to your computer and use it in GitHub Desktop.
Refactored code based on this repo (https://github.com/homeless-field/ascii_art)
import sys
from PIL import Image
# Setup image
img_orig = Image.open("ctycgchr36231.jpg")
scale = 3
w, h = img_orig.width, img_orig.height
image = img_orig.resize( (w//scale, h//scale) )
# Setup ascii variables
ascii_pixels = ('..', '**', '$$')
max_rgb = max(range(256))
rgb_sub_range = max_rgb / len(ascii_pixels)
def ascii_from_rgb(x, y):
r, g, b = image.getpixel((x, y))
avg_brightness = sum([r, g, b]) / len([r, g, b])
pixel_index = int(avg_brightness / rgb_sub_range)
ascii_pixel = ascii_pixels[pixel_index]
return f"{ascii_pixel}" if x < (image.width - 1) \
else f"{ascii_pixel}\n"
def ascii_art_generator(image):
return (
ascii_from_rgb(x, y)
for y in range(image.height)
for x in range(image.width)
)
if __name__ == "__main__":
ascii_art = ascii_art_generator(image)
# Pass an optional filename with '-f' flag to save to file:
# $ python ascii_art.py -f result.txt
filename, args = "", sys.argv[1:]
# Trying Python 3.8 walrus operator
if (len(args) >= 2) and ('-f' in args[0]) and (filename := args[1]):
with open(filename, 'w') as f:
for c in ascii_art:
f.write(c)
else:
print(''.join(ascii_art))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment