-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrecognition.py
212 lines (168 loc) · 5.59 KB
/
recognition.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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
# recognition.py
import shlex
import pytesseract
import cv2 as cv
import numpy as np
import processing
from bisect import bisect_left, bisect_right
from PIL import Image, ImageDraw, ImageFont
from multiprocessing import Pool
from itertools import starmap
from util import *
# Fondid
fontNames = [
"LiberationSans-Regular.ttf",
"LiberationSans-Bold.ttf",
"LiberationSerif-Regular.ttf",
"LiberationMono-Regular.ttf"
]
# Minimaalne ja maksimaalne katsetatava märgi laiuse
# suhe sisendiks antud märgi laiusega
minWidthMul = 0.8
maxWidthMul = 1.2
# kasutatavad fondisuurused
fontSizes = range(10, 59, 2)
#######################################
# suurim kõrguse ja laiuse suhe üle fontide
# arvutatakse järgnevas tsüklis
hwRatio = 1
fonts = []
for fn in fontNames:
cf = []
for fs in fontSizes:
cf.append(ImageFont.truetype(fn, size=fs))
w, h = boxSize(getCharBox('|', cf[-1]))
hwRatio = max(hwRatio, h / w)
fonts.append(cf)
def border(img, w, h, val):
return cv.copyMakeBorder(img, h, h, w, w, cv.BORDER_CONSTANT, value=val)
def cropToBox(img, box):
return img[box[1]:box[3], box[0]:box[2]]
# https://stackoverflow.com/a/31643997
def tessChar(img, box, whitelist):
img = border(cropToBox(img, box), 3, 3, (255, 255, 255))
ch = pytesseract.image_to_string(
img,
config="-l est --psm 10 -c tessedit_char_whitelist=" + shlex.quote(whitelist)
).strip()[:1]
return ch
patternCharCache = {}
# Genereeri ühe märgi võrldlusmaatriksid
def genCharImages(ch):
if ch in patternCharCache:
return
mats = []
for fl in fonts:
currm = []
for font in fl:
chBox = getCharBox(ch, font)
chSize = (chBox[2] - chBox[0], chBox[3] - chBox[1])
size = chSize[0], font.getsize("Ayj")[1] + 4
chImg = Image.new("L", size, 255)
draw = ImageDraw.Draw(chImg)
chOffset = (0, chBox[1] + 2)
draw.text((0, 2), ch, fill=0, font=font)
chImg = np.array(chImg)
currm.append(chImg)
mats.append(currm)
patternCharCache[ch] = mats
# Ühe märgi võrdlusmaatriksid
def charImages(ch, w):
for cl in patternCharCache[ch]:
wl = ListMap(cl, lambda img: img.shape[1])
lo = bisect_left(wl, int(round(w * minWidthMul)))
hi = bisect_right(wl, int(round(w * maxWidthMul)))
for i in range(lo, hi):
yield cl[i]
# Ühe märgi kohta "kindlus", et tegemist on õige märgiga
def singleChar(img, ch, w):
best = -1
ih, iw = img.shape
for template in charImages(ch, w):
th, tw = template.shape
if th > ih or tw > iw:
break
match = cv.matchTemplate(img, template, cv.TM_CCOEFF_NORMED)
curr = np.amax(match)
best = max(best, curr)
return best
# Maatrikskõrvutamine
def patternChar(img, box, whitelist):
# Binariseeri pilt ja lisa ääred maatriksite tarbeks
w, h = boxSize(box)
nw = int(round(w * (maxWidthMul - 1) / 2)) + 3
nh = int(round((w * maxWidthMul * hwRatio - h) / 2)) + 3
img = 255 - border(cropToBox(processing.toBin(img), box), nw, nh, 0)
# veendu, et kõik vajalikud märgid on olemas
for ch in whitelist:
genCharImages(ch)
# maksimaalse "kindlusega" märgi leidmine
with Pool(4) as p:
best = max(zip(p.starmap(singleChar, ((img, ch, w) for ch in whitelist)), whitelist))
return best[1]
contourCharCache = {}
# Leia pildilt kontuurid
# väljundiks positiivsete ja negatiivsete kontuuride invariandid
def contoursPosNeg(img):
# Jaga positiivseteks ja negatiivseteks kontuurideks
# https://docs.opencv.org/3.4/d9/d8b/tutorial_py_contours_hierarchy.html
x = cv.findContours(img, cv.RETR_CCOMP, cv.CHAIN_APPROX_SIMPLE)
if x[1] is None:
return [], []
contours, (hierarchy,) = x
pos, neg = [], []
for c, h in zip(contours, hierarchy):
if h[3] == -1:
pos.append(c)
else:
neg.append(c)
return pos, neg
def genCharContours(ch):
if ch in contourCharCache:
return
# genereeri maatriksid sellest märgist
genCharImages(ch)
cl = []
# iga eri fondi suurim pilt
for il in patternCharCache[ch]:
img = border(255 - il[-1], 2, 2, 0)
contours = contoursPosNeg(img)
cl.append(contours)
contourCharCache[ch] = cl
# Ühe märgi kontuurid
def charContours(ch):
return contourCharCache[ch]
# kahe kontuuri erinevus
def contourDiff(a, b):
return cv.matchShapes(a, b, cv.CONTOURS_MATCH_I1, 0.0)
# Leia kontuuride erinevus tähemärgist
def matchCharContours(contours, ch):
# https://docs.opencv.org/master/d5/d45/tutorial_py_contours_more_functions.html
pos, neg = contours
best = inf
for tpos, tneg in charContours(ch):
dp = 0
for tc in tpos:
dp += min(contourDiff(tc, c) for c in pos)
dp /= len(tpos)
if (len(tneg) == 0) == (len(neg) == 0):
dn = 0
for tc in tneg:
dn += min(contourDiff(tc, c) for c in neg)
dn /= max(len(tneg), 1)
if len(tneg) != len(neg):
dn = inf
d = dp + dn
best = min(best, d)
return best
# Kontuuridepõhine
def contourChar(img, box, whitelist):
orig = img
img = border(cropToBox(processing.toBin(img), box), 3, 3, 0)
for ch in whitelist:
genCharContours(ch)
contours = contoursPosNeg(img)
if len(contours[0]) == 0:
return ' '
best = min((matchCharContours(contours, ch), ch) for ch in whitelist)
return best[1]