烤雁子想要某陌做一个画字符画的功能,我简单分析了一下需求:其实我们不太可能一笔一画地把图片“画”出来!金主爸爸的要求用专业一点的思维理解其实是把给定的一张图片识别出来,然后用不同的字符“填充”进去。
然后某陌想到了Python,又在网上找了一些资料,最后整理了亲测可用的代码:
# -*- coding:utf-8 -*-
from PIL import Image
#IMG = r'd:\20221011.png'
IMG = r'd:\20221011.jpg'
WIDTH = 60
HEIGHT = 30
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__':
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)
# 写入文件
with open("output.txt", 'w') as f:
f.write(txt)
效果:
主要是下載 pil 的過程有點痛苦,其他還好~
pip install pillow -i https://mirrors.aliyun.com/pypi/simple
进入python.exe所在目录,输入
-m pip install --upgrade pip
参考资料:
Pycharm无法用pip安装PIL以及安装Pillow之后依然报错“No module named 'Pillow'”的诡异问题_Leonardo Liu的博客-CSDN博客
感觉还不错的一个转换软件:文字图画字符画转换器_文字转字符画-Web开发文档类资源-CSDN下载