-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathCharRecognitionGUI.py
467 lines (394 loc) · 18.5 KB
/
CharRecognitionGUI.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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
#! /usr/bin/env python
#
# GUI module generated by PAGE version 4.5
# In conjunction with Tcl version 8.6
# Nov 21, 2015 03:29:17 PM
import sys
import os
import numpy
from tkFileDialog import askopenfilename
import matplotlib.pyplot as plt
import pickle
try:
from Tkinter import *
except ImportError:
from tkinter import *
try:
import ttk
py3 = 0
except ImportError:
import tkinter.ttk as ttk
py3 = 1
import CharRecognitionGUI_support
from FreemanEncoder import FreemanEncoder
from PIL import Image, ImageDraw, ImageWin, ImageTk
import KNN
import HMM
import NaiveBayes
import RandomForest
import svm
import LogisticReg
import adaboost
import gbrt
def vp_start_gui():
'''Starting point when module is the main routine.'''
global val, w, root
root = Tk()
root.title("Digit Recognizer")
geom = "848x493+374+90"
root.geometry(geom)
CharRecognitionGUI_support.set_Tk_var()
w = New_Toplevel_1 (root)
CharRecognitionGUI_support.init(root, w)
root.mainloop()
w = None
def create_New_Toplevel_1(root, param=None):
'''Starting point when module is imported by another program.'''
global w, w_win, rt
rt = root
w = Toplevel (root)
w.title('New_Toplevel_1')
geom = "848x493+374+90"
w.geometry(geom)
CharRecognitionGUI_support.set_Tk_var()
w_win = New_Toplevel_1 (w)
CharRecognitionGUI_support.init(w, w_win, param)
return w_win
def destroy_New_Toplevel_1():
global w
w.destroy()
w = None
class New_Toplevel_1:
def __init__(self, master=None):
_bgcolor = '#d9d9d9' # X11 color: 'gray85'
_fgcolor = '#000000' # X11 color: 'black'
_compcolor = '#d9d9d9' # X11 color: 'gray85'
_ana1color = '#d9d9d9' # X11 color: 'gray85'
_ana2color = '#d9d9d9' # X11 color: 'gray85'
self.style = ttk.Style()
if sys.platform == "win32":
self.style.theme_use('winnative')
self.style.configure('.',background=_bgcolor)
self.style.configure('.',foreground=_fgcolor)
self.style.configure('.',font="TkDefaultFont")
self.style.map('.',background=
[('selected', _compcolor), ('active',_ana2color)])
master.configure(background="#d9d9d9")
self.style.configure('TNotebook.Tab', background=_bgcolor)
self.style.configure('TNotebook.Tab', foreground=_fgcolor)
self.style.map('TNotebook.Tab', background=
[('selected', _compcolor), ('active',_ana2color)])
self.TNotebook1 = ttk.Notebook(master)
self.TNotebook1.place(relx=0.02, rely=0.02, relheight=0.95
, relwidth=0.96)
self.TNotebook1.configure(width=574)
self.TNotebook1.configure(takefocus="")
self.TNotebook1_predict = ttk.Frame(self.TNotebook1)
self.TNotebook1.add(self.TNotebook1_predict, padding=3)
self.TNotebook1.tab(0, text="Recognize",underline="-1",)
self.TNotebook1_train = ttk.Frame(self.TNotebook1)
self.TNotebook1.add(self.TNotebook1_train, padding=3)
self.TNotebook1.tab(1, text="Train",underline="-1",)
#user defined variables
self.thumbnails = self.load_thumbnails(CharRecognitionGUI_support.thumbnails_path)
self.PIL_image = Image.new("1", (300, 300), "white")
self.hidden_canvas = ImageDraw.Draw(self.PIL_image)
self.x = None
self.y = None
# Initialize and train all classifiers
self._init_classifiers()
self.Clear = ttk.Button(self.TNotebook1_predict)
self.Clear.place(relx=0.44, rely=0.14, height=24, width=78)
self.Clear.configure(text='''Clear Canvas''')
self.Clear.bind("<Button-1>",self.clear)
self.Canvas1 = Canvas(self.TNotebook1_predict)
self.Canvas1.place(relx=0.01, rely=0.02, relheight=0.61, relwidth=0.35)
self.Canvas1.configure(background="white")
self.Canvas1.configure(borderwidth="2")
self.Canvas1.configure(highlightbackground="#d9d9d9")
self.Canvas1.configure(highlightcolor="black")
self.Canvas1.configure(insertbackground="black")
self.Canvas1.configure(relief=RIDGE)
self.Canvas1.configure(selectbackground="#c4c4c4")
self.Canvas1.configure(selectforeground="black")
self.Canvas1.configure(width=378)
self.Canvas1.bind("<B1-Motion>",self.drag)
self.Canvas1.bind("<ButtonRelease-1>",self.drag_end)
self.Save = ttk.Button(self.TNotebook1_predict)
self.Save.place(relx=0.5, rely=0.04, height=24, width=77)
self.Save.configure(text='''Save''')
self.Save.bind("<Button-1>",self.save)
self.Select = ttk.Button(self.TNotebook1_predict)
self.Select.place(relx=0.44, rely=0.24, height=24, width=77)
self.Select.configure(text='''Select Image''')
self.Select.bind("<Button-1>",self.select)
# self.Frame1 = Frame(self.TNotebook1_predict)
# self.Frame1.place(relx=0.61, rely=0.02, relheight=0.6, relwidth=0.36)
# self.Frame1.configure(relief=GROOVE)
# self.Frame1.configure(borderwidth="2")
# self.Frame1.configure(relief=GROOVE)
# self.Frame1.configure(background=_bgcolor)
# self.Frame1.configure(highlightbackground="#d9d9d9")
# self.Frame1.configure(highlightcolor="black")
# self.Frame1.configure(width=305)
self.CanvasHist = Canvas(self.TNotebook1_predict)
self.CanvasHist.place(relx=0.61, rely=0.02, relheight=0.6, relwidth=0.36)
self.CanvasHist.configure(background="white")
self.CanvasHist.configure(borderwidth="2")
self.CanvasHist.configure(highlightbackground="#d9d9d9")
self.CanvasHist.configure(highlightcolor="black")
self.CanvasHist.configure(insertbackground="black")
self.CanvasHist.configure(relief=RIDGE)
self.CanvasHist.configure(selectbackground="#c4c4c4")
self.CanvasHist.configure(selectforeground="black")
self.CanvasHist.configure(width=378)
self.freeman_textbox = Text(self.TNotebook1_predict)
self.freeman_textbox.place(relx=0.01, rely=0.69, height=131, width=514)
self.freeman_textbox.configure(background=_bgcolor)
self.freeman_textbox.configure(foreground="#000000")
self.freeman_textbox.configure(highlightbackground="#d9d9d9")
self.freeman_textbox.configure(highlightcolor="black")
self.scrollbar = Scrollbar(self.freeman_textbox)
self.scrollbar.pack(side=RIGHT, fill=Y)
self.scrollbar.config(command=self.freeman_textbox.yview)
self.freeman_textbox.configure(yscrollcommand=self.scrollbar.set)
self.TCombobox1 = ttk.Combobox(self.TNotebook1_predict)
self.TCombobox1.place(relx=0.41, rely=0.35, relheight=0.06
, relwidth=0.16)
self.value_list = ['kNN (Freeman Code)','HMM (Freeman Code)','RandomForest (EFD)',
'NaiveBayes (RAW)', 'SVM (EFD)', 'LogisticReg (EFD)',
'AdaBoost (EFD)', 'GradientBoosting (EFD)']
self.TCombobox1.configure(values=self.value_list)
self.TCombobox1.configure(textvariable=CharRecognitionGUI_support.combobox)
self.TCombobox1.configure(takefocus="")
self.TCombobox2 = ttk.Combobox(self.TNotebook1_predict)
self.TCombobox2.place(relx=0.4, rely=0.04, height=24, width=77)
self.value_list = ['0','1','2','3','4','5','6','7','8','9',]
self.TCombobox2.configure(values=self.value_list)
self.TCombobox2.configure(textvariable=CharRecognitionGUI_support.combobox2)
self.TCombobox2.configure(takefocus="")
self.TCombobox2.current(0)
self.Frame2 = Frame(self.TNotebook1_predict)
self.Frame2.place(relx=0.737, rely=0.715, relheight=0.26, relwidth=0.15)
self.Frame2.configure(relief=GROOVE)
self.Frame2.configure(borderwidth="2")
self.Frame2.configure(relief=GROOVE)
self.Frame2.configure(background=_bgcolor)
self.Frame2.configure(highlightbackground="#d9d9d9")
self.Frame2.configure(highlightcolor="black")
self.Frame2.configure(width=150, height=150)
self.Thumbnail = Label(self.TNotebook1_predict)
self.Thumbnail.place(relx=0.75, rely=0.73, relheight=0.225, relwidth=0.125)
self.Thumbnail.configure(background=_bgcolor)
self.Thumbnail.configure(disabledforeground="#a3a3a3")
self.Thumbnail.configure(foreground="#000000")
self._img1 = PhotoImage(file='./thumbnails/blank.gif')
self.Thumbnail.configure(image=self._img1)
self.Thumbnail.configure(text='''Label''')
self.Thumbnail.configure(width=94)
self.Recognize = ttk.Button(self.TNotebook1_predict)
self.Recognize.place(relx=0.44, rely=0.45, height=24, width=87)
self.Recognize.configure(text='''Recognize''')
self.Recognize.bind("<Button-1>",self.recognize)
self.Clear_Results = ttk.Button(self.TNotebook1_predict)
self.Clear_Results.place(relx=0.44, rely=0.55, height=24, width=87)
self.Clear_Results.configure(text='''Clear Results''')
self.Clear_Results.bind("<Button-1>",self.clear_results)
def _init_classifiers(self):
# Initialize classifier objects
self.fenc = FreemanEncoder()
self.knn = KNN.KNN()
self.HMM = HMM.HMM()
self.NaiveBayes = NaiveBayes.NaiveBayes()
self.RandomForest = RandomForest.RandomForests()
self.SVM = svm.SVM_SVC()
self.LogisticReg = LogisticReg.LogisticReg()
self.AdaBoost = adaboost.AdaBoost()
self.GBRT = gbrt.GBRT()
#Train initially on the default data set, if no model saved already
# Initialize KNN, no saved model for KNN
self.knn.knn_train(CharRecognitionGUI_support.training_dataset, 1.0)
# Initialize HMM
self.HMM.training(CharRecognitionGUI_support.training_dataset)
# Initialize Naive Bayes
try:
pickle.load( open( "./Models/naivebayes_model.p", "rb" ) )
except IOError:
self.NaiveBayes.training(CharRecognitionGUI_support.training_dataset)
# Initialize Random Forest
try:
pickle.load( open( "./Models/random_forest.p", "rb" ) )
except IOError:
self.RandomForest.training(CharRecognitionGUI_support.training_dataset)
# Initialize SVM
try:
pickle.load( open( "./Models/svm.p", "rb" ) )
except IOError:
self.SVM.training(CharRecognitionGUI_support.training_dataset)
# Initialize Logistic Regression
try:
pickle.load( open( "./Models/logistic_model.p", "rb" ) )
except IOError:
self.LogisticReg.training(CharRecognitionGUI_support.training_dataset)
# Initialize AdaBoost
try:
pickle.load( open( "./Models/AdaBoostClassifier.p", "rb" ) )
except IOError:
self.AdaBoost.training(CharRecognitionGUI_support.training_dataset)
# Initialize GBRT
try:
pickle.load( open( "./Models/GradientBoostingClassifier.p", "rb" ) )
except IOError:
self.GBRT.training(CharRecognitionGUI_support.training_dataset)
def load_thumbnails(self, thumbnails_path):
images = {}
for thumb in os.listdir(thumbnails_path):
thumb_name = os.path.splitext(thumb)[0]
images[thumb_name] = thumbnails_path + '/' + thumb
return images
def quit(self, event):
'''
Event function to quit the drawer window
'''
sys.exit()
def select(self, event):
Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
self.clear("<Button-1>")
image_path = askopenfilename()
self.PIL_image = Image.open(image_path)
self.selected_image = ImageTk.PhotoImage(self.PIL_image)
self.Canvas1.create_image(150, 150, image=self.selected_image)
def clear(self, event):
'''
Event function to clear the drawing canvas (draw white fill)
'''
self.Canvas1.delete("all")
self.PIL_image = Image.new("1", (300, 300), "white")
self.hidden_canvas = ImageDraw.Draw(self.PIL_image)
def drag(self, event):
'''
Event function to start drawing on canvas when left mouse drag happens
'''
newx,newy=event.x,event.y
if self.x is None:
self.x,self.y=newx,newy
return
self.Canvas1.create_line((self.x,self.y,newx,newy), width=5, smooth=True)
self.hidden_canvas.line((self.x,self.y,newx,newy), width=12)
self.x,self.y=newx,newy
def drag_end(self, event):
'''
Event function to stop drawing on canvas when mouse drag stops
'''
self.x,self.y=None,None
def save(self, event):
'''
Event function to save the current canvas image in JPG format
'''
image_cnt = 1
if not os.path.exists(CharRecognitionGUI_support.save_dir):
os.makedirs(CharRecognitionGUI_support.save_dir)
file_name = CharRecognitionGUI_support.save_dir + self.TCombobox2.get() + '_' + str(image_cnt) + ".jpg"
while os.path.isfile(file_name):
image_cnt += 1
file_name = CharRecognitionGUI_support.save_dir + self.TCombobox2.get() + '_' + str(image_cnt) + ".jpg"
self.PIL_image.save(file_name)
self.freeman_textbox.delete("1.0", END)
self.freeman_textbox.insert(END, 'SAVED!')
self.freeman_textbox.see(END)
def clear_results(self, event):
self.freeman_textbox.delete("1.0", END)
self._img1 = PhotoImage(file='./thumbnails/blank.gif')
self.Thumbnail.configure(image=self._img1)
self.CanvasHist.delete("all")
def recognize(self, event):
image = ~numpy.array(self.PIL_image.convert('L'))
try:
code = self.fenc.encode_freeman(image)
# Plotting the histogram
figure = plt.figure()
hist = list(map(int, list(code)))
plt_hist = plt.hist(hist)
plt.savefig('hist.png')
self.hist_im = ImageTk.PhotoImage(Image.open('hist.png').resize((280,280), Image.LANCZOS))
os.remove('hist.png')
self.CanvasHist.create_image(290, 265, image=self.hist_im, anchor=SE)
except ValueError:
self.freeman_textbox.delete("1.0", END)
self.freeman_textbox.insert(END, 'Please redraw the image')
self.freeman_textbox.see(END)
self.freeman_textbox.delete("1.0", END)
self.freeman_textbox.insert(END, str(code))
self.freeman_textbox.see(END)
if self.TCombobox1.get() == '':
pass
elif self.TCombobox1.get().split(" ")[0] == 'kNN':
pred = self.knn.knn_predict_one(code, 1)
pred_thumb = self.thumbnails[pred[0]]
self._image = PhotoImage(file=pred_thumb)
self.Thumbnail.configure(image=self._image)
elif self.TCombobox1.get().split(" ")[0] == 'HMM':
pred = self.HMM.predict(code)
pred_thumb = self.thumbnails[pred[0]]
self._image = PhotoImage(file=pred_thumb)
self.Thumbnail.configure(image=self._image)
elif self.TCombobox1.get().split(" ")[0] == 'NaiveBayes':
image = numpy.array(self.PIL_image.convert('L').resize((100,100), Image.LANCZOS))
image[image < 128] = 1
image[image >= 128] = 0
image[image == 1] = 255
pred = self.NaiveBayes.predict(image)
pred_thumb = self.thumbnails[pred[0]]
self._image = PhotoImage(file=pred_thumb)
self.Thumbnail.configure(image=self._image)
elif self.TCombobox1.get().split(" ")[0] == 'RandomForest':
image = numpy.array(self.PIL_image.convert('L').resize((100,100), Image.LANCZOS))
image[image < 128] = 1
image[image >= 128] = 0
image[image == 1] = 255
pred = self.RandomForest.predict(image)
pred_thumb = self.thumbnails[pred[0]]
self._image = PhotoImage(file=pred_thumb)
self.Thumbnail.configure(image=self._image)
elif self.TCombobox1.get().split(" ")[0] == 'SVM':
image = numpy.array(self.PIL_image.convert('L').resize((100,100), Image.LANCZOS))
image[image < 128] = 1
image[image >= 128] = 0
image[image == 1] = 255
pred = self.SVM.predict(image)
pred_thumb = self.thumbnails[pred[0]]
self._image = PhotoImage(file=pred_thumb)
self.Thumbnail.configure(image=self._image)
elif self.TCombobox1.get().split(" ")[0] == 'LogisticReg':
image = numpy.array(self.PIL_image.convert('L').resize((100,100), Image.LANCZOS))
image[image < 128] = 1
image[image >= 128] = 0
image[image == 1] = 255
pred = self.LogisticReg.predict(image)
pred_thumb = self.thumbnails[pred[0]]
self._image = PhotoImage(file=pred_thumb)
self.Thumbnail.configure(image=self._image)
elif self.TCombobox1.get().split(" ")[0] == 'AdaBoost':
image = numpy.array(self.PIL_image.convert('L').resize((100,100), Image.LANCZOS))
image[image < 128] = 1
image[image >= 128] = 0
image[image == 1] = 255
pred = self.AdaBoost.predict(image)
pred_thumb = self.thumbnails[pred[0]]
self._image = PhotoImage(file=pred_thumb)
self.Thumbnail.configure(image=self._image)
elif self.TCombobox1.get().split(" ")[0] == 'GradientBoosting':
image = numpy.array(self.PIL_image.convert('L').resize((100,100), Image.LANCZOS))
image[image < 128] = 1
image[image >= 128] = 0
image[image == 1] = 255
pred = self.GBRT.predict(image)
pred_thumb = self.thumbnails[pred[0]]
self._image = PhotoImage(file=pred_thumb)
self.Thumbnail.configure(image=self._image)
else:
self.freeman_textbox.delete("1.0", END)
self.freeman_textbox.insert(END, 'Not Implemented yet')
self.freeman_textbox.see(END)
if __name__ == '__main__':
vp_start_gui()