Python 生成字符画

479 阅读1分钟

跑在 python3 下,可以通过输入图片来生成字符画。大致原理在注释中有提到。具体的像素和符号转化关系,我没有去深入了解。

#! /Users/michael/anaconda3/bin/python3

from PIL import Image
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('file') # input file
parser.add_argument('-o', '--output') # output file (optional)
parser.add_argument('--width', type=int, default=80) # 字符画宽度
parser.add_argument('--height', type=int, default=80) # 字符画高度

args = parser.parse_args() # 获取参数
image = args.file
output = args.output
width = args.width
height = args.height

chs = "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. "
ascii_char = list(chs)

# 根据图片的每个像素来转成对应的字符。
# 可以看出,越往后字符的笔画越稀疏,也就是颜色越浅。
def get_char(r, g, b, alpha=256): 
    if alpha == 0:
        return ' '
    length = len(ascii_char)
    grey = int(0.2126*r + 0.7152*g + 0.0722*b)
    unit = (257)/length
    return ascii_char[int(grey/unit)]


im = Image.open(image)
im = im.resize((width, height), Image.NEAREST)

txt = ''
for i in range(height):
    for j in range(width):
        txt += get_char(*im.getpixel((j, i)))
    txt += '\n'

print(txt)

with open('fun.txt', 'w', encoding='utf-8') as f:
    f.write(txt)

运行命令:

python3 draw.py --width 60 --height 30 test.png

这是原图:

以下是效果图:

                     ,:                               
                       )???$                             
                      n????$             ???         
                       ????$            ????$       
              $         ??$              .????$       
           h%        ?$                      .??$        
          $        ?$8                         $<          
        J$        ??                                      
       -$+       ??                                       
       ?       @??       ??                            
      ]?       ??$     ???$       ??$               
      ?$       ??$     ???       ???$      $       
      ?$&      ???    ??$         ???     ?       
      B?$      ???$                  ??`    1?       
       ??.    ????$                        ??       
       ???  }??????$  .???         ???       
       ???? ???????    m    ^??????$       
       ????????????$!??????????       
       W??????????????????????        
        ?????????????$o  t??????@        
        +?????W???????$    ??????         
         ;????$ -???????    ?????$          
           ????#  ??????$    ?????c          
              p?$W    ??????   C????$%           
                        ??????  %????             
                          ?????W  t?p                 
                             ???$