实例来源实验楼网站,没事可以多逛逛,在此多谢实验楼的无私分享
1 from PIL import Image 2 import argparse 3 4 """ 5 description: 6 将图片像素转换为字母重新绘制输出 7 """ 8 9 ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ") 10 11 parser = argparse.ArgumentParser() 12 13 parser.add_argument('file') 14 parser.add_argument('-o','--output') 15 parser.add_argument('--width',type=int,default=80) 16 parser.add_argument('--height',type=int,default= 80) 17 18 args = parser.parse_args() 19 20 IMG = args.file 21 WIDTH = args.width 22 HEIGHT = args.height 23 OUTPUT = args.output 24 25 def get_char(r,g,b,alpha = 256): 26 if alpha == 0: 27 return ' ' 28 length = len(ascii_char) 29 gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b) 30 unit = (256.0 + 1)/length 31 return ascii_char[int(gray/unit)] 32 33 def main(): 34 im = Image.open(IMG) 35 im = im.resize((WIDTH,HEIGHT),Image.NEAREST) 36 txt = "" 37 for i in range(HEIGHT): 38 for j in range(WIDTH): 39 txt += get_char(*im.getpixel((j,i))) 40 txt += '\n' 41 print txt 42 43 if __name__=="__main__": 44 main()
在文件所在的当前目录存放待转换图片,直接执行命令: python convert.py test.png