Skip to content

Instantly share code, notes, and snippets.

@Ronald-TR
Created March 30, 2018 03:13
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save Ronald-TR/1bb452206b97b470a2b74942de984acf to your computer and use it in GitHub Desktop.
Save Ronald-TR/1bb452206b97b470a2b74942de984acf to your computer and use it in GitHub Desktop.
#!/usr/bin/python3
from PIL import Image
ASCII_CHARS = [ '#', '?', '%', '.', 'S', '+', '.', '*', ':', ',', '@']
def scale_image(image, new_width=100):
"""Resizes an image preserving the aspect ratio.
"""
(original_width, original_height) = image.size
aspect_ratio = original_height/float(original_width)
new_height = int(aspect_ratio * new_width)
new_image = image.resize((new_width, new_height))
return new_image
def convert_to_grayscale(image):
return image.convert('L')
def map_pixels_to_ascii_chars(image, range_width=25):
"""Maps each pixel to an ascii char based on the range
in which it lies.
0-255 is divided into 11 ranges of 25 pixels each.
"""
pixels_in_image = list(image.getdata())
pixels_to_chars = [ASCII_CHARS[int(pixel_value/range_width)] for pixel_value in pixels_in_image]
return "".join(pixels_to_chars)
def convert_image_to_ascii(image, new_width=100):
image = scale_image(image)
image = convert_to_grayscale(image)
pixels_to_chars = map_pixels_to_ascii_chars(image)
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)]
return "\n".join(image_ascii)
def handle_image_conversion(image_filepath):
image = None
try:
image = Image.open(image_filepath)
except Exception as e:
print("Unable to open image file {image_filepath}.".format(image_filepath=image_filepath))
print(e)
return
image_ascii = convert_image_to_ascii(image)
print(image_ascii)
if __name__=='__main__':
import sys
image_file_path = sys.argv[1]
handle_image_conversion(image_file_path)
@dutta-alankar
Copy link

dutta-alankar commented May 24, 2018

I have made some modifications to save to text file and working in python3
Usage: python /path/to/this/python/file /path/to/image/file

from PIL import Image
import os

ASCII_CHARS = [ '#', '?', '%', '.', 'S', '+', '.', '*', ':', ',', '@']

def scale_image(image, new_width=100):
    """Resizes an image preserving the aspect ratio.
    """
    (original_width, original_height) = image.size
    aspect_ratio = original_height/float(original_width)
    new_height = int(aspect_ratio * new_width)

    new_image = image.resize((new_width, new_height))
    return new_image

def convert_to_grayscale(image):
    return image.convert('L')

def map_pixels_to_ascii_chars(image, range_width=25):
    """Maps each pixel to an ascii char based on the range
    in which it lies.

    0-255 is divided into 11 ranges of 25 pixels each.
    """

    pixels_in_image = list(image.getdata())
    pixels_to_chars = [ASCII_CHARS[pixel_value//range_width] for pixel_value in
            pixels_in_image]

    return "".join(pixels_to_chars)

def convert_image_to_ascii(image, new_width=100):
    image = scale_image(image)
    image = convert_to_grayscale(image)

    pixels_to_chars = map_pixels_to_ascii_chars(image)
    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)]

    return "\n".join(image_ascii)

def handle_image_conversion(image_filepath):
    image = None
    try:
        image = Image.open(image_filepath)
    except Exception as e:
        print("Unable to open image file {image_filepath}.".format(image_filepath=image_filepath))
        print(e)
        return

    image_ascii = convert_image_to_ascii(image)
    f = open(os.path.splitext(image_filepath)[0]+'.txt','w')
    f.write(image_ascii)
    f.close()

if __name__=='__main__':
    import sys

    image_file_path = sys.argv[1]
    handle_image_conversion(image_file_path)

@Ronald-TR
Copy link
Author

Ronald-TR commented May 24, 2018

Nice!
Thanks for sharing the changes!
For everyone who came from somewhere else instead of this article.
This is not my own code, I just updated the above code for Python 3.

@linwoodc3
Copy link

linwoodc3 commented Sep 29, 2018

Hi. Is it possible to turn specific text into an image? Let's say I have a paragraph of text and I want to put that in the shape of a heart. Is that possible with this code? @Ronald-TR @dutta-alankar

@Ronald-TR
Copy link
Author

Ronald-TR commented Nov 27, 2018

@linwoodc3 unfortunately not, this is still an ascii art generator. With OpenCV you can do what you want more easily, please check the docs of python-opencv! Cheers! (and sorry for the long time to answer, gist not notified me :'{ )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment