Python练习007

题目:实现图片转字符串,并通过命令行输入参数
图片:
Python练习007

代码:

from PIL import Image
import argparse
import string

# 创建句柄
parser = argparse.ArgumentParser()

# 添加参数
parser.add_argument('--input','-i')
parser.add_argument('--output', '-o', type = str, default = 'result.txt')
parser.add_argument('--width', '-w', type = int, default = 80)
parser.add_argument('--height', type = int, default = 80)

args = parser.parse_args()

IMG = args.input
WIDTH = args.width
HEIGHT = args.height
FILE = args.output

letters = string.ascii_letters + string.ascii_uppercase + r"!@#$%^&*(){}[]\:;''<>?/~`"

def get_char(r, g, b, alpha = 256):
    if alpha == 0:
        return ' '
    length = len(letters)
    gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)
    return letters[int(gray / 256.0 * length)]

if __name__ == '__main__':
    img = Image.open(IMG)
    img = img.resize((WIDTH, HEIGHT), Image.NEAREST)
    char_img = ""
    for i in range(HEIGHT):
        for j in range(WIDTH):
            char_img += get_char(*img.getpixel((j,i)))
        char_img += '\n'
    print(char_img)
    
    if FILE:
        with open(FILE, 'w') as f:
            f.write(char_img)
    
上一篇:JavaSE基础——面向对象3:接口与内部类---007


下一篇:“007是常态,996才是福利”的每日优鲜,这是花样作死!