-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrender.py
61 lines (40 loc) · 1.81 KB
/
render.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
import random
from pathlib import Path
import click
from PIL import Image, ImageDraw, ImageFont
IMAGE_SIZE = 299
def render_text(text: str, filename: Path, font: ImageFont):
img = Image.new('RGB', (IMAGE_SIZE, IMAGE_SIZE), (0, 0, 0))
d = ImageDraw.Draw(img)
d.text((2, 2), text, font=font, fill=(255, 255, 255), spacing=1)
img.save(filename, 'PNG')
def render_test(output_dir):
output_dir = Path(output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
font = ImageFont.truetype('RobotoMono-Regular.ttf', 8)
text = '\n'.join([f"line number {i} ..." for i in range(50)])
render_text(text, output_dir / 'test.png', font)
@click.command()
@click.argument('filename', type=click.Path(exists=True))
@click.argument('count', type=click.INT)
@click.argument('output_dir', type=click.Path(file_okay=False, dir_okay=True))
def main(filename, count, output_dir):
output_dir = Path(output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
print(filename, count, output_dir)
font = ImageFont.truetype('RobotoMono-Regular.ttf', 8)
# 256x256: 17 lines per image with 10-sized font and default spacing. 27 lines per 8-size font and spacing=1
# 299x299: 32 lines per 8-size font and spacing=1
lines_per_image = 32
with open(filename, 'r') as f:
input_lines = f.readlines()
print(f"Rendering {count} images from {len(input_lines)} lines ", end='', flush=True)
offsets = sorted([random.randint(0, len(input_lines) - lines_per_image) for _ in range(count)])
for i in range(count):
first_line_no = offsets[i]
text = '\n'.join(input_lines[first_line_no : first_line_no + lines_per_image])
render_text(text, output_dir / f'{i:03d}.png', font)
print('.', end='', flush=True)
print(' DONE')
if __name__ == '__main__':
main()