Python图转字符画

本文参考:
https://blog.csdn.net/qq_20464153/article/details/79777823

将一副图以灰度值转化成黑白字符画
代码如下:

# -*- coding:utf-8 -*-
from PIL import Image

IMG = r'F:\PythonFiles\PycharmFile\ex10CharacterGraph.jpg'  #文件路径

WIDTH = 80  #定义输出画面的宽度
HEIGHT = 45  #定义
ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")  #所用字符列表

# 将256灰度映射到70个字符上
def get_char(r, g, b, alpha=256):  # alpha透明度
    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)]  # 不同的灰度对应着不同的字符

# 通过灰度来区分色块
if __name__ == '__main__':  #__name__ == '__main__'表示以下程序只要在本文件运行时才执行;若该文件被其他文件import引用,以下程序则不执行
    im = Image.open(IMG)
    im = im.resize((WIDTH, HEIGHT), Image.NEAREST)
    txt = ""
    for i in range(HEIGHT):
        for j in range(WIDTH):
            txt += get_char(*im.getpixel((j, i)))
        txt += '\n'
    print(txt)  #输出图像

    # 将图像写入txt文件
    with open("ex10CharacterGraph_Graph.txt", 'w') as f:
        f.write(txt)  

效果图:
在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/coberup/article/details/82888340