from PIL import Image
import argparse

##Python 实现图片转字符画

##命令行参数获取
parser = argparse.ArgumentParser("命令行参数获取")
parser.add_argument("--imgpath",default="ascii_dora.png")
parser.add_argument("--charpath",default="ascii_dora.txt")
parser.add_argument("--height",type=int,default=150)
parser.add_argument("--width",type=int,default=300)
args=parser.parse_args()
HEIGHT=args.height
WIDTH=args.width
IMGPATH=args.imgpath
CHARPATH=args.charpath


##根据rgb转换成gray对应的字符
def getchar(r,g,b,alpha=256):
    if alpha==0:
        return ' '
    gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)
    ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")
    return ascii_char[int(len(ascii_char)*gray/257)]

##打开图片,并根据像素转变成字符串
txt=''
tt=''
im=Image.open(IMGPATH)
im_resize=im.resize((WIDTH,HEIGHT),Image.NEAREST)

for i in range(HEIGHT):
    for j in range(WIDTH):
        tt=getchar(*im_resize.getpixel((j,i)))
        txt+=tt
    txt+='\n'
print(txt)

if CHARPATH:
    with open(CHARPATH,'w') as f:
        f.write(txt)
else:
    with open("ascii_dora.txt",'w') as f:
        f.write(txt)

 

posted on 2022-01-18 17:43  TinyRick  阅读(185)  评论(0编辑  收藏  举报