python3----练习题(图片转字符画)

时间:2023-03-09 17:55:42
python3----练习题(图片转字符画)
 import argparse
from PIL import Image def parse_param():
parser = argparse.ArgumentParser() # 命令行输入参数处理 parser.add_argument("input_file") # 输入文件
parser.add_argument("out_file") # 输出文件 parser.add_argument("--width", type=int, default=50) # 输出字符画宽
parser.add_argument("--height", type=int, default=50) # 输出字符画高 args = parser.parse_args() # 获取参数
width, height, input_file, out_file = args.width, args.height, args.input_file, args.out_file
return width, height, input_file, out_file def get_char(r, g, b, alpha=256):
'''
gray / 256 = x / len(ascii_chra) '''
if alpha == 0:
return " "
gray = (2126 * r + 7152 * g + 722 * b)/10000
# 将256灰度映射到70个字符上
ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")
x = int((gray / (alpha + 1.0)) * len(ascii_char))
return ascii_char[x] def write_file(out_file_name, content):
with open(out_file_name, "w") as f:
f.write(content) def main(file_name="test.jpg", width=80, height=80, out_file_name="out_file"):
text = ""
im = Image.open(file_name)
im = im.resize((width, height), Image.NEAREST)
for i in range(height):
for j in range(width):
content = im.getpixel((j, i))
text += get_char(*content)
text += "\n"
print(text)
write_file(out_file_name, text) # 字符画出到文件 if __name__ == '__main__':
main() 图片测试:
http://labfile.oss.aliyuncs.com/courses/370/ascii_dora.png

待完善.......