-
Notifications
You must be signed in to change notification settings - Fork 0
/
char.py
67 lines (48 loc) · 1.64 KB
/
char.py
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
59
60
61
62
63
64
65
66
67
from PIL import Image, ImageDraw, ImageFont
import argparse
# 命令行参数处理
parser = argparse.ArgumentParser()
parser.add_argument('file')
parser.add_argument('-o', '--output')
# 获取参数
args = parser.parse_args()
IMG = args.file
OUTPUT = args.output
FONT_SIZE = 40
SCALE_FACTOR = 0.1
ascii_char = list(
"$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")
def rgb_to_gray(r, g, b):
'将rgb值转化为灰度值'
return int(0.2126 * r + 0.7152 * g + 0.0722 * b)
def get_char(r, g, b, alpha=256):
'将256个灰度映射到字符列表上'
if alpha == 0:
return ' '
length = len(ascii_char)
gray = rgb_to_gray(r, g, b)
unit = 256.0 / length
return ascii_char[int(gray / unit)]
if __name__ == '__main__':
'主函数'
im = Image.open(IMG)
WIDTH, HEIGHT = im.size
WIDTH_A, HEIGHT_A = int(WIDTH * SCALE_FACTOR), int(HEIGHT * SCALE_FACTOR)
im = im.resize((WIDTH_A, HEIGHT_A), Image.ANTIALIAS)
# 创建图片对象
img = Image.new('RGB', (int(WIDTH * FONT_SIZE * SCALE_FACTOR),
int(HEIGHT * FONT_SIZE * SCALE_FACTOR)),
(255, 255, 255))
# 创建font对象
font = ImageFont.truetype('Arial.ttf', FONT_SIZE)
# 创建Draw对象
draw = ImageDraw.Draw(img)
for i in range(HEIGHT_A):
for j in range(WIDTH_A):
c = get_char(*im.getpixel((j, i)))
pixel = im.getpixel((j, i))
draw.text((j * FONT_SIZE, i * FONT_SIZE),
c, font=font, fill=pixel)
if not OUTPUT:
OUTPUT = IMG[0:IMG.find('.')] + "_char.png"
img.save(OUTPUT)