Advertisement
Guest User

Untitled

a guest
Feb 21st, 2017
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.06 KB | None | 0 0
  1. import sys
  2.  
  3. from PIL import Image
  4.  
  5.  
  6. def prepare_image(image, width, ascii_aspect_ratio=0.5):
  7. """resize and grayscale"""
  8. original_width, original_height = image.size
  9. aspect_ratio = original_height / original_width
  10. height = int(width * aspect_ratio * ascii_aspect_ratio)
  11. resized_image = image.resize((width, height))
  12. return resized_image.convert('L')
  13.  
  14.  
  15. def convert_to_ascii(image, width):
  16. """map pixels to chars and compose to width"""
  17. CHARS = ['#', '&', 'S', '?', '/', '=', '+', ',', '.', ' ']
  18. prepared_image = prepare_image(image, width)
  19. step = 255 // (len(CHARS) - 1)
  20.  
  21. pixels_to_chars = "".join(CHARS[brightness // step] for brightness in prepared_image.getdata())
  22. ascii_image = (pixels_to_chars[index: index + width] for index in range(0, len(pixels_to_chars), width))
  23.  
  24. return "\n".join(ascii_image)
  25.  
  26.  
  27. if __name__ == '__main__':
  28. """usage: python3 ascii_art.py 512.jpg 120"""
  29. image_file = sys.argv[1]
  30. width = int(sys.argv[2])
  31. img = Image.open(image_file)
  32.  
  33. ascii = convert_to_ascii(img, width)
  34. print(ascii)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement