Python Script for Converting Images to ASCII Art
This article demonstrates a Python command‑line script that converts an input image into ASCII art by calculating each pixel’s grayscale value using the standard luminance formula and mapping it to characters from a predefined set, optionally saving the output to a file.
This tutorial explains how to transform an image into ASCII art using a Python script. The script first computes the grayscale value of each pixel with the luminance formula gray = 0.2126 * r + 0.7152 * g + 0.0722 * b , then selects a corresponding character from a predefined character set to represent that pixel.
# !/usr/bin/env python # -*- coding:utf-8 -*- from PIL import Image import argparse parser = argparse.ArgumentParser() parser.add_argument('file') # 输入文件 parser.add_argument('-o', '--output') # 输出文件 parser.add_argument('--width', type=int, default=50) # 输出字符画宽 parser.add_argument('--height', type=int, default=50) # 输出字符画高 args = parser.parse_args() IMG = args.file WIDTH = args.width HEIGHT = args.height OUTPUT = args.output ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/|()1{}[]?-_ ~<>i!lI;:,\"^`'. ") def get_char(r,g,b,alpha=256): """将256灰度映射到70个字符上""" if alpha == 0: return ' ' length = len(ascii_char) gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b) unit = (256.0 / length) index = int(gray / unit) return ascii_char[index] if __name__ == '__main__': im = Image.open(IMG) im = im.resize((WIDTH, HEIGHT), Image.NEAREST) txt = "" for i in range(HEIGHT): for j in range(WIDTH): txt += get_char(*im.getpixel((j,i))) txt += '\n' print(txt) if OUTPUT: with open(OUTPUT, 'w') as f: f.write(txt) else: with open("output.txt", 'w') as f: f.write(txt)
The script outputs the generated ASCII art to the console and optionally writes it to a file; example screenshots of the resulting text art are shown in the original article.
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.