Python——>图像的字符画绘制

图像的字符画绘制

要点:这是一个采用PIL库将图片转化为字符画的实例

from PIL import Image

ascii_char = "$@asdsadqwdacadasdasdasdxzc"


def get_char(r, b, g, alpha=256):
    if alpha == 0:
        return ' '
    gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)
    unit = 256 / len(ascii_char)
    i =int(gray // unit)
    return ascii_char[i]


def main():
    im = Image.open("D:\\LOL.jpg")
    WIDTH, HEIGHT = 100, 60
    im = im.resize((WIDTH, HEIGHT))
    txt = ""
    for i in range(HEIGHT):
        for j in range(WIDTH):
            txt += get_char(*im.getpixel((j, i)))
        txt += '\n'
    fo = open("D:\\pic_char.txt", "w")
    fo.write(txt)
    fo.close()


main()

你可能感兴趣的:(Python,笔记)