20行代码将图片生成文字图片
原始图片是这样:
经过处理之后的效果是这样:
代码如下:
1 from PIL import Image 2 3 ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYX 4 zcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ") 5 6 def get_char(r,g,b,alpha = 256): 7 if alpha == 0: 8 return ' ' 9 length = len(ascii_char) 10 gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b) 11 12 unit = (256.0 + 1)/length 13 return ascii_char[int(gray/unit)] 14 15 if __name__ == '__main__': 16 17 im = Image.open('IMG_1649.JPG') 18 im = im.resize((64, 64)) 19 w, h = im.size 20 21 txt = "" 22 23 for i in range(h): 24 for j in range(w): 25 txt += get_char(*im.getpixel((j,i))) 26 txt += '\n' 27 28 print txt 29 with open("out.txt", 'w') as f: 30 f.write(txt)