zoukankan      html  css  js  c++  java
  • python3----练习题(图片转字符画)

     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 += "
    "
    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

    待完善.......

  • 相关阅读:
    Asp.net中导出Excel文档(Gridview)
    以太坊难度炸弹是什么?极大抑制矿工继续以POW方式挖矿!
    Solidity语言基础 和 Etherum ERC20合约基础
    BCH/BSV coin split troubleshooting
    比特币学习-Transaction的locktime属性
    在BCH硬分叉后防止重放攻击-2
    在BCH硬分叉后防止重放攻击-1
    区块链硬分叉-软分叉简单了解
    BTC和BCH 区别和联系?
    BCHABC/BCHSV的矛盾所在
  • 原文地址:https://www.cnblogs.com/jonm/p/8351754.html
Copyright © 2011-2022 走看看