-
Notifications
You must be signed in to change notification settings - Fork 1
/
run_hw2.py
2282 lines (2016 loc) · 95.4 KB
/
run_hw2.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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Example job for running a neural network."""
import os
import sys
from io import open
import sklearn.metrics as mt
PATH_CUR = os.path.dirname(os.path.realpath(__file__))
sys.path.append(PATH_CUR)
sys.path.append('../../')
os.environ['KERAS_BACKEND'] = 'tensorflow'
import pickle
import random
import argparse
import numpy as np
import cv2
import matplotlib as mpl
# mpl.use('Agg')
from matplotlib import pyplot as plt
from ocrolib.hwocr import label2code
import json
from scipy import misc
import keras
from keras.models import model_from_json
from keras import optimizers
#from flax.hwocr import img_prep
from sklearn.model_selection import train_test_split
import pandas
def gen_dict():
label2codes = pickle.load(open('./data/label2codes.pkl', 'rb'))
label2chars={}
chars2label={}
for l, code in label2codes.items():
label2chars[l]=label2code.jis2unicode(code)
chars2label[label2chars[l]]=l
json.dump(label2chars,open('./data/label2chars.json','w'))
json.dump(chars2label, open('./data/chars2label.json','w'))
def load_image2(dir, img_rows =64, img_cols = 64):
im_names = []
border = 10
arr_img = np.empty([0,img_rows, img_cols,1])
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
for file in sorted(os.listdir(dir)):
filename = dir + file
if os.path.isfile(filename) and '.blank' not in file and 'OUTPUT' in file:
im_names.append(filename)
img = misc.imread(filename)
hei, wid, channel = img.shape
if wid > hei:
top, bottom = [int(abs(wid - hei) / 2)] * 2
left, right = 0, 0
if wid < hei:
top, bottom = 0, 0
left, right = [int(abs(wid - hei) / 2)] * 2
# if(wid <30 and hei< 30):
top, bottom, left, right = [top + border, bottom + border, left + border, right + border]
print(top, bottom, left, right)
color = [255]
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
img_border = cv2.copyMakeBorder(gray, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color)
img_border = cv2.resize(img_border, (img_rows, img_cols), interpolation=cv2.INTER_CUBIC)
ret, thresh1 = cv2.threshold(img_border, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
size = thresh1.shape
img_resize = cv2.resize(img_border, size)
ret, thresh = cv2.threshold(img_resize, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
kernel = np.ones((2, 2), np.uint8)
img_dilation = cv2.erode(thresh, kernel, iterations=1)
# rotate = misc.imrotate(img_dilation, -15)
# img_resize = misc.imresize(invert, size, mode='F')
# img_resize = cv2.resize(rotate, size)
out = cv2.normalize(img_dilation.astype('float'), None, 0.0, 1.0, cv2.NORM_MINMAX)
reshape = out.reshape([-1, img_rows, img_cols, 1])
arr_img = np.row_stack((arr_img, reshape))
arr_img = np.transpose(arr_img, (0, 3, 1, 2))
print('test shape: ', arr_img.shape)
return arr_img, im_names
def load_image(dir, img_rows =64, img_cols = 64):
im_names = []
arr_img = np.empty([0,img_rows, img_cols,1])
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
for file in sorted(os.listdir(dir)):
filename = dir + file
if os.path.isfile(filename) and '.blank' not in file and 'OUTPUT' in file:
im_names.append(filename)
# print(filename)
img = cv2.imread(filename, cv2.CV_8UC1)
# img = cv2.copyMakeBorder(img, top=5, bottom=5, left=5, right=5,
# borderType=cv2.BORDER_CONSTANT, value=[255, 255, 255])
# print(img)
# img = clahe.apply(img)
out = cv2.resize(img,(img_rows,img_cols),interpolation=cv2.INTER_CUBIC)
# out=cv2.adaptiveThreshold(out, 1.0, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 115, 1)
# # out = cv2.normalize(img_resize, None, 0, 255, cv2.NORM_MINMAX)
# out = cv2.blur(out, (3,3))
out = cv2.adaptiveThreshold(out, 1.0, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 115, 1)
# out = cv2.medianBlur(out,5)
# print('shape ', img_resize.shape, ' content', out)
reshape = out.reshape([-1,img_rows, img_cols,1])
arr_img = np.row_stack((arr_img, reshape))
arr_img = np.transpose(arr_img, (0, 3, 1, 2))
print('test shape: ', arr_img.shape)
return arr_img, im_names
def load_single_img_old_model(filename, img_rows = 32, img_cols = 32):
arr_img = np.empty([0, img_rows, img_cols, 1])
img = cv2.imread(filename, cv2.IMREAD_GRAYSCALE)
_, img = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
if img is None: return None
img_resize = cv2.resize(img, (img_cols, img_rows))
out = cv2.normalize(img_resize.astype('float'), None, 0.0, 1.0, cv2.NORM_MINMAX)
reshape = out.reshape([-1, img_rows, img_cols, 1])
arr_img = np.row_stack((arr_img, reshape))
return arr_img
import ocrolib.hwocr.mnist_helper as mh
def load_single_img_nice(filename, img_rows =64, img_cols = 64, nobj=3):
if isinstance(filename, str):
img = cv2.imread(filename, cv2.CV_8UC1)
else:
img=cv2.normalize(filename, None, 0, 255, cv2.NORM_MINMAX, dtype=cv2.CV_8U)
oldimg=img
img = mh.do_cropping(img,max_cobj=nobj)
# img = mh.do_cropping(img)
# img = cv2.resize(img, (img_rows, img_cols), interpolation=cv2.INTER_CUBIC)
# img = mh.deskew(img, (img_rows, img_cols))
img = mh.resize_img(img, (img_rows, img_cols))
_,img = cv2.threshold(img, 127, 1, cv2.THRESH_BINARY)
# reshape = img.reshape([-1, img_rows, img_cols, 1])
return oldimg, img.reshape([1, img_rows, img_cols])
def load_single_img(filename, img_rows =64, img_cols = 64):
# print(filename)
img = cv2.imread(filename, cv2.CV_8UC1)
# img = img_prep.deskew(img)
# img = cv2.copyMakeBorder(img, top=5, bottom=5, left=5, right=5,
# borderType=cv2.BORDER_CONSTANT, value=[255, 255, 255])
# print(img)
# img = clahe.apply(img)
img2 = cv2.resize(img, (img_rows, img_cols), interpolation=cv2.INTER_CUBIC)
# out = cv2.medianBlur(img2, 5)
out = cv2.GaussianBlur(img2, (3, 3), 0)
#out = img2
out = cv2.adaptiveThreshold(out, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 115, 1)
# out = cv2.Canny(img2, 100, 200)
# kernel = np.ones((3, 3), np.uint8)
# out = 255-cv2.erode(255-out, kernel, iterations=1)
# out[out>0]=1
out = cv2.normalize(out, None, 0, 1.0, cv2.NORM_MINMAX, dtype=cv2.CV_32F)
# plt.imshow(out)
# plt.show()
# out = cv2.blur(out, (3,3))
# out = cv2.adaptiveThreshold(out, 255 , cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 115, 1)
# im2, contours, hierarchy = cv2.findContours(out, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
#
# if len(contours) != 0:
# # draw in blue the contours that were founded
# cv2.drawContours(img2, contours, -1, 255, 3)
#
# # find the biggest area
# c = max(contours, key=cv2.contourArea)
#
# x, y, w, h = cv2.boundingRect(c)
# # draw the book contour (in green)
# cv2.rectangle(img2, (x, y), (x + w, y + h), (0, 255, 0), 2)
#
# plt.imshow(out)
# plt.show()
# out = cv2.medianBlur(out,5)
# print('shape ', img_resize.shape, ' content', out)
reshape = out.reshape([-1, img_rows, img_cols, 1])
return reshape, out.reshape([1, img_rows, img_cols])
def load_single_img_with_size_info(filename, img_rows =64, img_cols = 64):
# print(filename)
img = cv2.imread(filename, cv2.CV_8UC1)
shape = img.shape
# img = img_prep.deskew(img)
# img = cv2.copyMakeBorder(img, top=5, bottom=5, left=5, right=5,
# borderType=cv2.BORDER_CONSTANT, value=[255, 255, 255])
# print(img)
# img = clahe.apply(img)
img2 = cv2.resize(img, (img_rows, img_cols), interpolation=cv2.INTER_CUBIC)
# out = cv2.medianBlur(img2, 5)
out = cv2.GaussianBlur(img2, (3, 3), 0)
out = cv2.adaptiveThreshold(out, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 115, 1)
# out = cv2.Canny(img2, 100, 200)
# kernel = np.ones((3, 3), np.uint8)
# out = 255-cv2.erode(255-out, kernel, iterations=1)
out = cv2.normalize(out, None, 0, 1.0, cv2.NORM_MINMAX, dtype=cv2.CV_32F)
# plt.imshow(out)
# plt.show()
# out = cv2.blur(out, (3,3))
# out = cv2.adaptiveThreshold(out, 255 , cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 115, 1)
# im2, contours, hierarchy = cv2.findContours(out, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
#
# if len(contours) != 0:
# # draw in blue the contours that were founded
# cv2.drawContours(img2, contours, -1, 255, 3)
#
# # find the biggest area
# c = max(contours, key=cv2.contourArea)
#
# x, y, w, h = cv2.boundingRect(c)
# # draw the book contour (in green)
# cv2.rectangle(img2, (x, y), (x + w, y + h), (0, 255, 0), 2)
#
# plt.imshow(out)
# plt.show()
# out = cv2.medianBlur(out,5)
# print('shape ', img_resize.shape, ' content', out)
reshape = out.reshape([-1, img_rows, img_cols, 1])
return reshape, out.reshape([1, img_rows, img_cols]), shape
def load_image_general(dir, img_rows =64, img_cols = 64):
im_names = []
arr_img = np.empty([0,img_rows, img_cols,1])
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
print(dir)
for file in sorted(os.listdir(dir)):
filename = dir + '/'+file
if os.path.isfile(filename) and \
('.jpg' in filename or '.png' in filename or '.JPG' in filename or '.PNG' in filename):
print(filename)
im_names.append(filename)
reshape, out = load_single_img(filename, img_rows, img_cols)
arr_img = np.row_stack((arr_img, reshape))
arr_img = np.transpose(arr_img, (0, 3, 1, 2))
print('test shape: ', arr_img.shape)
return arr_img, im_names
def get_extra_data(root_dir='./test_images/form1-20/', dataout='./data/extra_real.pkl',split=0.8):
all_labels=[]
all_samples=[]
print(root_dir)
mychar2label={}
mylabel2char={}
ind=0
for root, dirs, files in os.walk(root_dir):
for name in files:
if '.jpg' in name or '.png' in name or '.JPG' in name or '.PNG' in name:
filename = os.path.join(root, name)
print(filename)
_, img_arrs = load_single_img(filename)
l = name[-5]
all_samples+=[img_arrs]
if l not in mychar2label:
mychar2label[l]=ind
mylabel2char[ind]=l
ind+=1
all_labels.append(mychar2label[l])
labels = np.asarray(all_labels)
labels = keras.utils.to_categorical(labels, len(mychar2label))
imgs = np.asarray(all_samples)
print(imgs[:3])
pickle.dump((imgs[:int(imgs.shape[0]*split)], labels[:int(imgs.shape[0]*split)],
imgs[int(imgs.shape[0]*split):], labels[int(imgs.shape[0]*split):]),
open(dataout, 'wb'))
json.dump(mylabel2char, open(dataout[:-4]+'.label2chars.json', 'w'))
json.dump(mychar2label, open(dataout[:-4]+'.chars2label.json', 'w'))
print(imgs.shape)
print(labels.shape)
print(len(mychar2label))
print(len(mylabel2char))
def load_data_npz(data_dir='./data/fullkata96char.npz', label_dir='./data/katakana.csv', img_rows=64, img_cols=64):
katamap = open(label_dir, encoding='utf-8')
label2char={}
char2label={}
ind=0
for l in katamap:
c=l.split()[0]
label2char[c]=ind
char2label[ind]=c
ind+=1
print(label2char)
print(len(char2label))
height, width = 32, 32
ary = np.load(data_dir)['a']
labels = np.load(data_dir)['b']
print(ary.shape)
ary = ary.reshape([-1, height, width]).astype(np.float32)
X=[]
y=[]
for i in range(ary.shape[0]):
im = cv2.normalize(ary[i], None, 0, 255, cv2.NORM_MINMAX, dtype=cv2.CV_8UC1)
im = cv2.resize(im, (img_rows, img_cols), interpolation=cv2.INTER_CUBIC)
# out = cv2.GaussianBlur(im, (3, 3), 0)
out = cv2.adaptiveThreshold(im, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 115, 1)
kernel = np.ones((3, 3), np.uint8)
out = 255-cv2.erode(out, kernel, iterations=1)
out = cv2.normalize(out, None, 0, 1.0, cv2.NORM_MINMAX, dtype=cv2.CV_32F)
X.append(out.reshape(1,img_rows,img_cols))
y.append(labels[i])
# print(labels[i])
# plt.imshow(out, cmap='gray')
# plt.show()
X_train, X_test, Y_train, Y_test = train_test_split(np.asarray(X), np.asarray(y), test_size=0.2)
Y_train = keras.utils.to_categorical(Y_train, len(label2char))
Y_test = keras.utils.to_categorical(Y_test, len(label2char))
json.dump(char2label, open('./data/full_katakana.char2label.json', 'w'))
json.dump(label2char, open('./data/full_katakana.label2char.json', 'w'))
print(X_train.shape)
print(X_test.shape)
print(Y_train.shape)
print(Y_test.shape)
pickle.dump((X_train, Y_train, X_test, Y_test), open('./data/full_katakana.pkl', 'wb'))
def get_mnist(out_row=64, out_col=64):
from keras.datasets import mnist
from keras import backend as K
# input image dimensions
img_rows, img_cols = 28, 28
# the data, shuffled and split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()
if K.image_data_format() == 'channels_first':
x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
input_shape = (1, img_rows, img_cols)
else:
x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
input_shape = (img_rows, img_cols, 1)
x_train2=np.zeros((x_train.shape[0], 1, out_row, out_col))
x_test2=np.zeros((x_test.shape[0], 1, out_row, out_col))
element = cv2.getStructuringElement(cv2.MORPH_CROSS, (5, 5))
for i in range(x_train.shape[0]):
img_resize = cv2.resize(x_train[i], (out_row, out_col), interpolation=cv2.INTER_CUBIC)
# out = cv2.adaptiveThreshold(img_resize, 1.0, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 9, 5)
_, out = cv2.threshold(img_resize, 10, 255, cv2.THRESH_BINARY)
out = cv2.erode(out, element)
# out = cv2.medianBlur(out, 3)
out=cv2.normalize(out, None, 0, 1.0, cv2.NORM_MINMAX)
out=1-out
x_train2[i][0]=out
print(out.shape)
# plt.imshow(out)
# plt.show()
for i in range(x_test.shape[0]):
img_resize = cv2.resize(x_test[i], (out_row, out_col), interpolation=cv2.INTER_CUBIC)
# out = cv2.adaptiveThreshold(img_resize, 1.0, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 9, 5)
_, out = cv2.threshold(img_resize, 10, 255, cv2.THRESH_BINARY)
out = cv2.erode(out, element)
# out = cv2.medianBlur(out, 3)
out = cv2.normalize(out, None, 0, 1.0, cv2.NORM_MINMAX)
out = 1 - out
x_test2[i][0]=out
char2label={}
label2char={}
for i in range(0,10):
char2label[chr(i+48)]=i
label2char[str(i)]=chr(i+48)
json.dump(char2label, open('./data/full_mnist.char2label.json', 'w'))
json.dump(label2char, open('./data/full_mnist.label2char.json', 'w'))
y_train = keras.utils.to_categorical(y_train, 10)
y_test = keras.utils.to_categorical(y_test, 10)
print(x_train2.shape)
print(x_test2.shape)
print(y_train.shape)
print(y_test.shape)
pickle.dump((x_train2, y_train, x_test2, y_test), open('./data/full_mnist.pkl', 'wb'))
def load_model_weights(name, model):
try:
model.load_weights(name)
except Exception as e:
print ("Can't load weights!")
print(str(e))
def save_model_weights(name, model):
try:
model.save_weights(name)
except Exception as e:
print ("failed to save classifier weights")
print(str(e))
def show_training_images():
X_train, y_train, X_test, y_test, label2code = pickle.load(open('./data/all.pkl', 'rb'))
label2imgs = pickle.load(open('./gallery/lib_img.pkl','rb'))
while 1:
index = random.choice(range(X_train.shape[0]))
data = X_train[index]
id = np.argmax(y_train[index])
print('shape {} id {} '.format(data.shape, id))
fig = plt.figure()
a = fig.add_subplot(1, 2, 1)
a.set_title('Sample')
plt.imshow(data[0])
a = fig.add_subplot(1, 2, 2)
a.set_title('Gallery')
plt.imshow(label2imgs[id])
plt.show()
def make_gallery(fpath='./data/full.pkl'):
X_train, y_train, X_test, y_test = pickle.load(open(fpath, 'rb'))
label2imgs={}
for i in range(X_train.shape[0]):
if len(y_train.shape)==1:
id = y_train[i]
else:
id = np.argmax(y_train[i])
if not id in label2imgs:
label2imgs[id]= X_train[i][0]*255
# print(np.max(X_train[i][0]))
# print(np.min(X_train[i][0]))
cv2.imwrite('./gallery/'+str(id)+'.png', label2imgs[id])
for i in range(X_test.shape[0]):
if len(y_test.shape)==1:
id = y_test[i]
else:
id = np.argmax(y_test[i])
if not id in label2imgs:
label2imgs[id]= X_test[i][0]*255
cv2.imwrite('./gallery/'+str(id)+'.png', label2imgs[id])
pickle.dump(label2imgs,open('./gallery/lib_img.pkl','wb'))
print('done save gallery!')
def make_gallery10(fpath='./data/full.pkl'):
X_train, y_train, X_test, y_test = pickle.load(open(fpath, 'rb'))
print(len(X_train))
label2imgs={}
for i in range(X_train.shape[0]-1, -1, -1):
if len(y_train.shape)==1:
id = y_train[i]
else:
id = np.argmax(y_train[i])
if not id in label2imgs:
label2imgs[id]= [X_train[i][0]*255]
# print(np.max(X_train[i][0]))
# print(np.min(X_train[i][0]))
else:
if len(label2imgs[id])<10:
label2imgs[id].append(X_train[i][0]*255)
for i in range(X_train.shape[0]):
if len(y_train.shape) == 1:
id = y_train[i]
else:
id = np.argmax(y_train[i])
if not id in label2imgs:
label2imgs[id] = [X_train[i][0] * 255]
# print(np.max(X_train[i][0]))
# print(np.min(X_train[i][0]))
else:
if len(label2imgs[id]) < 10:
label2imgs[id].append(X_train[i][0] * 255)
# for i in range(X_test.shape[0]-1, -1, -1):
# if len(y_test.shape)==1:
# id = y_test[i]
# else:
# id = np.argmax(y_test[i])
# if not id in label2imgs:
# label2imgs[id]= [X_test[i][0]*255]
# else:
# if len(label2imgs[id]) < 5:
# label2imgs[id].append(X_test[i][0] * 255)
pickle.dump(label2imgs,open(fpath[:-4]+'.gallery.pkl','wb'))
print('done save gallery!')
def get_data():
from .preprocessing.make_keras_input import data
X_train, y_train, X_test, y_test, label2codes = data(mode='all')
# print(label2codes)
pickle.dump((X_train, y_train, X_test, y_test, label2codes), open('./data/all.pkl','wb'))
def predict_single_sep_number(dir_img, model,label2chars, nmodel, nlabel2chars, type=1):
_, img = load_single_img(dir_img)
if type ==0:
print('predict mix')
probab_predict = model.predict_proba(np.asarray([img]), batch_size=1)
top_index = np.argsort(probab_predict * -1)[0][0]
return label2chars[str(top_index)], probab_predict[0][top_index]
if type==2:
probab_predict = model.predict_proba(np.asarray([img]), batch_size=1)
top_index = np.argsort(probab_predict * -1)[0]
for ind in top_index:
ch = label2chars[str(ind)]
if not ch.isdigit() and not ch == '-':
print('predict char')
return ch, probab_predict[0][ind]
if type==1:
probab_predict = model.predict_proba(np.asarray([img]), batch_size=1)
top_index = np.argsort(probab_predict * -1)[0]
t_r = ''
fid=0
for ind in top_index:
ch = label2chars[str(ind)]
if ch.isdigit() or ch == '-' or ch =='(' or ch == ')':
t_r = ch
fid=ind
break
if t_r=='-' or t_r =='(' or t_r == ')':
return t_r, probab_predict[0][fid]
probab_predict = nmodel.predict_proba(np.asarray([img]), batch_size=1)
print('predict number')
top_index = np.argsort(probab_predict * -1)[0][0]
return nlabel2chars[str(top_index)], probab_predict[0][top_index]
def predict_single_sep_number_kata(dir_img,
model,label2chars,
nmodel, nlabel2chars,
kmodel, klabel2chars,
type=0):
_, img, size = load_single_img_with_size_info(dir_img)
if type ==0:
print('predict mix')
probab_predict = model.predict_proba(np.asarray([img]), batch_size=1)
top_index = np.argsort(probab_predict * -1)[0][0]
return label2chars[str(top_index)], probab_predict[0][top_index]
if type==2:
print('predict text')
probab_predict = model.predict_proba(np.asarray([img]), batch_size=1)
top_index = np.argsort(probab_predict * -1)[0]
for ind in top_index:
ch = label2chars[str(ind)]
if not ch.isdigit() and not ch == '-' and ch not in klabel2chars.values():
return ch, probab_predict[0][ind]
if type==1:
probab_predict = model.predict_proba(np.asarray([img]), batch_size=1)
top_index = np.argsort(probab_predict * -1)[0]
t_r = ''
fid = 0
for ind in top_index:
ch = label2chars[str(ind)]
if ch.isdigit() or ch == '-' or ch =='(' or ch == ')':
t_r = ch
fid = ind
break
if t_r=='-' or t_r =='(' or t_r == ')':
return t_r, probab_predict[0][fid]
probab_predict = nmodel.predict_proba(np.asarray([img]), batch_size=1)
print('predict number')
top_index = np.argsort(probab_predict * -1)[0][0]
return nlabel2chars[str(top_index)], probab_predict[0][top_index]
if type==3:
# check if image is diacritic
if max(size) < 50:
probab_predict = model.predict_proba(np.asarray([img]), batch_size=1)
top_index = np.argsort(probab_predict * -1)[0][:2]
t_r = ''
fid = 0
for ind in top_index:
ch = label2chars[str(ind)]
print(ch)
if ch in ['\'', '0', 'o']:
t_r = ch
fid = ind
break
if t_r == '\'':
return u'\u3099', probab_predict[0][fid]
elif t_r in ['0', 'o']:
return u'\u309A', probab_predict[0][fid]
print('predict kata')
probab_predict = kmodel.predict_proba(np.asarray([img]), batch_size=1)
top_index = np.argsort(probab_predict * -1)[0][0]
return klabel2chars[str(top_index)], probab_predict[0][top_index]
def predict_single_sep_number_kata_kanji(dir_img,
model,label2chars,
nmodel, nlabel2chars,
kmodel, klabel2chars,
khmodel, khlabel2chars,
type=0):
if type != 4:
_, img, size = load_single_img_with_size_info(dir_img)
else:
_, img = load_single_img(dir_img)
#img = load_single_img_old_model(dir_img)
if type ==0:
print('predict mix')
probab_predict = model.predict_proba(np.asarray([img]), batch_size=1)
top_index = np.argsort(probab_predict * -1)[0][0]
return label2chars[str(top_index)], probab_predict[0][top_index]
if type==2:
print('predict text')
probab_predict = model.predict_proba(np.asarray([img]), batch_size=1)
top_index = np.argsort(probab_predict * -1)[0]
for ind in top_index:
ch = label2chars[str(ind)]
if not ch.isdigit() and not ch == '-' and ch not in klabel2chars.values():
return ch, probab_predict[0][ind]
if type==1:
probab_predict = model.predict_proba(np.asarray([img]), batch_size=1)
top_index = np.argsort(probab_predict * -1)[0]
t_r = ''
fid = 0
for ind in top_index:
ch = label2chars[str(ind)]
if ch.isdigit() or ch == '-' or ch =='(' or ch == ')':
t_r = ch
fid = ind
break
if t_r=='-' or t_r =='(' or t_r == ')':
return t_r, probab_predict[0][fid]
probab_predict = nmodel.predict_proba(np.asarray([img]), batch_size=1)
print('predict number')
top_index = np.argsort(probab_predict * -1)[0][0]
return nlabel2chars[str(top_index)], probab_predict[0][top_index]
if type==3:
# check if image is diacritic
if max(size) < 50:
probab_predict = model.predict_proba(np.asarray([img]), batch_size=1)
top_index = np.argsort(probab_predict * -1)[0][:2]
t_r = ''
fid = 0
for ind in top_index:
ch = label2chars[str(ind)]
print(ch)
if ch in ['\'', '0', 'o']:
t_r = ch
fid = ind
break
if t_r == '\'':
return u'\u3099', probab_predict[0][fid]
elif t_r in ['0', 'o']:
return u'\u309A', probab_predict[0][fid]
print('predict kata')
probab_predict = kmodel.predict_proba(np.asarray([img]), batch_size=1)
top_index = np.argsort(probab_predict * -1)[0][0]
return klabel2chars[str(top_index)], probab_predict[0][top_index]
# predict kanji
if type==4:
probab_predict = khmodel.predict_proba(np.asarray([img]), batch_size=1)
print('predict kanji')
top_index = np.argsort(probab_predict * -1)[0][0]
return khlabel2chars[str(top_index)], probab_predict[0][top_index]
#return label2code.label2unicode_etl9(top_index), probab_predict[0][top_index]
def predict_single_sep_number_kata_kanji_old(dir_img,
model,label2chars,
nmodel, nlabel2chars,
kmodel, klabel2chars,
khmodel, khlabel2chars,
type=0):
if type != 4:
_, img, size = load_single_img_with_size_info(dir_img)
else:
img = load_single_img_old_model(dir_img)
if type ==0:
print('predict mix...')
probab_predict = model.predict_proba(np.asarray([img]), batch_size=1)
top_index = np.argsort(probab_predict * -1)[0][0]
return top_index, label2chars[str(top_index)], probab_predict[0][top_index]
if type==2:
print('predict text...')
probab_predict = model.predict_proba(np.asarray([img]), batch_size=1)
top_index = np.argsort(probab_predict * -1)[0]
for ind in top_index:
ch = label2chars[str(ind)]
if not ch.isdigit() and not ch == '-' and ch not in klabel2chars.values():
return ind, ch, probab_predict[0][ind]
if type==1:
probab_predict = model.predict_proba(np.asarray([img]), batch_size=1)
top_index = np.argsort(probab_predict * -1)[0]
t_r = ''
fid = 0
for ind in top_index:
ch = label2chars[str(ind)]
if ch.isdigit() or ch == '-' or ch =='(' or ch == ')':
t_r = ch
fid = ind
break
if t_r=='-' or t_r =='(' or t_r == ')':
return fid, t_r, probab_predict[0][fid]
probab_predict = nmodel.predict_proba(np.asarray([img]), batch_size=1)
print('predict number...')
top_index = np.argsort(probab_predict * -1)[0][0]
return top_index, nlabel2chars[str(top_index)], probab_predict[0][top_index]
if type==3:
# check if image is diacritic
if max(size) < 50:
probab_predict = model.predict_proba(np.asarray([img]), batch_size=1)
top_index = np.argsort(probab_predict * -1)[0][:2]
t_r = ''
fid = 0
for ind in top_index:
ch = label2chars[str(ind)]
#print(ch)
if ch in ['\'', '0', 'o']:
t_r = ch
fid = ind
break
if t_r == '\'':
return fid, u'\u3099', probab_predict[0][fid]
elif t_r in ['0', 'o']:
return fid, u'\u309A', probab_predict[0][fid]
print('predict kata...')
probab_predict = kmodel.predict_proba(np.asarray([img]), batch_size=1)
top_index = np.argsort(probab_predict * -1)[0][0]
return top_index, klabel2chars[str(top_index)], probab_predict[0][top_index]
# predict kanji
if type==4:
probab_predict = khmodel.predict_proba(img, batch_size=1)
print('predict kanji')
top_index = np.argsort(probab_predict * -1)[0][0]
return label2code.label2unicode_etl9(top_index), probab_predict[0][top_index]
def predict_single(dir_img,model, label2chars, type=0):
_, img = load_single_img(dir_img)
print(img.shape)
# plt.imshow(img[0])
# plt.show()
if type==0:
result_predict = model.predict_classes(np.asarray([img]), batch_size=1)
else:
probab_predict = model.predict_proba(np.asarray([img]), batch_size=1)
top_index = np.argsort(probab_predict * -1)[0]
for ind in top_index:
ch = label2chars[str(ind)]
if ch.isdigit() or ch=='-':
if type==1:#digit
print('predict digit')
return ch
else:
if type==2:#char
print('predict char')
return ch
return label2chars[str(result_predict[0])]
def predict_single_topk(dir_img,model, topk=3):
_, img = load_single_img(dir_img)
print(img.shape)
probab_predict = model.predict_proba(np.asarray([img]), batch_size=1)
top_index = np.argsort(probab_predict * -1)[0][:topk]
return top_index, img
def predict(dir_img, topk=3):
from keras.models import model_from_json
label2imgs = pickle.load(open('./data/full.gallery.pkl', 'rb'))
label2chars = json.load(open('./data/full.label2char.json'))
# print(label2codes)
json_file = open("./save/model7_1.json", 'r')
loaded_model_json = json_file.read()
model = model_from_json(loaded_model_json)
load_model_weights('./save/M7_1-all_weights.h5', model)
model.compile(loss='categorical_crossentropy', optimizer=optimizers.Adam(lr=1e-4), metrics=['accuracy'])
new_images, im_names = load_image_general(dir_img)
f = open('./test.txt','w',encoding='utf-8')
f.write('...\n')
for i in range(new_images.shape[0]):
bimg=np.asarray(np.asarray([new_images[i]]))
print(im_names[i])
probab_predict = model.predict_proba(bimg, batch_size=1)
top_index = np.argsort(probab_predict * -1)[0][:topk]
result_predict = top_index[0]
# print('probability ', probab_predict)
# result_predict = model.predict_classes(bimg, batch_size=1)
jc=label2chars[str(result_predict)]
f.write(str(jc))
f.write('\n')
print('predict {} -->{} with prob {}'.format(result_predict, jc.encode('utf-8'),
probab_predict[0][result_predict]))
fig = plt.figure()
raw = cv2.imread(im_names[i])
a = fig.add_subplot(topk + 1, 5, 1)
a.set_title('Real input')
plt.imshow(raw)
a = fig.add_subplot(topk + 1, 5, 2)
a.set_title('Processed input')
plt.imshow(new_images[i][0])
curindj=6
for jj in range(5):
a = fig.add_subplot(topk + 1, 5,curindj)
a.set_title('Top 1')
plt.imshow(label2imgs[result_predict][jj])
curindj+=1
print('probability ', probab_predict)
for ii, index in enumerate(list(top_index[1:])):
jc =label2chars[str(index)]
print('predict {} -->{} '.format(index, jc.encode('utf-8')))
for jj in range(5):
a = fig.add_subplot(topk + 1, 5, curindj)
a.set_title('Top {}'.format(ii+2))
plt.imshow(label2imgs[index][jj])
curindj+=1
fig.tight_layout()
plt.show()
f.close()
def report(dir_input, dir_report, topk=3):
if not os.path.isdir(dir_report):
os.mkdir(dir_report)
from keras.models import model_from_json
label2chars = json.load(open('./data/label2chars.json'))
label2imgs = pickle.load(open('./gallery/lib_img.pkl', 'rb'))
json_file = open("./save/model7_1.json", 'r')
loaded_model_json = json_file.read()
model = model_from_json(loaded_model_json)
load_model_weights('./save/M7_1-hiragana_weights.h5', model)
all_acc=0
all_sam=0
for subdir in sorted(os.listdir(dir_input)):
subrdir = dir_report + '/' + subdir
subdir = dir_input + '/' + subdir
if not os.path.isdir(subrdir):
os.mkdir(subrdir)
if os.path.isdir(subdir):
for subdir1 in sorted(os.listdir(subdir)):
subrdir1 = subrdir + '/' + subdir1 + '/'
subdir1 = subdir + '/' + subdir1+'/'
if os.path.isdir(subdir1):
acc_folder = 0
print(subdir1)
new_images, im_names = load_image_general(subdir1)
for i in range(new_images.shape[0]):
bimg = np.asarray([new_images[i]])
print(im_names[i])
real_jc = os.path.basename(im_names[i])[:-4].split('-')[-1]
res_str = real_jc
# result_predict = model.predict_classes(bimg, batch_size=1)[0]
probab_predict = model.predict_proba(bimg, batch_size=1)
top_index = np.argsort(probab_predict*-1)[0][:topk]
result_predict = top_index[0]
jc = label2chars[str(result_predict)]
print('predict {} -->{} '.format(result_predict, jc.encode('utf-8')))
res_str+=' vs '+jc
if real_jc==jc:
print('correct')
acc_folder+=1
else:
print('wrong')
fig = plt.figure()
a = fig.add_subplot(1, topk+1, 1)
a.set_title('Real input')
plt.imshow(new_images[i][0])
a = fig.add_subplot(1, topk+1, 2)
a.set_title('Predict Class')
plt.imshow(label2imgs[result_predict])
print('probability ', probab_predict)
for ii, index in enumerate(list(top_index[1:])):
jc = label2chars[str(index)]
print('predict {} -->{} '.format(index, jc.encode('utf-8')))
res_str += ' vs ' + jc
a = fig.add_subplot(1, topk+1, ii+3)
a.set_title('Suggest Class')
plt.imshow(label2imgs[index])
plt.show()
if not os.path.isdir(subrdir1):
os.mkdir(subrdir1)
if real_jc==label2chars[str(result_predict)]:
res_str+=' --> correct'
else:
res_str += ' --> wrong'
fig.savefig(subrdir1+'/reuslt{}.jpg'.format(os.path.basename(im_names[i])[:-4]))
with open(subrdir1+'/reuslt{}.txt'.format(format(os.path.basename(im_names[i])[:-4])),'w', encoding='utf-8') as f:
f.write(res_str)
with open(subrdir1 + '/reuslt.txt', 'w', encoding='utf-8') as f:
f.write(str(acc_folder/new_images.shape[0]))
f.write('\r\n')
f.write(str(acc_folder)+' vs '+str(new_images.shape[0]))
all_acc+=acc_folder
all_sam+=new_images.shape[0]
with open(dir_report + '/result.txt', 'w', encoding='utf-8') as f:
f.write(str(all_acc/all_sam))
f.write('\r\n')
f.write(str(all_acc) + ' vs ' + str(all_sam))
print(all_acc/all_sam)
def combine_data2(data1, data2, dataout, char2label1, label2char2):
char2label1 = json.load(open(char2label1))
label2char2 = json.load(open(label2char2))
X_train, y_train, X_test, y_test = pickle.load(open(data1, 'rb'))
print(y_train.shape)
print(X_train.shape)
print(X_train[0])
print(np.max(X_train[0]))
print(np.min(X_train[0]))
X_train2, y_train2, X_test2, y_test2 = pickle.load(open(data2, 'rb'))
print(y_train2.shape)
print(X_train2.shape)
X_train_all = np.concatenate((X_train, X_train2), axis=0)
X_test_all = np.concatenate((X_test, X_test2), axis=0)
print(label2char2)
y_train22=np.zeros(y_train2.shape[0], dtype=np.int32)
new_labels=len(char2label1)
for yind in range(y_train2.shape[0]):
ly = y_train2[yind]
if len(y_train2.shape)>1:
ly = np.argmax(y_train2[yind])
if label2char2[str(ly)] in char2label1:
y_train22[yind]= char2label1[label2char2[str(ly)]]
# print(label2char2[str(ly)])
# print(char2label1[label2char2[str(ly)]])
else:
print('new label')
y_train22[yind] =new_labels
char2label1[label2char2[str(ly)]] = new_labels
new_labels+=1
y_test22 = np.zeros(y_test2.shape[0], dtype=np.int32)
for yind in range(y_test2.shape[0]):
ly = y_test2[yind]
if len(y_test2.shape) > 1:
ly = np.argmax(y_test2[yind])
if label2char2[str(ly)] in char2label1:
y_test22[yind]= char2label1[label2char2[str(ly)]]
else:
y_test22[yind] =new_labels
char2label1[label2char2[str(ly)]] = new_labels
new_labels+=1
nlabel2chars={}
for k, v in char2label1.items():
nlabel2chars[v]=k
if len(y_train.shape)>1:
y_train_all = np.concatenate((np.argmax(y_train, axis=1), y_train22), axis=0)
else:
y_train_all = np.concatenate((y_train, y_train22), axis=0)
if len(y_test.shape) > 1:
y_test_all = np.concatenate((np.argmax(y_test,axis=1), y_test22), axis=0)
else:
y_test_all = np.concatenate((y_test, y_test22), axis=0)
print(y_train_all.shape)
print(y_test_all.shape)
# while True:
# ind = random.choice(range(X_train_all.shape[0]))
# print(nlabel2chars[y_train_all[ind]])
# plt.imshow(X_train_all[ind][0])
# plt.show()
pickle.dump((X_train_all, y_train_all, X_test_all, y_test_all), open(dataout, 'wb'),protocol=4)
json.dump(char2label1,open(dataout[:-4]+'.char2label.json','w'))
json.dump(nlabel2chars, open(dataout[:-4] + '.label2char.json', 'w'))
print(len(char2label1))
print(len(nlabel2chars))
make_gallery(dataout)
def combine_data3(data1, data2, dataout, cury=['kanhi','kata'], sub=1.0):
X_train, y_train, X_test, y_test = pickle.load(open(data1, 'rb'))
sublen=int(X_train.shape[0]*sub)