-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
196 lines (156 loc) · 6.69 KB
/
main.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
from os import path
from math import ceil
import argparse
from dataclasses import dataclass
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
class FontTableCharacters:
start = ord(' ')
end = ord('~')
range = range(start, end + 1)
@dataclass
class Dimensions:
top: int
right: int
bottom: int
left: int
class ImageAnalyzer:
def __init__(self):
pass
# Returns char start from left to right, top to bottom
def analyzeImage(self, im):
dim = Dimensions(im.height, 0, 0, im.width)
for y in range(im.height):
for x in range(im.width):
if self.getBlackWhiteFromPixel( im.getpixel((x, y)) ) == 1:
dim.top = min(dim.top, y)
dim.bottom = max(dim.bottom, y)
dim.left = min(dim.left, x)
dim.right = max(dim.right, x)
return dim
def analyze(self, fontFile, width, height, marginVertical, marginHorizontal):
# Assuming width is always smaller than height
imageHeight = height * 2
imageWidth = width * 2 if width != -1 else imageHeight
prevDims = (0, Dimensions(imageHeight, 0, 0, imageWidth))
for fontSize in range(2, int(height * 8)):
maxDims = Dimensions(imageHeight, 0, 0, imageWidth)
for chars in FontTableCharacters.range:
im = Image.new(mode = 'L', size = (imageWidth, imageHeight), color = 255)
font = ImageFont.truetype(fontFile, size = fontSize)
imText = ImageDraw.Draw(im)
imText.text((0, 0), chr(chars), fill = 0, font = font, align = 'left')
dims = self.analyzeImage(im)
maxDims.top = min(maxDims.top, dims.top)
maxDims.right = max(maxDims.right, dims.right)
maxDims.bottom = max(maxDims.bottom, dims.bottom)
maxDims.left = min(maxDims.left, dims.left)
if (maxDims.bottom - maxDims.top) >= (height - 2 * marginVertical) or (width != -1 and (maxDims.right - maxDims.left) >= (width - 2 * marginHorizontal)):
return prevDims
prevDims = (fontSize, maxDims)
return (0, Dimensions(0, 0, 0, 0))
# Returns 1 if black, 0 for white
def getBlackWhiteFromPixel(self, px):
return 0 if px > 212 else 1
def getBinary(self, im):
lst = list()
for y in range(im.height):
comment = ''
numbers = list()
for x in range(ceil(im.width / 8)):
s = ''
for b in range(0, 8):
px = self.getBlackWhiteFromPixel( im.getpixel((x * 8 + b, y)) )
s += str(px)
comment += '#' if px == 1 else '.'
numbers.append(f'0x{int(s, 2):02x}')
lst.append((numbers, comment))
return lst
def generate(self, fontWidth, width, height, fontFile, fontSize, top):
lines = list()
font = ImageFont.truetype(fontFile, size = fontSize)
for chars in FontTableCharacters.range:
im = Image.new(mode = 'L', size = (width, height), color = 255)
imText = ImageDraw.Draw(im)
imText.text((0, 0), chr(chars), fill = 0, font = font, align = 'left')
dim = self.analyzeImage(im)
im = Image.new(mode = 'L', size = (width, height), color = 255)
imText = ImageDraw.Draw(im)
imText.text(((fontWidth - dim.right + dim.left) / 2 - dim.left, top), chr(chars), fill = 0, font = font, align = 'left')
lst = self.getBinary(im)
# im.save(f'./deneme/image-{chars}.jpg')
lines.append(f'// @{int((chars - FontTableCharacters.start) * height * width / 8)} \'{chr(chars)}\' ({dim.right - dim.left} pixels wide)')
for l in lst:
numbers = ', '.join(l[0])
lines.append(f'{numbers}, // {l[1]}')
lines.append('')
return lines
def main(output, fontFile, width, height, marginVertical, marginHorizontal):
analyzer = ImageAnalyzer()
print('[INFO] Starting analyze process to find the best font size possible')
(fontSize, dims) = analyzer.analyze(fontFile, width, height, marginVertical, marginHorizontal)
if fontSize == 0:
print('[ERROR] Cannot find the font size!')
return -1
print(f'[INFO] Found the best font size to apply: {fontSize}')
print(f'[INFO] Maximum font dimensions in the image is found as: {dims}')
fontWidth = dims.right - dims.left
bestWidth = ceil((fontWidth + 2 * marginHorizontal) / 8) * 8
print(f'[INFO] Best possible width for the font is: {fontWidth} (actual font size is {bestWidth})')
imageWidth = bestWidth if width == -1 else width
imageHeight = height
prelines = f"""/**
******************************************************************************
* @file font{height}.c
* @author Auto Generated by ePaper Font Generator
* @version V1.0.0
* @date 18-February-2014
******************************************************************************
*/
#include "fonts.h"
#if defined(__AVR__) || defined(ARDUINO_ARCH_SAMD)
#include <avr/pgmspace.h>
#elif defined(ESP8266) || defined(ESP32)
#include <pgmspace.h>
#endif
const uint8_t Font{height}_Table [] = {{
"""
postlines = f"""}};
sFONT Font{height} = {{
Font{height}_Table,
{fontWidth}, /* Width */
{imageHeight}, /* Height */
}};"""
lines = analyzer.generate(fontWidth, imageWidth, imageHeight, fontFile, fontSize, marginVertical - dims.top)
with open(output, 'w', encoding = 'utf-8') as f:
f.writelines(prelines)
f.writelines(f' {s}\n' for s in lines)
f.writelines(postlines)
return 0
if __name__ == '__main__':
parser = argparse.ArgumentParser(description = ('Flash STM32 and nRF52840 microcontrollers on BulkTainer board and inject cloud certificates and create the device on Coiote.'
'\nInput arguments are optional allowing to choose which parts of the script will be executed.'), formatter_class = argparse.RawDescriptionHelpFormatter)
parser.add_argument('--output', help = 'Output font file', default = './font.c')
parser.add_argument('--width', help = 'Width of the font (-1: auto)', type = int, default = -1)
parser.add_argument('--height', help = 'Height of the font', type = int, default = 64)
parser.add_argument('--margin-vertical', help = 'Vertical margin of the font', type = int, default = 1)
parser.add_argument('--margin-horizontal', help = 'Horizontal margin of the font', type = int, default = 2)
parser.add_argument('--font', help = 'Font file')
args = parser.parse_args()
if args.font == None:
parser.print_help()
exit(-1)
if not path.exists(args.font):
print('[ERROR] Font file not found!')
parser.print_help()
exit(-1)
if args.height < 2:
print('[ERROR] Height parameter cannot be less than 2!')
parser.print_help()
exit(-1)
if args.width != -1 and args.width < 2:
print('[ERROR] Height parameter cannot be less than 2!')
parser.print_help()
exit(-1)
exit(main(args.output, args.font, args.width, args.height, args.margin_vertical, args.margin_horizontal))