Python 将普通图片转字符画

from PIL import  Image
ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")

height=100
weight=100
def get_char(r,g,b,alpha=256):
    if alpha==0:
        return ' '
    length=len(ascii_char)
    gray=int(0.2126*r+0.7152*g+0.0722*b)
    unit=(256.0+1)/length

    return ascii_char[int(gray/unit)]

im_path=r'E:/wm.png'
im=Image.open(im_path)
im=im.resize((height,weight),Image.NEAREST)

txt=""
for i in range(height):
    for j in range(weight):
        txt+=get_char(*im.getpixel((j,i)))
    txt+='\n'

f=open('E:/test.txt','w')
f.write(txt)
f.close()

 

posted @ 2018-01-26 14:20  小九xD  阅读(326)  评论(0编辑  收藏  举报