话不多说直接上代码
需要执行pip install pillow
安装图片处理模块
from PIL import Image
IMG = "51_616.jpg"
ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")
#图片转字符
#将256灰度映射到70个字符上
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)]
if __name__ == "__main__":
im = Image.open(IMG)
#此处为原比例输出可以进行替换
im = im.resize(im.size,Image.NEAREST)
txt = ''
for i in range(im.size[1]):
for j in range(im.size[0]):
txt += get_char(*im.getpixel((j,i)))
txt +='\n'
with open("output.txt",'w') as f:
f.write(txt)