Skip to content
scipython.com

ASCII art

Posted on

ASCII art depicts an image with the printable characters of the ASCII (American Standard Code for Information Interchange) character set, each character standing for the brightness of a small region of the image through the density of its glyph. This post introduces a Python script that converts an image into ASCII art for display in a terminal, and shows how measuring the ink coverage of the glyphs in a particular font improves the choice of characters.

The script described here divides an image into a grid of cells, one for each character of the output, and draws each cell with a character whose glyph is as dense as the cell is bright: $ and @ for the brightest cells, and . and a space for the darkest. ASCII art of this kind is tone-based: it reproduces the brightness of an image rather than its outlines.

Saturn and its rings, tilted towards the viewer, drawn in light characters on a dark ground: dense letters such as 0, Z, m and q for the bright disc, sparser letters and punctuation for the rings and the gaps between them, and spaces for the black sky.
Saturn as ASCII art, 98 characters wide, from an image taken by the Hubble Space Telescope on 22 March 2004 (image: NASA, ESA and E. Karkoschka, University of Arizona; source).

Character sequence

The characters are those of a sequence of 70 given by Paul Bourke in Character representation of grey scale images (1997), which runs from the densest glyph to a space:

text
$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,"^`'.

A dense glyph lights more of its cell than a sparse one when the text is light on a dark background, as in a terminal with a dark theme, and so stands for a bright region of the image. On paper, or in a terminal with dark text on a light background, the reverse is true: Bourke gives the sequence as running from black to white, and the script's --invert option inverts the image before it is converted.

Implementation

The script, ascii_art.py, converts the image to greyscale with Pillow, whose convert("L") method uses the ITU-R 601-2 luma transform, \(L = 0.299R + 0.587G + 0.114B\). It then resizes the image so that each pixel corresponds to one character, by Lanczos resampling, which takes a weighted average of the pixels around each cell. A character cell is taller than it is wide, so the image is given fewer rows than its proportions alone would give, by the factor --aspect, the width of a cell divided by its height. This depends on the font and the line spacing: it is 0.5 by default, and \(0.6/1.32 = 0.45\) for JetBrains Mono, the font of the code on this page, at its natural line spacing (a cell 0.6 em wide and 1.32 em tall).

Each greyscale pixel value \(p\), from 0 to 255, is then converted to a brightness level

\[\ell = \frac{p - p_\mathrm{b}}{p_\mathrm{w} - p_\mathrm{b}},\]

clipped to the range \(0 \le \ell \le 1\), where \(p_\mathrm{b}\) is the black level (--black, 32 by default) and \(p_\mathrm{w}\) the white level (--white, 255 by default). A level \(\ell\) is drawn with the character at position \(k = (1 - \ell)(n - 1)\), rounded to the nearest integer, in the sequence of \(n\) characters numbered from 0: $ for \(\ell = 1\) and the space for \(\ell = 0\). The black level is needed because the dark background of a photograph or painting is rarely exactly black: the background of the painting in the last figure below has pixel values between about 14 and 24, which, with a black level of 0, would be drawn as a haze of " and ^ characters.

The script takes the name of the image file and, optionally, the width of the output in characters (100 by default):

python ascii_art.py saturn.jpg --width 98

The other options are listed by python ascii_art.py --help. The script is given below; its coverage function and --font option are described in the next section.

ascii_art.py
"""Render an image as ASCII art, for display in a terminal.

Each character of the output stands for the brightness of a cell of the image:
the brighter the cell, the denser the character's glyph, since the text is
taken to be light on a dark background (--invert reverses this). By default,
the character is chosen by its position in Paul Bourke's sequence; with
--font, it is the character whose glyph in that font has the closest ink
coverage.
"""

import argparse

import numpy as np
from PIL import Image, ImageDraw, ImageFont, ImageOps

# Paul Bourke's sequence of characters, from the densest glyph to a space
# (https://paulbourke.net/dataformats/asciiart/).
CHARS = r"""$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,"^`'. """


def coverage(chars, font_path, size=100):
    """Return the fraction of its cell inked by each character's glyph in the
    font, the cell being as wide as the font's advance and as tall as its
    ascent plus its descent."""
    font = ImageFont.truetype(font_path, size)
    ascent, descent = font.getmetrics()
    width = round(font.getlength(" "))
    cov = np.empty(len(chars))
    for i, char in enumerate(chars):
        cell = Image.new("L", (width, ascent + descent))
        ImageDraw.Draw(cell).text((0, 0), char, fill=255, font=font)
        cov[i] = np.asarray(cell).mean() / 255
    return cov


def brightness(img, width, aspect=0.5, black=32, white=255, invert=False):
    """Return the image, resized to width columns, as an array of brightness
    levels from 0 (at or below black) to 1 (at or above white)."""
    img = img.convert("L")
    if invert:
        img = ImageOps.invert(img)
    # A character cell is taller than it is wide (aspect is its width divided
    # by its height), so the image is given fewer rows than columns.
    height = round(width * img.height / img.width * aspect)
    img = img.resize((width, height), Image.Resampling.LANCZOS)
    p = np.asarray(img, dtype=float)
    return np.clip((p - black) / (white - black), 0, 1)


def ascii_art(level, chars=CHARS, cov=None):
    """Return the ASCII art for an array of brightness levels as a string.

    If cov is None, a level is drawn with the character at the proportional
    position in chars, from the first (level 1) to the last (level 0);
    otherwise, with the character whose coverage, as a fraction of the
    greatest in cov, is closest to it.
    """
    if cov is None:
        idx = np.rint((1 - level) * (len(chars) - 1)).astype(int)
    else:
        idx = np.abs(level[..., np.newaxis] - cov / cov.max()).argmin(axis=-1)
    glyphs = np.array(list(chars))[idx]
    return "\n".join("".join(row) for row in glyphs)


def main():
    parser = argparse.ArgumentParser(description="Render an image as ASCII art.")
    parser.add_argument("filename", help="the image file")
    parser.add_argument("-w", "--width", type=int, default=100,
                        help="the width of the output, in characters"
                             " (default: 100)")
    parser.add_argument("-a", "--aspect", type=float, default=0.5,
                        help="the width of a character cell divided by its"
                             " height (default: 0.5)")
    parser.add_argument("-b", "--black", type=int, default=32,
                        help="the black level: pixel values at or below it are"
                             " drawn as spaces (default: 32)")
    parser.add_argument("-W", "--white", type=int, default=255,
                        help="the white level: pixel values at or above it are"
                             " drawn with the densest glyph (default: 255)")
    parser.add_argument("-i", "--invert", action="store_true",
                        help="invert the image, for dark text on a light"
                             " background")
    parser.add_argument("-f", "--font",
                        help="a TrueType or OpenType font file: choose each"
                             " character by its ink coverage in this font")
    args = parser.parse_args()

    level = brightness(Image.open(args.filename), args.width, args.aspect,
                       args.black, args.white, args.invert)
    cov = coverage(CHARS, args.font) if args.font else None
    print(ascii_art(level, CHARS, cov))


if __name__ == "__main__":
    main()

Ink coverage

The mapping above draws a level \(\ell\) with a glyph whose coverage, the fraction of its cell that it inks, is proportional to \(\ell\) only if the coverage falls evenly along the sequence. Bourke's sequence is not tied to any font, and in a particular font its coverage falls neither evenly nor monotonically. The coverage function measures it by drawing each glyph with Pillow in a cell as wide as the font's advance and as tall as its ascent plus its descent, and taking the mean of the cell's pixel values; the figure below shows the result for JetBrains Mono.

A bar chart of the ink coverage, in per cent, of each of the 70 characters of the sequence, which label the bars. The coverage falls from about 24% for the dollar sign to zero for the space, but unevenly and with many reversals: the asterisk, tenth, has about 12%, while characters further along, such as the zero and the capital Q, have more than 20%. A dashed straight line from the first bar to zero at the last lies below most of the bars.
The ink coverage of the glyphs of Bourke's sequence in JetBrains Mono, as a percentage of a cell 0.6 em wide and 1.32 em tall; the last character is the space. If each glyph's coverage lay on the dashed line, the default mapping would draw each level with a coverage proportional to it.

Of the 2415 pairs of characters, 387 (16%) are in the wrong order: *, the tenth character, has little more than half the coverage of 0, the 23rd, and @ and W both have more than $. The densest glyph, @, inks only a quarter of its cell, and 47 of the 70 glyphs lie above the dashed line, which makes the mid-tones of an image too bright and reduces its contrast: a level of 0.5 is drawn as n, with 61% of the coverage of $.

With the --font option, the script instead draws each cell with the character whose coverage, as a fraction of the greatest, is closest to its level. The font should be that of the terminal in which the output is shown (on macOS, Menlo is /System/Library/Fonts/Menlo.ttc), e.g.

python ascii_art.py girl-with-a-pearl-earring.jpg --font JetBrainsMono-Regular.ttf

The image then uses the full range of coverage, from the space to @, and gains contrast, as the figure below shows: the lit side of the face and the collar are drawn in the densest glyphs, and the turban, which is dark in greyscale, recedes. The levels are matched to the coverage as they are, although pixel values are roughly proportional to the 1/2.2 power of luminance (they are gamma-encoded): matching the coverage to the luminance instead, approximately \(\ell^{2.2}\), draws the mid-tones so faintly that little more than the highlights of the painting can be seen.

Two versions, side by side, of Vermeer's Girl with a Pearl Earring as ASCII art in light characters on a dark ground: the girl looks over her shoulder, in a turban whose tail hangs down on the right. In the left version, titled Position in the sequence, the face, turban and shoulder are drawn in characters of middling density; in the right, titled Ink coverage, the lit side of the face and the collar are drawn in dense characters and the rest mostly in punctuation.
Johannes Vermeer's Girl with a Pearl Earring (c. 1665, Mauritshuis, The Hague; public domain) as ASCII art, 53 characters wide, with the characters chosen by their position in Bourke's sequence (left) and by their coverage in JetBrains Mono (right).

Extensions

Each character can be printed in the colour of its cell with the 24-bit ANSI escape code \x1b[38;2;R;G;Bm, which sets the colour of the text that follows in terminals that support it. Characters beyond ASCII give finer detail: Unicode's upper half block, ▀, printed in one colour on a background of another, divides each cell into two roughly square pixels, and its 256 Braille patterns (U+2800 to U+28FF) divide it into a grid of 2 × 4 dots. A short sequence, such as Bourke's ten-character sequence (a space followed by .:-=+*#%@), can be dithered by error diffusion, as described in the earlier post on Floyd–Steinberg dithering, to make up for its coarse steps of brightness. Finally, structure-based ASCII art follows the outlines of an image rather than its tones: Xu, Zhang and Wong approximate the lines of an image by the shapes of characters, with a measure of shape similarity that tolerates misalignment [ACM Trans. Graph. 29, 52 (2010), doi:10.1145/1778765.1778789].

Comments

Leave a comment

Optional, and never shown: only the moderator sees it.

Comments are written in Markdown (code between ``` lines) and appear once approved. Your name and comment are published; your email address, if you give one, is seen only by the moderator.