要达到的效果如下图所示
或者这样
源码如下:
from PIL import Image
ascii_char =list("/\|()1{}$@B%8&WM#ZO0QLCJUYX*hkbdpqwmoahkbdpqwmzcvunxrjft[]?-_+~<>i!lI;:,\"^`'. ")
imgname = "D:/jzm.png"
output ="D:/a.txt"
width =60
height=35
def get_char(r,g,b,alpha= 256):
length = len(ascii_char)
gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)
unitcount = (256.0+1)/length
return ascii_char[int(gray/unitcount)]
img = Image.open(imgname)
img = img.resize((width,height),Image.NEAREST)
txt = ""
for i in range(height):
for j in range(width):
txt += get_char(*img.getpixel((j,i)))
txt += '\n'
with open(output,'w') as f:
f.write(txt)
使用python的PIL库对图片进行处理,将每个像素映射到70个字符上,再一个个像素输出即可
代码注释:
def get_char(r,g,b,alpha= 256):
length = len(ascii_char)
gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)
unitcount = (256.0+1)/length
return ascii_char[int(gray/unitcount)]
版权声明:本文为博主原创文章,转载请附上博文链接!
将彩色图片的RBG数值转化为灰度值,并根据字符的个数计算出每个字符对应几个灰度值,因为灰度值为0~255但只有70个字符符号,大约每个字符对应三个灰度值
img = img.resize((width,height),Image.NEAREST)
对图片重新设置大小,第二个参数可以设置图片的质量,有四个选项.NEAREST,BILINEAR,BICUBIC,LANCZOS,默认为第一个,第四个图像质量最高
txt += get_char(*img.getpixel((j,i)))
img.getpixel(j,i)返回的是一个三元组元素,加*是为了将其分为三个变量值
———————
作者:NesCafee
原文:https://blog.csdn.net/dpengwang/article/details/79076188