Python在doc命令下运行实现图片转字符画
程序员文章站
2022-05-02 22:58:21
python在doc命令下运行实现图片转字符画
# -*- coding: utf-8 -*-
"""
created on wed jul 18 17:59:...
python在doc命令下运行实现图片转字符画
# -*- coding: utf-8 -*- """ created on wed jul 18 17:59:59 2018 @author: administrator """ 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) #python3 test_img.py --width 30 --height 30 timg.jpg or python3 test.py timg.jpg
下一篇: 【Python3爬虫】大众点评爬虫