Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sys
- from PIL import Image
- def prepare_image(image, width, ascii_aspect_ratio=0.5):
- """resize and grayscale"""
- original_width, original_height = image.size
- aspect_ratio = original_height / original_width
- height = int(width * aspect_ratio * ascii_aspect_ratio)
- resized_image = image.resize((width, height))
- return resized_image.convert('L')
- def convert_to_ascii(image, width):
- """map pixels to chars and compose to width"""
- CHARS = ['#', '&', 'S', '?', '/', '=', '+', ',', '.', ' ']
- prepared_image = prepare_image(image, width)
- step = 255 // (len(CHARS) - 1)
- pixels_to_chars = "".join(CHARS[brightness // step] for brightness in prepared_image.getdata())
- ascii_image = (pixels_to_chars[index: index + width] for index in range(0, len(pixels_to_chars), width))
- return "\n".join(ascii_image)
- if __name__ == '__main__':
- """usage: python3 ascii_art.py 512.jpg 120"""
- image_file = sys.argv[1]
- width = int(sys.argv[2])
- img = Image.open(image_file)
- ascii = convert_to_ascii(img, width)
- print(ascii)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement