Making cool looking ASCII art in python
In this post we are going to build a simple python program to build the ASCII art in python, so let’s get started.
How we are going to build this?
- Resizing the image to the desired width with maintaing the desired ratio
- Then converting the image to the gray scaled image
- Swapping the pixels with the ASCII character to the intensity of the individual pixel
The python library that we are going to use is the PILLOW, to install it run
pip install Pillow
Then import the Image class from it and also declare the list of ASCII symbols which are arranged in the decreasing order of the intensity
from PIL import Image
ASCII_CHARS = ["@", "#", "S", "%", "?", "*", "+", ";", ":", ",", "."]
Firstly start-off by making a resize function which will resize the image and maintain the aspect ratio and will return the resized image
def resize (image, new_width=120):
width, height = image.size
ratio = height/width
new_height = int(new_width * ratio)
resized_image = image.resize((new_width, new_height))
return(resized_image)
Now we are going to turn the image into the grayscaled image
def gray_img(image):
grayscale_image = image.convert("L")
return(grayscale_image)
Now we are all set with the gray image, it’s time to swap the pixels from the original image by defining the pixels_to_ascii function
def pixels_to_ascii(image):
pixels = image.getdata()
characters = "".join([ASCII_CHARS[pixel//25] for pixel in pixels])
return(characters)
At last defining the main function to execute the whole program
def main(new_width=120):
path = input("Enter a file name")
new_image = pixels_to_ascii(gray_img(resize(image)))
pixel_count = len(new_image)
ascii_image = "\n".join([new_image [index:(index+new_width)] for index in range(0, pixel_count, new_width)])
print(ascii_image)
with open("ascii_image.txt", "w") as f:
f.write(ascii_image)
Now run the program by calling the main function
You will see the file called “ascii_image.txt” it will have the cool looking ascii image.
Program
from PIL import Image
ASCII_CHARS = ["@", "#", "S", "%", "?", "*", "+", ";", ":", ",", "."]
def resize (image, new_width=120):
width, height = image.size
ratio = height/width
new_height = int(new_width * ratio)
resized_image = image.resize((new_width, new_height))
return(resized_image)
def gray_img(image):
grayscale_image = image.convert("L")
return(grayscale_image)
def pixels_to_ascii(image):
pixels = image.getdata()
characters = "".join([ASCII_CHARS[pixel//25] for pixel in pixels])
return(characters)
def main(new_width=120):
path = input("Enter a file name")
new_image = pixels_to_ascii(gray_img(resize(image)))
pixel_count = len(new_image)
ascii_image = "\n".join([new_image [index:(index+new_width)] for index in range(0, pixel_count, new_width)])
print(ascii_image)
with open("ascii_image.txt", "w") as f:
f.write(ascii_image)
main()
Original Image
ASCII Image
Reference
Kite’s official YouTube channel https://www.youtube.com/watch?v=v_raWlX7tZY