python练习小项目(持续更新中...)

1 使用python将图片转换成字符画
效果图

python练习小项目(持续更新中...)
文章图片
image.png python练习小项目(持续更新中...)
文章图片
QQ20180217-180057@2x.png 【python练习小项目(持续更新中...)】安装必要的库
pillow(PIL)库是python 图片处理库
$ sudo apt-get update
$ sudo apt-get install python-dev
$ sudo apt-get install libtiff5-dev libjpeg8-dev zlib1g-dev libfreetype6-dev liblcms2-dev libwebp-dev tcl8.6-dev tk8.6-dev python-tk
$ sudo pip install pillow
新建 testAsciiPy.py文件

# -*- coding: utf-8 -*- # @Time: 2018/2/17 下午3:41 # @Author: scl # @Email: 1163820757@qq.com # @File: testAsciiPy.py # @Software: PyCharmfrom PIL import Image import argparseascii_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.outputdef 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)]if __name__ == '__main__':img = Image.open(IMG) img = img.resize((WIDTH,HEIGHT),Image.NEAREST)txt = ''for i in range(HEIGHT): for j in range(WIDTH): txt += get_char(*img.getpixel((j,i)))txt += '\n'print(txt)if OUTPUT: with open(OUTPUT,'w') as f: f.write(txt) else: with open('output.txt','w') as f: f.write(txt)

参考资料:https://www.shiyanlou.com/courses/370/labs/1191/document

    推荐阅读