a shot of dev knowledge

Related tags

How to generate ASCII Art from image using Python

In this shot, you will learn how to generate ASCII art from an image using Python.

Steps to convert image to ASCII character:

  • Load an image
  • Resize Image
  • Convert image to GreyScale
  • Convert GreyScale data of each pixel into respective ASCII character

Load an image

We can load an image using the PIL image Library:

import PIL.Image

def main():
    path = input("Enter the path to the image field : \n")
        image = PIL.Image.open(path)
        print(path, "Unable to find image ");

The above code reads the image from the path given by the user. If the image doesn’t exist on the given path, the program will show an error message.

Define ASCII list

Let’s create a list of ASCII characters:

ASCII_CHARS = ["@", "#", "$", "%", "?", "*", "+", ";", ":", ",", "."]

The ASCII characters are arranged from darkest to lightest, meaning the darkest pixel will be replaced with @ and lightest with .

Resize image

We need to convert the image to a smaller width and height so that it doesn’t result in too large of text size. To find the new_height, multiply new_width with old_height and divide by old_width.

def resize(image, new_width = 100):
    width, height = image.size
    new_height = new_width * old_height / old_width
    return image.resize((new_width, new_height))

Convert image to GreyScale

We can use the convert method on the image with L option to get a GreyScale image:

def to_greyscale(image):
    return image.convert("L")

Convert GreyScale Image to ASCII character

To convert the image to ASCII character first, get each pixel value(0-255) and the corresponding ASCII character and join them as a string:

def pixel_to_ascii(image):
    pixels = image.getdata()
    ascii_str = "";
    for pixel in pixels:
        ascii_str += ASCII_CHARS[pixel//25];
    return ascii_str

Now, we have a to_greyscale method to convert our image to a GreyScale image and a pixel_to_ascii method to convert our GreyScale image to ASCII string. Once we get the ASCII string of the image, we need to split the string based on the image’s width and save it in a file:

import PIL.Image
def main():
    path = input("Enter the path to the image fiel : \n")
        image = PIL.Image.open(path)
        print(path, "Unable to find image ")
    #resize image
    image = resize(image);
    #convert image to greyscale image
    greyscale_image = to_greyscale(image)
    # convert greyscale image to ascii characters
    ascii_str = pixel_to_ascii(greyscale_image)
    img_width = greyscale_image.width
    ascii_str_len = len(ascii_str)
    #Split the string based on width  of the image
    for i in range(0, ascii_str_len, img_width):
        ascii_img += ascii_str[i:i+img_width] + "\n"
    #save the string to a file
    with open("ascii_image.txt", "w") as f:

Related tags

View all Courses
Related Courses
Related Courses
View all Courses

Keep Exploring