Creating ASCII Art from Images with Python and Pillow
This tutorial demonstrates how to transform a picture into ASCII art using roughly 50 lines of Python code with the Pillow library, covering image scaling, grayscale conversion, character mapping, and saving the result as a text file while noting environment-specific display considerations.
This guide explains how to generate ASCII art from an image using Python (3.6) and the Pillow (PIL) library, requiring only about 50 lines of code.
Prerequisites include a Windows platform, Jupyter IDE, and Pillow installed via pip.
First, the image is opened, resized, and optionally blurred:
from PIL import Image
im = Image.open("C:/Users/Administrator/Desktop/柴犬.jpg")
w, h = im.size
im.thumbnail((w//2, h//2)) # scale to 50%
im.save("C:/Users/Administrator/Desktop/狗狗.jpg", "jpeg")
from PIL import Image, ImageFilter
im = Image.open("C:/Users/Administrator/Desktop/柴犬.jpg")
im2 = im.filter(ImageFilter.BLUR)
im2.save("C:/Users/Administrator/Desktop/模糊柴犬.jpg", "jpeg")The script then defines a list of ASCII characters ordered from dark to light and uses a grayscale conversion formula (gray = 0.2126 * r + 0.7152 * g + 0.0722 * b) to map each pixel to a character.
ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/|()1{}[]?-_+~<>i!lI;:,\"^`'. ")
WIDTH = 120
HEIGHT = 60
def get_char_from_pixel(r, g, b, alpha=256):
if alpha == 0:
return " "
length = len(ascii_char)
gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)
unit = (256.0 + 1) / length
return ascii_char[int(gray / unit)]
def ascii_pic_from_pil(path):
text = ""
im = Image.open(path)
im = im.resize((WIDTH, HEIGHT), Image.NEAREST)
for h in range(im.size[1]):
for w in range(im.size[0]):
text += get_char_from_pixel(*im.getpixel((w, h)))
text += "\n"
return text
def save_to_file(filename, pic_str):
with open(filename, 'w') as f:
f.write(pic_str)
img = ascii_pic_from_pil('C:/Users/Administrator/Desktop/狗狗.jpg')
save_to_file('C:/Users/Administrator/Desktop/狗狗.txt', img)Running the script creates a .txt file containing the ASCII representation, which can be viewed in a terminal; the visual result may differ depending on the terminal’s font, line height, and width settings.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.