The image of a character drawn with
The second blog, a daily record of learning bit by bit.
Knowledge summary
- Python PIL third-party image processing libraries
- Gray value equation
gray = 0.2126 * r + 0.7152 * g + 0.0722 * b
sign small symbol mapping with local gray value at the beginning of the list, with a large gray value of the local end of the list of maps. - getpixel ((j, i)) to give the color of a pixel, typically return (r, g, b)
from PIL import Image
ascii_char = list ('"$%_&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-/+@<>i!;:,\^`.')
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)]
def main():
im = Image.open('boy.jpg')
WIDTH , HEIGHT = 90,34
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")
fo.write(txt)
fo.close()
if __name__ == '__main__':
main()