码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-01-25 16:51:13      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:default   入参   near   ima   png   com   text   灰度   range   

 1 import argparse
 2 from PIL import Image
 3 
 4 def parse_param():
 5     parser = argparse.ArgumentParser()   # 命令行输入参数处理
 6 
 7     parser.add_argument("input_file")  # 输入文件
 8     parser.add_argument("out_file")    # 输出文件
 9 
10     parser.add_argument("--width", type=int, default=50)  # 输出字符画宽
11     parser.add_argument("--height", type=int, default=50)  # 输出字符画高
12 
13     args = parser.parse_args()   # 获取参数
14     width, height, input_file, out_file = args.width, args.height, args.input_file, args.out_file
15     return width, height, input_file, out_file
16 
17 def get_char(r, g, b, alpha=256):
18     ‘‘‘
19     gray / 256 = x / len(ascii_chra)
20 
21     ‘‘‘
22     if alpha == 0:
23         return " "
24     gray = (2126 * r + 7152 * g + 722 * b)/10000
25     # 将256灰度映射到70个字符上
26     ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`‘. ")
27     x = int((gray / (alpha + 1.0)) * len(ascii_char))
28     return ascii_char[x]
29 
30 def write_file(out_file_name, content):
31     with open(out_file_name, "w") as f:
32         f.write(content)
33 
34 def main(file_name="test.jpg", width=80, height=80, out_file_name="out_file"):
35     text = ""
36     im = Image.open(file_name)
37     im = im.resize((width, height), Image.NEAREST)
38     for i in range(height):
39         for j in range(width):
40             content = im.getpixel((j, i))
41         text += get_char(*content)
42         text += "\n"
43     print(text)
44     write_file(out_file_name, text)   # 字符画出到文件
45 
46 
47 if __name__ == __main__:
48     main()
49 
50 
51 
52 图片测试:
53 http://labfile.oss.aliyuncs.com/courses/370/ascii_dora.png

待完善.......

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

标签:default   入参   near   ima   png   com   text   灰度   range   

原文地址:https://www.cnblogs.com/jonm/p/8351754.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!