由图像转为字符画的实现而引发的问题,先上小程序代码:
#DrawCharImage.Py
from PIL import Image
ascii_char = list('~OUTHANMW') #字符画里的字符集,图片颜色越深对应的字符越浅,用户可自己设定
#使用灰度值将彩色图像转换为黑白文稿,白色为255,黑色为0
def get_char(r, b, g, alpha = 256):
if alpha == 0:
return ''
gray = int(0.2126*r + 0.7152*g + 0.0722*b)
unit = 256/len(ascii_char)
return ascii_char[int(gray//unit)]
#为了使生成的字符画有最佳效果,可使用Image类的resize(size)函数对图片重新设定大小
def main():
im = Image.open('astro.jpg')
WIDTH, HEIGHT = 500,300
im = im.resize((WIDTH,HEIGHT))
txt = ''
for i in range(HEIGHT):
for j in range(WIDTH):
txt += get_char(*im.getpixel((j,i)))
txt += '\n'
fo = open('pic_char.txt','w'