Python将图片转换为字符画的方法
最近在学习Python,看到网上用Python将图片转换成字符画便来学习一下
题目意思是,程序读入一个图片,以txt格式输出图片对应的字符画,如图所示:
以下是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=80) # 输出字符画宽 parser.add_argument('--height', type=int, default=80) # 输出字符画高 # 获取参数 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;:,\"^`'. ") # 将256灰度映射到70个字符上 def get_char(r, b, g, 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((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)
在输出文件中得到如下字符集:
相关推荐
YENCSDN 2020-11-17
lsjweiyi 2020-11-17
houmenghu 2020-11-17
Erick 2020-11-17
HeyShHeyou 2020-11-17
以梦为马不负韶华 2020-10-20
lhtzbj 2020-11-17
夜斗不是神 2020-11-17
pythonjw 2020-11-17
dingwun 2020-11-16
lhxxhl 2020-11-16
坚持是一种品质 2020-11-16
染血白衣 2020-11-16
huavhuahua 2020-11-20
meylovezn 2020-11-20
逍遥友 2020-11-20
weiiron 2020-11-16