-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathtrain.py
More file actions
68 lines (50 loc) · 1.82 KB
/
train.py
File metadata and controls
68 lines (50 loc) · 1.82 KB
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
from PIL import Image, ImageDraw, ImageFont
import os
import subprocess
import string
import sys
white = (255, 255, 255)
# Creates png image files for each character in the font
def textToImage(fontName, fontSize):
font = ImageFont.truetype("fonts/" + fontName + ".ttf", fontSize)
letters = string.ascii_uppercase
for letter in letters:
image = Image.new("RGB", (200, 120), white)
draw = ImageDraw.Draw(image)
draw.text((0, 0), letter, fill='black', font=font)
filename = "characters/" + fontName + "-" + str(fontSize) + "-" + letter + ".png"
image.save(filename)
# Count the amount of pixels in each section of the character image
def generatePixelMatrix(fontName, fontSize):
f = open(fontName + ".ocr", "w")
letters = string.ascii_uppercase
for letter in letters:
image = Image.open("characters/" + fontName + "-" + str(fontSize) + "-" + letter + ".png")
rgbImage = image.convert("RGB")
width, height = image.size
# For each pixel: 0 is white, 1 is black
matrix = []
# Loop
for y in range(0, height):
for x in range(0, width):
if rgbImage.getpixel((x, y)) == white:
matrix.append("0")
else:
matrix.append("1")
matrixToWrite = ""
for i in range(0, len(matrix)):
matrixToWrite = matrixToWrite + "," + matrix[i]
f.write(letter + "," + str(width) + "," + str(height) + str(matrixToWrite) + "\n")
f.close()
# -------------------------------
if len(sys.argv) == 2:
fontName = sys.argv[1]
else:
print("Usage: python train.py font-name")
print("Example: python train.py Helvetica")
sys.exit()
fontSize = 42
os.system("rm characters/*.png > /dev/null 2>&1")
textToImage(fontName, fontSize)
os.system("mogrify -trim characters/" + fontName + "-" + str(fontSize) + "-" + "*.png")
generatePixelMatrix(fontName, fontSize)