20行代碼將圖片生成文字圖片

 

原始圖片是這樣:spa

 

通過處理以後的效果是這樣:code


代碼以下:blog

 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)

相關文章
相關標籤/搜索