#coding=utf-8from PIL import Imageimport 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.fileWIDTH = args.widthHEIGHT = args.heightOUTPUT = args.output ascii_char = list("[email protected]%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`‘. ") # 将256灰度映射到70个字符上def get_char(r,g,b,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 #字符画输出到文件 #如果存在该txt文件,那么就直接生成字符画 ,否则就会创建一个文件并且生成 if OUTPUT: with open(OUTPUT,‘w‘) as f: f.write(txt) else: with open("output.txt",‘w‘) as f: f.write(txt) 将该文件保存为 1.py 终端执行命令 Python 1.py b.png(此处是目标图片)
时间: 2024-11-07 07:11:31