Python的图片与字符画转换

总体思想为:将图片转换为灰度图片后,利用字符的“复杂程度”替换掉图片的内容,字符数组的“复杂程度”由大到小排列即可。

代码

(需要pip安装PIL库)

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
from PIL import Image 
import argparse

# 命令行输入参数处理
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

ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")


# 将256灰度映射到70个字符上
def get_char(r, b, g, 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__':

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 OUTPUT:
with open(OUTPUT,'w') as f:
f.write(txt)
else:
with open("output.txt", 'w') as f:
f.write(txt)

(稿)

Powered by Hexo and Hexo-theme-hiker

Copyright © 2017 - 2024 青域 All Rights Reserved.

UV : | PV :