python练习小项目(持续更新中...)
1 使用python将图片转换成字符画
效果图
文章图片
image.png
文章图片
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
推荐阅读
- python学习之|python学习之 实现QQ自动发送消息
- 【生信技能树】R语言练习题|【生信技能树】R语言练习题 - 中级
- 逻辑回归的理解与python示例
- python自定义封装带颜色的logging模块
- 【Leetcode/Python】001-Two|【Leetcode/Python】001-Two Sum
- Python基础|Python基础 - 练习1
- Python爬虫|Python爬虫 --- 1.4 正则表达式(re库)
- Python(pathlib模块)
- 呼吸练习心得
- python青少年编程比赛_第十一届蓝桥杯大赛青少年创意编程组比赛细则