# the packages neededfrom PIL import Image
import argparse
# All of the ASCii characters are stored in a list,# can be modified by your own characters
ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")
# construct a argument parse instance
parse = argparse.ArgumentParser()
# add arguments to parse
parse.add_argument('file')
parse.add_argument('-o', '--output')
parse.add_argument('--width', type=int, default=80)
parse.add_argument('--height', type=int, default=80)
args = parse.parse_args()
# read arguments to variables
IMG = args.file # this argument is the file name
WIDTH = args.width # the width of the img should be
HEIGHT = args.height # the height of the img should be
OUTPUT = args.output # the file to store the char-picturedefget_char(r, g, b, alpha = 256):"""Translate a tuple of RGB data to gray scale
Using a simple algorithm: gray = 0.2126*r + 0.7152*g + 0.0722*b
and some gray level value correspond to a specific char
"""
length = len(ascii_char)
gray = int(0.2126*r + 0.7152*g + 0.0722*b)
unit = (256.0+1)/length
if alpha == 0: # corresponding to the RGB=(0, 0, 0)return' 'return ascii_char[int(gray/unit)]
if __name__ == '__main__':
# If this python file is the main file, run following codes
im = Image.open(IMG) # open the Image file
im = im.resize((WIDTH, HEIGHT), Image.NEAREST) # reset the size of the image
txt = ""for i in range(HEIGHT):
for j in range(WIDTH):
txt += get_char(*im.getpixel((j, i))) # *im.getpixel unzipped to: r, g, b, alpha
txt += '\n'print txt
if OUTPUT: # write with specific file namewith open(OUTPUT,'w') as f:
f.write(txt)
else: # write with default file namewith open("output.txt",'w') as f:
f.write(txt)