Welcome, guest | Sign In | My Account | Store | Cart

ASCII Art Generator (Image to ASCII Art Converter)

Input file maybe JPG, PNG, GIF etc. Output file name maybe output.txt etc.

Python, 45 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# ASCII Art Generator (Image to ASCII Art Converter)
# FB - 20160925
import sys
if len(sys.argv) != 3:
    print "USAGE:"
    print "[python] img2asciiart.py InputImageFileName OutputTextFileName"
    print "Use quotes if file paths/names contain spaces!"
    sys.exit()
inputImageFileName = sys.argv[1]
OutputTextFileName = sys.argv[2]

from PIL import Image, ImageDraw, ImageFont
font = ImageFont.load_default() # load default bitmap monospaced font
(chrx, chry) = font.getsize(chr(32))
# calculate weights of ASCII chars
weights = []
for i in range(32, 127):
    chrImage = font.getmask(chr(i))
    ctr = 0
    for y in range(chry):
        for x in range(chrx):
            if chrImage.getpixel((x, y)) > 0:
                ctr += 1
    weights.append(float(ctr) / (chrx * chry))

image = Image.open(inputImageFileName)
(imgx, imgy) = image.size
imgx = int(imgx / chrx)
imgy = int(imgy / chry)
# NEAREST/BILINEAR/BICUBIC/ANTIALIAS
image = image.resize((imgx, imgy), Image.BICUBIC)
image = image.convert("L") # convert to grayscale
pixels = image.load()
output = open(OutputTextFileName, "w")
for y in range(imgy):
    for x in range(imgx):
        w = float(pixels[x, y]) / 255
        # find closest weight match
        wf = -1.0; k = -1
        for i in range(len(weights)):
            if abs(weights[i] - w) <= abs(wf - w):
                wf = weights[i]; k = i
        output.write(chr(k + 32))
    output.write("\n")
output.close()

2 comments

jameskafka 7 years, 5 months ago  # | flag

Hi,

A fresh noob here. I receive the following error while running the program:

./image2ascii.py: line 4: syntax error near unexpected token sys.argv' ./image2ascii.py: line 4:if len(sys.argv) != 3:'

any suggestion?

FB36 (author) 7 years, 5 months ago  # | flag

Maybe you used copy-paste instead of the Download button on this page and some part(s) of the code not copied correctly? (Copy-paste sometimes can change some characters and make the code not run correctly.)

Also another possibility is that this is Python 2.7.x code and you trying to run it using Python 3.x? (I never tested it running it using Python 3.x)

Also this code requires installing PIL library for Python to work. (Search how to install PIL for Python if you didn't do it before.)