python实战 基于PIL库简易实现图像转字符画

如果没有PIL库,则使用命令行安装
python2安装:pip install PIL
python3安装:pip install pillow

from PIL import Image
#字符集:用作字符画的颜色构成
ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft|()1{}[]?-_+~<>i!lI;:,.^`/ ")

# get_char函数:将256灰度映射到68个字符上,因为键盘字符集一共有68个
def get_char(r,g,b,alpha=256):
    if alpha==0:
        return ' ' #alpha为0表示该区域为空白
    length =len(ascii_char) #获取字符集长度
    gray =int (0.2126*r+0.7125*g+0.0722*b) # sRGB IEC61966-2.1 简化公式
    unit=(256.0+1)/length #灰度值范围为 0-255,而字符集只有 70,需要进行处理才能将灰度值映射到指定的字符上
    return ascii_char[int(gray/unit)] # 返回灰度值对应的字符

im=Image.open('C:/Users/zn/Desktop/2.jpg') #图像路径(一定要写对了)
im=im.resize((100,50),Image.NEAREST) #设置图像大小为 100 X 50,并设置为低质量图像
txt=" "  #定义字符画文本
for i in range(50):
    for j in range(100):
        txt+=get_char(*im.getpixel((j,i)))#遍历提取图片中每行的像素的 RGB 值,调用 getchar 转成对应的字符并进行字符画的拼接
    txt+='\n'
print(txt) #输出字符画                   

效果图如下:
哆啦A梦
小猪佩奇
尽量使用高对比度,线条清晰简洁的图像,能达到较好效果

猜你喜欢

转载自blog.csdn.net/m0_46141590/article/details/105858715