python小项目练习之转换像素图片为字符图

实例来源实验楼网站,没事可以多逛逛,在此多谢实验楼的无私分享

 from PIL import Image
import argparse """
description:
将图片像素转换为字母重新绘制输出
""" ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ") parser = argparse.ArgumentParser() parser.add_argument('file')
parser.add_argument('-o','--output')
parser.add_argument('--width',type=int,default=80)
parser.add_argument('--height',type=int,default= 80) args = parser.parse_args() IMG = args.file
WIDTH = args.width
HEIGHT = args.height
OUTPUT = args.output def get_char(r,g,b,alpha = 256):
if alpha == 0:
return ' '
length = len(ascii_char)
gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)
unit = (256.0 + 1)/length
return ascii_char[int(gray/unit)] def main():
im = Image.open(IMG)
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 if __name__=="__main__":
main()

在文件所在的当前目录存放待转换图片,直接执行命令: python convert.py test.png

上一篇:Unity3D和Egret3D的基情


下一篇:HDU 4857 逃生 (优先队列+反向拓扑)