云亦然
天下皆白,唯我独黑。非攻墨门,兼爱平生。

Python的终端影集

2018-12-25 16:54:10 python
Word count: 490 | Reading time: 2min

先上效果图吧:

怎么实现呢?

通过python的PIL库,将彩色转黑白(256种灰度),创建字符集,建立字符集与灰度的映射
没有PIL库的话 需要 pip install Pillow

最好把照片裁成1:1的比例,保证显示比例正常,通过定时刷新,模拟一个动感影集

上面的图 我懒得截图了 就成那样了

[Python的终端影集][]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58

from PIL import Image
import os
import time

codeLib = '''@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,"^`'. '''#生成字符画所需的字符集
count = len(codeLib)

def transform_image(image_file):
#转换为黑白图片,参数"L"表示黑白模式
image_file = image_file.convert("L")
codePic = ''
#size属性表示图片的分辨率,'0'为横向大小,'1'为纵向
for h in range(0,image_file.size[1]):
for w in range(0,image_file.size[0]):
#返回指定位置的像素,如果所打开的图像是多层次的图片,那这个方法就返回一个元组
gray = image_file.getpixel((w,h))
#建立灰度与字符集的映射
codePic = codePic + codeLib[int(((count-1)*gray)/256)]
codePic = codePic+'\r\n'
return codePic

def main():

# 获取终端的高度
height = os.get_terminal_size().lines

# 获取同级目录文件夹下所有图片的列表
the_names = os.listdir("./images")

# 开启循环
while 1 :
# 遍历每张图片
for the_name in the_names:
try:

# 清屏幕
print("\n"*height)
# 拼合当前图片名
my_img = open("./images/"+the_name,'rb')
# 打开当前图片
image_file = Image.open(my_img)
#调整图片尺寸到原来的四分之一
# image_file=image_file.resize((int(image_file.size[0]*0.5), int(image_file.size[1]*0.5)))
image_file=image_file.resize((250, 250))

#打印图片
print(transform_image(image_file))
# 每张图片停顿10秒
time.sleep(10)
except Exception as e:
pass

if __name__ == "__main__":
main()





        

Author: 云亦然

Link: http://JaneBraun.github.io/2018/12/25/Python的终端影集/

Copyright: All articles in this blog are licensed under CC BY-NC-SA 3.0 unless stating additionally.

< PreviousPost
网络安全之搜索引擎收集信息
NextPost >
Python猜拳游戏
CATALOG