1. 程式人生 > >python3----練習題(圖片轉字符畫)

python3----練習題(圖片轉字符畫)

text parse 習題 ret turn clas import 參數 har

 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----練習題(圖片轉字符畫)