python图片转字符画代码 :首先计算出图片颜色对应的灰度值;然后根据灰度值,从字符集中获取图片中每个像素点对应的字符,代码为【args = parser.parse_args()】。' z' F& ]/ k5 Y4 H
原理
/ B p* D1 W0 r* ~0 A1 N1、计算出图片颜色对应的灰度值,计算公式如下% L6 _7 O6 K7 U8 j) a4 Z( n
gray = 0.2126 * r 0.7152 * g 0.0722 * b. d+ K7 b4 b% m. d
2、根据灰度值,从字符集中获取图片中每个像素点对应的字符$ P) Z& o8 }# P2 |* P8 S
- # !/usr/bin/env python
-
- # -*- coding:utf-8 -*-
-
- from PIL import Image
-
- import argparse
- #命令行输入参数处理
-
- parser = argparse.ArgumentParser()
-
- parser.add_argument('file') #输入文件
-
- parser.add_argument('-o', '--output') #输出文件
-
- parser.add_argument('--width', type = int, default = 50) #输出字符画宽
-
- parser.add_argument('--height', type = int, default = 50) #输出字符画高
-
- #获取参数
-
- args = parser.parse_args()
-
- IMG = args.file
-
- WIDTH = args.width
-
- HEIGHT = args.height
-
- OUTPUT = args.output
-
- # 字符画使用的字符集
-
- ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_ ~<>i!lI;:,"^`'. ")
-
- def get_char(r,g,b,alpha = 256):
-
- """将256灰度映射到70个字符上"""
-
- if alpha == 0:
-
- return ' '
-
- length = len(ascii_char)
-
- # 计算灰度的公式
-
- gray = int(0.2126 * r 0.7152 * g 0.0722 * b)
-
- unit = (256.0 1)/length
-
- index=int(gray/unit)
-
- return ascii_char[index]
-
- 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)
-
- #字符画输出到文件
-
- if OUTPUT:
-
- with open(OUTPUT,'w') as f:
-
- f.write(txt)
-
- else:
-
- with open("output.txt",'w') as f:
-
- f.write(txt)z
运行结果
1 n3 K- j: h( n4 X/ V7 w
0 h: r: Y D. l0 l- j# j
|